12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using Azure;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Filter;
- using HTEXLib.COMM.Helpers;
- using System.Text;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Hosting;
- using static TEAMModelOS.SDK.GroupListService;
- using TEAMModelOS.Controllers.Both;
- using CourseDto = TEAMModelOS.Controllers.Both.CourseDto;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("grouplist")]
- [ApiController]
- public class GroupListController : ControllerBase
- {
- private AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureStorageFactory _azureStorage;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- private const 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.optNo ,c.expire,c.qrcodeExpire,c.qrcodeDays ,c.grades ";
- public IConfiguration _configuration { get; set; }
- public GroupListController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option,
- AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration, AzureRedisFactory azureRedis)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- _serviceBus = serviceBus;
- _configuration = configuration;
- _azureStorage = azureStorage;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- _azureRedis=azureRedis;
- }
- //学生获取自己已经加入的名单。
- [ProducesDefaultResponseType]
- [HttpPost("get-student-joined-grouplist")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetMyCourseAndGroupList(JsonElement json)
- {
- var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- object scope = null;
- HttpContext?.Items.TryGetValue("Scope", out scope);
- int memberType = 2;
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- memberType = 2;
- // Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- memberType = 1;
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- memberType = 1;
- }
- List<GroupListGrp> groups = null;
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
- {
- groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" },time:time);
- }
- else {
- groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" });
- }
-
- return Ok(new { groups = groups });
- }
- [ProducesDefaultResponseType]
- [HttpPost("get-grouplist-nos")]
- public async Task<IActionResult> GetGroupListNos(JsonElement json)
- {
- GroupList groupList = null;
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- json.TryGetProperty("school", out JsonElement school);
- var queryNo = $"SELECT value(c) FROM c where c.no ='{_stuListNo}'";
- 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}") }))
- {
- groupList=item;
- break;
- }
- }
- if (groupList==null) {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: queryNo,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- groupList=item;
- break;
- }
- }
- if (groupList!=null)
- {
- return Ok(new {code=200, nos = groupList.members.Select(x => x.irs),optNo= groupList.optNo , limitCount=groupList.limitCount});
- }
- else {
- return Ok(new {code=404, nos =new List<string>() , optNo =0, limitCount =0});
- }
- }
- /// <summary>
- /// 扫码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("scan-code-join-list")]
- public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
- {
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- json.TryGetProperty("school", out JsonElement school);
- json.TryGetProperty("courseId", out JsonElement _courseId);
- int seatNo = 0;
- if (json.TryGetProperty("seatNo", out JsonElement _seatNo) ) {
- if (int.TryParse($"{_seatNo}", out int __seatNo)) {
- seatNo=__seatNo;
- }
- }
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("id_token", out JsonElement id_token);
- var jwt = new JwtSecurityToken(id_token.GetString());
- var id = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object name);
- jwt.Payload.TryGetValue("lang", out object lang);
- jwt.Payload.TryGetValue("picture", out object picture);
- try
- {
- TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
- }
- catch (CosmosException ex)
- {
- if (ex.Status == 404)
- {
- //如果沒有,則初始化Teacher基本資料到Cosmos
- TmdUser tmduser = new TmdUser
- {
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- id = id,
- pk = "Base",
- code = "Base",
- name = name?.ToString(),
- picture = picture?.ToString(),
- //创建账号并第一次登录IES5则默认赠送1G
- defaultSchool = null,
- schools = new List<TmdUser.School>(),
- lang= lang?.ToString(),
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
- }
- }
- int year = DateTimeOffset.UtcNow.Year;
- (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", id, type: 1, $"{school}", year, $"{name}", $"{picture}", $"{lang}", seatNo, $"{_courseId}");
- //没有TmdUser时
- if (data.status == 0)
- {
- await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
- List<string> ids = new List<string>();
- if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
- {
- ids.Add(data.stuList.creatorId);
- }
- else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
- {
- //通知管理员
- string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.IsNotEmpty())
- {
- string bizcode = "scan-join";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- // _coreAPIHttpService.PushNotify(idNameCodes, $"scan-join_groupList", Constant.NotifyType_IES5_Course, new Dictionary<string, object> { { "tmdid", id }, { "tmdname", name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- return Ok(new { data.stuList, data.status });
- }
- else
- {
- return Ok(new { data.status });
- }
- }
- /// <summary>
- /// 根据邀请码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher,student")]
- [HttpPost("input-code-join-list")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> InputCodeJoinList(JsonElement json)
- {
- string head_lang = _option.Location.Contains("China") ? "zh-cn" : "zh-tw";
- if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
- {
- head_lang = $"{_lang}";
- }
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
-
- int type = 0;
- string no = null;
- var client = _azureCosmos.GetCosmosClient();
- int year = DateTimeOffset.UtcNow.Year;
- object scope = null;
- HttpContext?.Items.TryGetValue("Scope", out scope);
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- type = 2;
- Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
- no = student.no;
- year = student.year;
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- type = 1;
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- type = 1;
- }
- int seatNo =0;
- (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", userid, type, school, year, _name, _picture, head_lang,seatNo);
- if (data.status == 0)
- {
- await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
- List<string> ids = new List<string>();
- if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
- {
- ids.Add(data.stuList.creatorId);
- }
- else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
- {
- //通知管理员
- string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.IsNotEmpty())
- {
- string bizcode = "scan-join";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_groupList", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdid", userid }, { "tmdname", _name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- return Ok(new { data.stuList, data.status });
- }
- else
- {
- return Ok(new { data.status });
- }
- }
- /// <summary>
- /// 获取名单的tags
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher,student")]
- [HttpPost("get-grouplist-tags")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistTags(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- object scope = null;
- StringBuilder sql = new StringBuilder($"SELECT {SummarySql} ,A1.tag FROM c " +
- $" join A1 in c. members where A1.id='{id}' and A1.tag<>null ");
- HttpContext?.Items.TryGetValue("Scope", out scope);
- if (!string.IsNullOrEmpty(school) && $"{scope}".Equals(Constant.ScopeStudent))
- {
- sql.Append($" and A1.code='{school}'");
- }
- List<dynamic> groupLists = new List<dynamic>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- groupLists.Add(item);
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
- GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- groupLists.Add(item);
- }
- return Ok(new { groupLists });
- }
- /// <summary>
- /// 获取发布活动的名单(弃用)
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("activity-grouplist")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetActivityGrouplist(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement tmdid);
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
- json.TryGetProperty("periodId", out JsonElement periodId);
- long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<GroupListGrp> groupLists = new List<GroupListGrp>();
- switch (true)
- {
- //我管理的
- case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
- //包含,学校的行政班,教学班
- json.TryGetProperty("type", out JsonElement _type);
- List<string> types = null;
- if (_type.ValueKind.Equals(JsonValueKind.Array))
- {
- types = _type.ToObject<List<string>>();
- }
- else if (_type.ValueKind.Equals(JsonValueKind.String))
- {
- types = new List<string> { $"{_type}" };
- }
- if (types.IsEmpty() || types.Contains("class"))
- {
- StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year,c.no FROM c where ( c.graduate = 0 or IS_DEFINED(c.graduate) = false )");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- classsql.Append($" and c.periodId='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
- {
- int scount = 0;
- HashSet<string> groupNames = new HashSet<string>();
- string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
- await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
- {
- if (!string.IsNullOrWhiteSpace(gp.groupName))
- {
- groupNames.Add(gp.groupName);
- }
- scount += 1;
- }
- ///行政班(学生搜寻classId动态返回)class
- GroupListGrp group = new GroupListGrp
- {
- id = item.id,
- code = $"GroupList-{schoolId}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = $"{schoolId}",
- type = "class",
- year = item.year,
- expire=0,
- groupName = groupNames,
- scount= scount
- };
- groupLists.Add(group);
- }
- }
- if (types.IsEmpty() || types.Contains("teach"))
- {
- //教学班
- StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach' and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- teachsql.Append($" and c.periodId='{periodId}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (types.IsEmpty() || types.Contains("research"))
- {
- //教研组
- StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (types.IsEmpty() || types.Contains("yxtrain"))
- {
- //研修名单
- StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- return Ok(new { groupLists });
- //弃用
- case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
- //我执教的
- //从学校的课程和个人课程搜寻与我相关的课程对应的名单。
- List<TeachCourse> teachCourses = new List<TeachCourse>();
- if (!string.IsNullOrEmpty($"{schoolId}"))
- {
- var schoolQuery = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- schoolQuery.Append($" and c.period.id='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<TeachCourse>(queryText: schoolQuery.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId}") }))
- {
- teachCourses.Add(item);
- }
- }
- var query = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
- GetItemQueryIterator<TeachCourse>(queryText: query.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{tmdid}") }))
- {
- teachCourses.Add(item);
- }
- var classIds = teachCourses.Select(x => x.schedule).Where(y => !string.IsNullOrEmpty(y.classId)).Select(x => x.classId).Distinct().ToList();
- var schedule = teachCourses.Where(y => !string.IsNullOrEmpty(y.schedule.stulist)).Distinct().ToList();
- //var schedule = teachCourses.Select(x => new { schedule = x.schedule.Where(mm=>!string.IsNullOrEmpty(mm.stulist)), scope = x.scope }).ToList();
- if (classIds.IsNotEmpty())
- {
- string insql = string.Join(",", classIds.Select(x => $"'{x}'"));
- query = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year FROM c where c.id in ({insql}) and ( c.graduate = 0 or IS_DEFINED(c.graduate) = false) ");
- ///行政班(学生搜寻classId动态返回)class
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: query.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{schoolId}") }))
- {
- HashSet<string> groupNames = new HashSet<string>();
- string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where c.classId='{item.id}'and c.groupName <>null";
- await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
- {
- groupNames.Add(gp.groupName);
- }
- GroupListGrp group = new GroupListGrp
- {
- id = item.id,
- code = $"GroupList-{schoolId}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = $"{schoolId}",
- type = "class",
- expire=0,
- year = item.year,
- groupName = groupNames
- };
- groupLists.Add(group);
- }
- }
- if (schedule.IsNotEmpty())
- {
- var privateList = schedule.Where(x => x.scope.Equals("private")).Select(x => x.schedule.stulist).Distinct();
- if (privateList.Count() > 0)
- {
- string insql = string.Join(",", privateList.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- var schoolList = schedule.Where(x => x.scope.Equals("school")).Select(x => x.schedule.stulist).Distinct();
- if (schoolList.Count() > 0)
- {
- List<GroupListDto> groups = new List<GroupListDto>();
- string insql = string.Join(",", schoolList.Select(x => $"'{x}'"));
- //我教的学校教学班,如果有过期的教学班则不返回
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql}) and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- }
- List<CourseGroupList> courseGroups = new List<CourseGroupList>();
- teachCourses.GroupBy(y => (y.id, y.name, y.scope, y.period.name, y.period.id, y.subject.name, y.subject.id)).ToList().ForEach(x =>
- {
- List<GroupListGrp> classIds = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.classId)).Select(b => b.schedule.classId).Contains(n.id)).ToList();
- List<GroupListGrp> stulists = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.stulist)).Select(b => b.schedule.stulist).Contains(n.id)).ToList();
- if (classIds == null)
- {
- classIds = new List<GroupListGrp>();
- }
- if (stulists != null)
- {
- classIds.AddRange(stulists);
- }
- CourseGroupList groupList = new CourseGroupList()
- {
- scope = x.Key.Item3,
- subject = x.Key.Item6,
- subjectId = x.Key.Item7,
- period = x.Key.Item4,
- periodId = x.Key.Item5,
- id = x.Key.Item1,
- name = x.Key.Item2,
- groups = classIds
- };
- courseGroups.Add(groupList);
- });
- return Ok(new { groupLists = courseGroups });
- case bool when $"{opt}".Equals("private", StringComparison.OrdinalIgnoreCase):
- //我个人的
- break;
- default:
- break;
- }
- return Ok(new { error = 1, msg = "参数异常" });
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-activity-grouplist")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> ActivityGrouplist(JsonElement json)
- {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
- json.TryGetProperty("periodId", out JsonElement periodId);
- long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- json.TryGetProperty("time", out JsonElement _time);
-
- switch (true)
- {
- //我管理的
- case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
- {
- List<GroupListGrp> groupLists = new List<GroupListGrp>();
- //包含,学校的行政班,教学班
- json.TryGetProperty("type", out JsonElement _type);
- List<string> types = null;
- if (_type.ValueKind.Equals(JsonValueKind.Array))
- {
- types = _type.ToObject<List<string>>();
- }
- else if (_type.ValueKind.Equals(JsonValueKind.String))
- {
- types = new List<string> { $"{_type}" };
- }
- if (types.IsEmpty() || types.Contains("class"))
- {
- StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year,c.no FROM c where ( c.graduate = 0 or IS_DEFINED(c.graduate) = false )");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- classsql.Append($" and c.periodId='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
- {
- int scount = 0;
- HashSet<string> groupNames = new HashSet<string>();
- string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
- await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{school}") }))
- {
- if (!string.IsNullOrWhiteSpace(gp.groupName))
- {
- groupNames.Add(gp.groupName);
- }
- scount += 1;
- }
- ///行政班(学生搜寻classId动态返回)class
- GroupListGrp group = new GroupListGrp
- {
- id = item.id,
- code = $"GroupList-{school}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = $"{school}",
- type = "class",
- year = item.year,
- expire=0,
- no=item.no,
- groupName = groupNames,
- scount= scount
- };
- groupLists.Add(group);
- }
- }
- if (types.IsEmpty() || types.Contains("teach"))
- {
- //教学班
- StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach' and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- teachsql.Append($" and c.periodId='{periodId}'");
- }
- 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 (types.IsEmpty() || types.Contains("research"))
- {
- //教研组
- StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: researchsql.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 (types.IsEmpty() || types.Contains("yxtrain"))
- {
- //研修名单
- StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: yxtrainsql.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));
- }
- }
- //long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- return Ok(new { groupLists });
- }
- case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
- {
- string sql = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
- List<KeyValuePair<string,CourseTask >> schoolTeacherTask = new List<KeyValuePair<string, CourseTask>>();
- List<KeyValuePair<string,CourseTask >> schoolAssistantTask = new List<KeyValuePair<string,CourseTask >>();
- List<KeyValuePair<string,CourseTask >> privateTeacherTask = new List<KeyValuePair<string,CourseTask >>();
- List<KeyValuePair<string,CourseTask >> privateAssistantTask = new List<KeyValuePair<string,CourseTask >>();
- List<CourseDto> schoolCourses = new List<CourseDto>();
- List<CourseDto> teahcerCourses = new List<CourseDto>();
- List<string> groupIds = new List<string>();
- if (!string.IsNullOrWhiteSpace(school))
- {
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- JsonElement _year = default, _semesterId = default, _periodId = default;
- if (!json.TryGetProperty("periodId", out _periodId)) return BadRequest();
- if (!json.TryGetProperty("year", out _year))
- {
- return BadRequest();
- }
- if (!json.TryGetProperty("semesterId", out _semesterId))
- {
- return BadRequest();
- }
- var period = schoolBase.period.Find(x => x.id.Equals($"{_periodId}"));
- //string date = SchoolService.GetOpensByStudyYearAndSemester(period.semesters, int.Parse($"{_year}"), $"{_semesterId}");
- sql = $"{sql} and c.year={_year} and c.semesterId='{_semesterId}'";
- HashSet<string> courseIds = new HashSet<string>();
- var resultSchool= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseTask>(sql, $"CourseTask-{school}");
- if (resultSchool.list.IsNotEmpty()) {
- resultSchool.list.ForEach(x => {
- var schedulesTeacher = x.schedules.Where(z =>!string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
- if (schedulesTeacher.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesTeacher.ToList();
- schoolTeacherTask.Add(new KeyValuePair<string,CourseTask >(x.courseId, courseTask));
- groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- }
- var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid) );
- if (schedulesAssistant.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesAssistant.ToList();
- schoolAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- groupIds.AddRange(schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- }
- });
- }
- if (courseIds.Any()) {
- string sqlCourse = $"select value c from c where c.id in ({string.Join(",",courseIds.Select(b=>$"'{b}'"))})";
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourse, $"CourseBase-{school}");
- if (result.list.IsNotEmpty())
- {
- foreach (var item in result.list)
- {
- List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
- var teacher = schoolTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
- if (teacher.Any()) {
- courseTaskDtos.AddRange(teacher.ToList());
- }
- var assistant= schoolAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
- if (assistant.Any()) {
- courseTaskDtos.AddRange(assistant.ToList());
- }
- schoolCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
- }
- }
- }
- }
-
- {
- HashSet<string> courseIds = new HashSet<string>();
- string sqlCoursePrivate = $"select value c.id from c where c.creatorId='{tmdid}'";
- var resultCourseBasePrivate = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<string>(sqlCoursePrivate, $"CourseBase");
- if (resultCourseBasePrivate.list.IsNotEmpty())
- {
- courseIds=new HashSet<string>(resultCourseBasePrivate.list);
- }
- string sqlprivate = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
- var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseTask>(sqlprivate, $"CourseTask");
- if (resultTeacher.list.IsNotEmpty())
- {
- resultTeacher.list.ForEach(x => {
- var schedulesTeacher = x.schedules.Where(z => !string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
- if (schedulesTeacher.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesTeacher.ToList();
- privateTeacherTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- }
- var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid));
- if (schedulesAssistant.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesAssistant.ToList();
- privateAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- groupIds.AddRange(schedulesAssistant.Where(z=>!string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- }
- });
-
- }
- if (courseIds.Any())
- {
- string sqlCourse = $"select value c from c where c.creatorId='{tmdid}' and c.id in ({string.Join(",", courseIds.Select(b => $"'{b}'"))})";
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseBase>(sqlCourse, $"CourseBase");
- if (result.list.IsNotEmpty())
- {
- foreach (var item in result.list)
- {
- List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
- var teacher = privateTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
- if (teacher.Any())
- {
- courseTaskDtos.AddRange(teacher.ToList());
- }
- var assistant = privateAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
- if (assistant.Any())
- {
- courseTaskDtos.AddRange(assistant.ToList());
- }
- teahcerCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
- }
- }
- }
- List<CourseGroupList> courseGroupLists = new List<CourseGroupList>();
- _coreAPIHttpService.check=false;
- var groupListDatas = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToHashSet().ToList(), school);
- foreach (var z in teahcerCourses)
- {
- CourseGroupList courseGroupList= new CourseGroupList
- {
- scope="private",
- id=z.courseBase.id,
- name=z.courseBase.name,
- periodId=z.courseBase.period?.id,
- period=z.courseBase.period?.name,
- subject=z.courseBase.subject?.name,
- subjectId= z.courseBase.subject?.id
- };
- foreach (var x in z.courseTasks)
- {
- foreach (var y in x.courseTask.schedules)
- {
- var data = groupListDatas.groups.Find(m => m.id.Equals(y.groupId));
- if (data!= null)
- {
- HashSet<string> groupName = data.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- GroupListGrp groupListGrp = new GroupListGrp(data, groupName);
- groupListGrp.teachType=x.type;
- courseGroupList.groups.Add(groupListGrp);
- }
- }
- }
- courseGroupLists.Add(courseGroupList);
- }
- foreach (var z in schoolCourses)
- {
- CourseGroupList courseGroupList = new CourseGroupList
- {
- scope="school",
- id=z.courseBase.id,
- name=z.courseBase.name,
- periodId=z.courseBase.period?.id,
- period=z.courseBase.period?.name,
- subject=z.courseBase.subject?.name,
- subjectId= z.courseBase.subject?.id
- };
- foreach (var x in z.courseTasks)
- {
- foreach (var y in x.courseTask.schedules)
- {
- var data = groupListDatas.groups.Find(m => m.id.Equals(y.groupId));
- if (data!= null) {
- HashSet<string> groupName = data.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- GroupListGrp groupListGrp = new GroupListGrp(data, groupName);
- groupListGrp.teachType=x.type;
- courseGroupList.groups.Add(groupListGrp);
- }
- }
- }
- courseGroupLists.Add(courseGroupList);
- }
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- foreach (var groups in courseGroupLists) {
- groups.groups.RemoveAll(z => z.expire>0 && z.expire<now);
- }
- return Ok(new { groupLists = courseGroupLists });
- }
- }
- }
- return Ok();
- }
- /// <summary>
- /// 根据任意名单id获取成员信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-members-listids")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetMembersListids(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- json.TryGetProperty("groupNames", out JsonElement groupNames);
- List<Dictionary<string, List<string>>> groupLists = new List<Dictionary<string, List<string>>>();
- if (groupNames.ValueKind.Equals(JsonValueKind.Array))
- {
- groupLists = groupNames.ToObject<List<Dictionary<string, List<string>>>>();
- }
- List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
- if (groupLists.Count > 0)
- {
- foreach (var gp in groupLists)
- {
- foreach (KeyValuePair<string, List<string>> pp in gp)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- List<string> listids = ids.ToObject<List<string>>();
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
- {
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps,time:time);
- return Ok(new { groups, members });
- }
- else
- {
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps);
- return Ok(new { groups, members });
- }
-
- }
- /// <summary>
- /// 根据任意名单id获取名单摘要信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-grouplist-listids")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetGroupListListids(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- List<string> listids = ids.ToObject<HashSet<string>>().ToList() ;
- List<GroupListDto> groups = null;
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
- {
- groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql, time: time);
- }
- else
- {
- groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql);
- }
-
- return Ok(new { groups });
- }
- /// <summary>
- /// 获取名单和成员信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplists-members")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistsMembers(JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement _tmdid);
- json.TryGetProperty("schoolId", out JsonElement _schoolId);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
- json.TryGetProperty("periodId", out JsonElement periodId);
- json.TryGetProperty("no", out JsonElement no);
-
- List<RGroupList> groups = new List<RGroupList>();
- string sqlSemester = "";
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
- {
- var groupListSemester = await GetGroupListSemester(client, null, $"{_schoolId}", $"{type}", $"{periodId}", $"{no}", time);
- if (groupListSemester.groupListDtos.IsNotEmpty())
- {
- groups.AddRange(groupListSemester.rgroupList);
- //排除掉已有的数据
- sqlSemester =$" and c.id not in ({string.Join(",", groupListSemester.groupListDtos.Select(z => $"'{z.id}'"))})";
- }
- }
- StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
- string tbname = "Teacher";
- string code = $"GroupList";
- if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- code = $"GroupList-{_schoolId}";
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- sql.Append($" and c.periodId='{periodId}'");
- }
- if (!string.IsNullOrEmpty($"{no}"))
- {
- sql.Append($" and c.no='{no}'");
- }
- }
- else
- {
- sql.Append($" and c.creatorId='{_tmdid}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- groups.Add(item);
- }
- (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{type}", groups, tbname, _dingDing, $"{_schoolId}");
- return Ok(new { groups = groupsData, members });
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- return Ok();
- }
- /// <summary>
- /// 获取名单列表
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplists")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplists(JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement _tmdid);
- json.TryGetProperty("schoolId", out JsonElement _schoolId);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
- json.TryGetProperty("periodId", out JsonElement periodId);
- json.TryGetProperty("no", out JsonElement no);
- List<GroupListDto> groups = new List<GroupListDto>();
- string sqlSemester = "";
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0) {
- var groupListSemester = await GetGroupListSemester(client, null, $"{_schoolId}", $"{type}", $"{periodId}", $"{no}", time);
- if (groupListSemester.groupListDtos.IsNotEmpty()) {
- groups.AddRange(groupListSemester.groupListDtos);
- //排除掉已有的数据
- sqlSemester =$" and c.id not in ({string.Join(",",groupListSemester.groupListDtos.Select(z=>$"'{z.id}'"))})";
- }
- }
- StringBuilder sql = new StringBuilder($"SELECT distinct {SummarySql} FROM c where c.type='{type}' {sqlSemester}");
-
- string tbname = "Teacher";
- string code = $"GroupList";
- if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- code = $"GroupList-{_schoolId}";
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- sql.Append($" and c.periodId='{periodId}'");
- }
- if (!string.IsNullOrEmpty($"{no}"))
- {
- sql.Append($" and c.no='{no}'");
- }
- }
- else
- {
- sql.Append($" and c.creatorId='{_tmdid}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<GroupListDto>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- groups.Add(item);
- }
- return Ok(new { groups });
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- return Ok();
- }
- /// <summary>
- /// 根据id,code获取学校行政班信息和学生信息。用于维护学生基本信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-classstudents-idcode")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetClassStudentsIdcode(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest();
- List<Student> students = new List<Student>();
- Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"Class-{_code}"));
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}", out long time) && time>0)
- {
- var groupListSemester = await GetGroupListSemester(client, new List<string> { id.GetString()}, $"{_code}",type:null, periodId:null,no:null, time);
- if (groupListSemester.rmembers.IsNotEmpty())
- {
-
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.id in ({string.Join(",",groupListSemester.rmembers.Select(z=>$"'{z.id}'"))}) ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
- {
- item.salt = null;
- item.pw = null;
- item.classId=clazz.id;
- students.Add(item);
- }
- }
- }
- if (!students.IsNotEmpty()) {
- try
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
- {
- item.salt = null;
- item.pw = null;
- students.Add(item);
- }
-
- }
- catch (Exception ex)
- {
- return Ok(new { error = 404, msg = "班级不存在!" });
- }
- }
- return Ok(new { classInfo = clazz, students = students });
- }
- //处理通用名单
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplist-idcode")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistIdcode(JsonElement json)
- {
- RGroupList groupList = null;
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("type", out JsonElement _type);
- json.TryGetProperty("code", out JsonElement _code);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
-
- string tbname = $"{scope}".Equals("private") ? "Teacher" : "School";
- string code = "";
- //根据时间获取历史名单
- if (json.TryGetProperty("time", out JsonElement _time) && long.TryParse($"{_time}",out long time) && time>0 && !string.IsNullOrWhiteSpace($"{_code}")){
- var semesterGroupList = await GetGroupListSemester(client, new List<string> { id.GetString()}, _code.GetString(),type:null,periodId:null,no:null, time);
- if (semesterGroupList.rgroupList.IsNotEmpty()) {
- groupList=semesterGroupList.rgroupList.First();
- }
- }
- if (groupList==null) {
- if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
- {
- if ($"{scope}".Equals("private"))
- {
- //私人名单
- code = "GroupList";
- }
- else
- {
- //学校自定义名单
- code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
- }
- groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<RGroupList>($"{id}", new PartitionKey($"{code}"));
- }
- else if ($"{_type}".Equals("class"))
- {
- try
- {
- code = $"Class-{_code}";
- Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"{code}"));
- if (clazz != null)
- {
- List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
- {
- students.Add(item);
- }
- ///行政班(学生搜寻classId动态返回)class
- List<RMember> smembers = students.Where(x => x.classId.Equals(clazz.id)).Select(y => new RMember { id = y.id, code = $"{_code}", name = y.name, type = 2, picture = y.picture, no = y.no, classId = y.classId, groupId = y.groupId, groupName = y.groupName }).ToList();
- groupList = new RGroupList
- {
- id = clazz.id,
- code = $"GroupList-{clazz.school}",
- name = clazz.name,
- periodId = clazz.periodId,
- pk = "GroupList",
- year = clazz.year,
- expire = 0,
- school = clazz.school,
- scope = "school",
- type = "class",
- scount = smembers.Count,
- no = clazz.no,
- leader = clazz.teacher?.id,
- members = smembers,
- };
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { groupList });
- }
- }
- }
- (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{groupList.type}", new List<RGroupList> { groupList }, tbname, _dingDing, $"{_code}");
- groupList = groupsData.FirstOrDefault();
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n {json}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { groupList });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n{json}", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { groupList });
- }
- /// <summary>
- /// 保存或更新通用名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upsert-grouplist")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> UpsertGroupList(JsonElement json)
- {
- GroupList list = json.ToObject<GroupList>();
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- if (string.IsNullOrEmpty(list.type))
- {
- return BadRequest();
- }
- list.year = list.year > 0 ? list.year : DateTimeOffset.UtcNow.Year;
- list.ttl = -1;
- list.creatorId = userid;
- list.school = string.IsNullOrEmpty(list.school) ? school : list.school;
- list.pk = "GroupList";
- if (list.scope.Equals("private"))
- {
- //私人名单
- list.code = "GroupList";
- list.school = null;
- //只有开启审核,且设置天数大于零,且之前没有设置过期时间的时候才会重新设置过期时间。
- GroupList dblist = null;
- if (!string.IsNullOrWhiteSpace(list.id))
- {
- var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(list.id, new PartitionKey(list.code));
- if (response.Status==200)
- {
- dblist = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
- }
- }
- if (list.review==1)
- {
- if (list.qrcodeDays>0)
- {
-
- if (dblist!=null)
- {
- //更新过期时间
- if (dblist.qrcodeDays!=list.qrcodeDays)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
- }
- else
- {
- //相同
- if (dblist.review==0 && list.review==1)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
- }
- else
- {
- list.qrcodeExpire=dblist.qrcodeExpire;
- }
- }
- }
- else
- {
- if (list.qrcodeExpire<=0)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- }
- }
- }
- else
- {
- return Ok(new { error = 400, msg = "必须设置二维码过期天数!" });
- }
- }
- else
- {
- if (dblist!=null && dblist.review==1) {
- list.qrcodeDays = 1;
- list.qrcodeExpire = 0;
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
- List<GroupWaitingList> groupWaitingLists = new List<GroupWaitingList>();
- foreach (var rcd in datas)
- {
- var value = rcd.Value.ToString().ToObject<GroupWaitingList>();
- if (value!=null) { groupWaitingLists.Add(value); }
- }
- if (groupWaitingLists.IsNotEmpty()) {
- var takeCount = list.limitCount-dblist.members.Count;
- if (takeCount>0)
- {
- var takes = groupWaitingLists.OrderBy(x => x.applyTime).Take(takeCount);
- if (takes!=null && takes.Count()>0)
- {
- foreach (var t in takes)
- {
- GroupListService.JoinList(list, t.userid, t.type, t.school, t.year,t.seatNo);
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string stuFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=0;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
- }
- }
- //未自动加入的,直接拒绝
- var untakes = groupWaitingLists.Except(takes);
- if (untakes!=null && untakes.Count()>0)
- {
- foreach (var t in takes)
- {
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string stuFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=1;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
- }
- }
- }
- }
- }
- else
- {
- //已经加满,删除候选
- foreach (var t in groupWaitingLists)
- {
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string stuFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, stuFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=1;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, stuFiled, value.ToJsonString());
- }
- }
- }
- }
- await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
- }
- }
- }
- else
- {
- //学校自定义名单
- list.code = !list.code.StartsWith("GroupList-") ? $"GroupList-{list.code}" : list.code;
- }
- switch (true)
- {
- //普通学生名单(包含学校教学班名单,个人课程名单),其中学生成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("teach", StringComparison.OrdinalIgnoreCase):
- list.type = "teach";
- list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //教研组名单,只有加入学校的老师名单 成员账号类型是醍摩豆ID,保存在学校表,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("research", StringComparison.OrdinalIgnoreCase):
- list.type = "research";
- list.scope = "school";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //个人好友名单,成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList
- case bool when $"{list.type}".Equals("friend", StringComparison.OrdinalIgnoreCase):
- list.type = "friend";
- list.scope = "private";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //社交群组类型(包含学校交流群组,个人交流群组),成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("group", StringComparison.OrdinalIgnoreCase):
- list.type = "group";
- list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //研修类型成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("yxtrain", StringComparison.OrdinalIgnoreCase):
- list.type = "yxtrain";
- list.scope = "school";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- default:
- return Ok(new { error = 400, msg = "参数错误!" });
- }
- return Ok(new { list });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/upsert-grouplist()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //删除名单
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete-grouplist")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> DeleteGroupList(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- string tbname = "";
- string datacode = "";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- datacode = $"GroupList-{code}";
- }
- else
- {
- tbname = "Teacher";
- datacode = $"GroupList";
- }
- try
- {
- await GroupListService.DeleteGrouplistEvent($"{id}", datacode, tbname, client, _configuration, _serviceBus);
- }
- catch (Exception ex) { }
- return Ok(new { id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/delete-grouplist()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { error = 400 });
- }
- }
- /// <summary>
- /// 保存或更新通用名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("upsert-group-member")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> UpsertGroupMember(JsonElement json)
- {
- if (!json.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
- if (!json.TryGetProperty("scope", out JsonElement _scope)) { return BadRequest(); }
- if (!json.TryGetProperty("id", out JsonElement _id)) { return BadRequest(); }
- if (!json.TryGetProperty("code", out JsonElement _code)) { return BadRequest(); }
- if (!json.TryGetProperty("type", out JsonElement _type)) { return BadRequest(); }
- try
- {
- GroupList groupList = null;
- string tbname = $"{_scope}".Equals("private") ? "Teacher" : "School";
- string code = "";
- if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
- {
- if ($"{_scope}".Equals("private"))
- {
- //私人名单
- code = "GroupList";
- }
- else
- {
- //学校自定义名单
- code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
- }
- groupList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>($"{_id}", new PartitionKey($"{code}"));
- }
- switch (true)
- {
- case bool when $"{_opt}".Equals("up-nickname", StringComparison.OrdinalIgnoreCase) && json.TryGetProperty("members", out JsonElement _members):
- var members = _members.ToObject<List<Member>>();
- List<Member> updateSuccess = new List<Member>();
- List<Member> updateFailed = new List<Member>();
- members.ForEach(x =>
- {
- var member = groupList.members.Find(z => z.type == x.type && z.id.Equals(x.id));
- if (member != null)
- {
- member.nickname = x.nickname;
- updateSuccess.Add(member);
- }
- else
- {
- updateFailed.Add(x);
- }
- });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<GroupList>(groupList, $"{_id}", new PartitionKey(code));
- return Ok(new { updateSuccess, updateFailed });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location},更新名单成员信息异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- return Ok();
- }
- /// <
- /// summary>
- /// 处理名单审核
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("review")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> review(JsonElement request)
- {
- (string userId, _, _, string school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
-
- var client = _azureCosmos.GetCosmosClient();
- switch (true)
- {
- //待加入列表
- case bool when $"{grant_type}".Equals("waitlist", StringComparison.OrdinalIgnoreCase):
- {
- if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- //string tbname = ($"{_scope}".Equals("school")) ? Constant.School : Constant.Teacher;
- //string code = $"";
- string key = $"GroupList:GroupWaitingList:{_scope}:{_id}";
- var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
- List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
- if (datas!=null && datas.Length>0)
- {
- foreach (var data in datas)
- {
- var group = data.Value.ToString().ToObject<GroupWaitingList>();
- if (group!=null)
- {
- waitingLists.Add(group);
- }
- }
- }
- return Ok(new { waitingLists });
- }
- //处理审核
- case bool when $"{grant_type}".Equals("process", StringComparison.OrdinalIgnoreCase):
- {
- if (!request.TryGetProperty("id", out JsonElement _id)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement _scope)) return BadRequest();
- if (!request.TryGetProperty("pass", out JsonElement _pass)) return BadRequest();
- if (!request.TryGetProperty("members", out JsonElement _members)) return BadRequest();
- var members = _members.ToObject<List<Member>>();
- string tbname = $"{_scope}".Equals("school") ? Constant.School : Constant.Teacher;
- string code = $"{_scope}".Equals("school") ?$"GroupList-{school}" : "GroupList";
- string key = $"GroupList:GroupWaitingList:{_scope}:{_id}";
- List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
- if (members.IsNotEmpty()) {
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(_id.ToString(), new PartitionKey(code));
- if (response.Status==200)
- {
- GroupList groupList = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
- bool add=false;
- foreach (var member in members)
- {
- string filed = $"{member.type}".Equals("2") ? $"{school}_{member.id}" : member.id;
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(key, filed);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{member.id}" : $"GroupList:StudentWaitinglist:{member.id}";
- string sutFiled = $"{_scope}:{_id}";
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if ($"{_pass}".Equals("0"))
- {
- //通过
- if (now>value.qrcodeExpire)
- {
- value.status=2;
- }
- else
- {
- if (groupList!=null)
- {
- var mb = groupList.members.Find(x => x.type==value.type && x.id.Equals(value.userid));
- if (mb== null)
- {
- var joindata = GroupListService.JoinList(groupList, value.userid, value.type, value.school, value.year);
- if (joindata.status==0) {
- add=true;
- }
- }
- }
- value.status=0;
- }
- await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
- waitingLists.Add(value);
-
- }
- else if ($"{_pass}".Equals("1"))
- {
- //拒绝
- value.status=1;
- await _azureRedis.GetRedisClient(8).HashDeleteAsync(key, filed);
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
- waitingLists.Add(value);
- }
- else
- {
- return BadRequest(new { code = 1, msg = "参数错误" });
- }
- }
- }
- if (add)
- {
- await GroupListService.UpsertList(groupList, _azureCosmos, _configuration, _serviceBus);
- }
- }
- }
- return Ok(new { waitingLists });
- }
- //审核结果,学生端获取到被拒绝的,或者过期的自动删除,未被审核的保存
- case bool when $"{grant_type}".Equals("result", StringComparison.OrdinalIgnoreCase):
- {
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{userId}" : $"GroupList:StudentWaitinglist:{userId}";
- var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(stuKey);
- List<GroupWaitingList> waitingLists = new List<GroupWaitingList>();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (datas!=null && datas.Length>0)
- {
- foreach (var data in datas)
- {
- var group = data.Value.ToString().ToObject<GroupWaitingList>();
- if (group!=null)
- {
- waitingLists.Add(group);
- if (group.status!=-1)
- {
- await _azureRedis.GetRedisClient(8).HashDeleteAsync(stuKey, $"{group.groupScope}:{group.groupId}");
- }
- else
- {
- if (now>group.qrcodeExpire)
- {
- group.status=2;
- await _azureRedis.GetRedisClient(8).HashDeleteAsync(stuKey, $"{group.groupScope}:{group.groupId}");
- }
- }
- }
- }
- }
- return Ok(new { waitingLists });
- }
- }
- return BadRequest();
- }
-
- /// <
- /// summary>
- ///
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("backups-all")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> BackupsAll(JsonElement json) {
- string sqlschool = "select value c from c ";
- var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sqlschool, "Base");
- List<School> schools = resultSchool.list;
- List<GroupListSemester> listSemesters= new List<GroupListSemester>();
- foreach (var school in schools) {
- string sqlclass = $"select value c from c where c.year<2023 ";
- var resultClass = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sqlclass, $"Class-{school.id}");
- if (resultClass.list.IsNotEmpty()) {
- var data = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, resultClass.list.Select(z=>z.id).ToList(), school.id);
- if (data.groups.IsNotEmpty()) {
- foreach(var group in data.groups)
- {
- if(group.members.IsNotEmpty())
- {
- var period = school.period.Find(z => z.id.Equals(group.periodId));
- if (period != null)
- {
- {
- //2023-06-01
- var dataSemester = SchoolService.GetSemester(period, 1688140800000);
- string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
- string code = $"GroupListSemester-{school.id}";
- GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
- groupListSemester.id = id;
- groupListSemester.code = code;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=dataSemester.currSemester.id;
- groupListSemester.groupListId=group.id;
- groupListSemester.studyYear=dataSemester.studyYear;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- listSemesters.Add(groupListSemester);
- }
- {
- //2022-11-01
- var dataSemester = SchoolService.GetSemester(period, 1667232000000);
- string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
- string code = $"GroupListSemester-{school.id}";
- GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
- groupListSemester.id = id;
- groupListSemester.code = code;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=dataSemester.currSemester.id;
- groupListSemester.groupListId=group.id;
- groupListSemester.studyYear=dataSemester.studyYear;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- listSemesters.Add(groupListSemester);
- }
- //{
- // //2022-06-01
- // var dataSemester = SchoolService.GetSemester(period, 1654012800000);
- // string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
- // string code = $"GroupListSemester-{school.id}";
- // GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
- // groupListSemester.id = id;
- // groupListSemester.code = code;
- // groupListSemester.pk="GroupListSemester";
- // groupListSemester.semesterId=dataSemester.currSemester.id;
- // groupListSemester.groupListId=group.id;
- // groupListSemester.studyYear=dataSemester.studyYear;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- // listSemesters.Add(groupListSemester);
- //}
- //{
- // //2021-11-01
- // var dataSemester = SchoolService.GetSemester(period, 1635696000000);
- // string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
- // string code = $"GroupListSemester-{school.id}";
- // GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
- // groupListSemester.id = id;
- // groupListSemester.code = code;
- // groupListSemester.pk="GroupListSemester";
- // groupListSemester.semesterId=dataSemester.currSemester.id;
- // groupListSemester.groupListId=group.id;
- // groupListSemester.studyYear=dataSemester.studyYear;
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- // listSemesters.Add(groupListSemester);
- //}
- }
- }
- }
- }
- }
- }
- return Ok(listSemesters.Count);
- }
- /// <
- /// summary>
- ///
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
-
- [HttpPost("process-grouplist-backups")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> Backups(JsonElement json) {
- if (!json.TryGetProperty("grant_type", out JsonElement _grant_type)) return BadRequest();
- switch (true) {
- case bool when $"{_grant_type}".Equals("ignore", StringComparison.OrdinalIgnoreCase):
- {
- json.TryGetProperty("keys", out JsonElement _keys);
- List<string> keys = _keys.ToObject<List<string>>();
- foreach (var key in keys) {
- var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
- if (data.HasValue)
- {
- SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
- notify.ignore=1;
- await _azureRedis.GetRedisClient(8).StringSetAsync(key, notify.ToJsonString());
- //3天 * 24 =72小时
- #if DEBUG
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(0, 0, 60));
- #else
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(72, 0, 0));
- #endif
- }
- }
- return Ok(new { code = 200 });
- }
- case bool when $"{_grant_type}".Equals("sync_edited", StringComparison.OrdinalIgnoreCase):
- {
- try {
- json.TryGetProperty("editedStus", out JsonElement _editedStus);
- List<GroupListSemester> groupListSemesters = _editedStus.ToObject<List<GroupListSemester>>();
- List<RMember> syncedMembers = new List<RMember>();
- foreach (var z in groupListSemesters)
- {
- z.code=$"GroupListSemester-{z.school}";
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(z.id, new PartitionKey(z.code));
- if (response.Status==200)
- {
- GroupListSemester groupListSemester = JsonDocument.Parse(response.Content).ToObject<GroupListSemester>();
- var notIn = z.members.ExceptBy(groupListSemester.members.Select(z => z.id), x => x.id);
- if (notIn!=null && notIn.Count()>0)
- {
- syncedMembers.AddRange(notIn);
- groupListSemester.members.AddRange(notIn);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(groupListSemester, new PartitionKey(z.code));
- }
- }
- else
- {
- z.scope="school";
- z.type="class";
- z.pk= "GroupListSemester";
- syncedMembers.AddRange(z.members);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(z, new PartitionKey(z.code));
- }
- }
- return Ok(new { code = 200 , syncedMembers });
- }
- catch (Exception ex ){
- await _dingDing.SendBotMsg($"{_option.Location},{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return Ok(new { code = 500 });
- }
- }
- }
- return Ok(new { code=400 });
- }
- //新学年8.1号开学 ,第二学期开学2.17,设置提示区间60天
- //2023-8-7 type = "studyYearStarted";新学年已经开始
- //2023-10-7 type = "";不提示
- //2024-1-20 type = "semesterEnding";本学期即将结束
- //2024-3-20 type = "semesterStarted";新学期已经开始
- //2024-4-20 type = "";不提示
- //2024-7-20 type = "studyYearEnding";本学年即将结束
- /// <
- /// summary>
- /// 检查当前学期的开学时间和学期结束时间
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("check-class-sync")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> CheckSemesters(JsonElement json)
- {
- if (!json.TryGetProperty("schoolId", out JsonElement _schoolId)) { return BadRequest(); }
- School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(_schoolId.GetString(), new PartitionKey("Base"));
- List<dynamic> periodNotify = new List<dynamic>();
- foreach (var period in school.period) {
- if (period!=null)
- {
- //var semesterInfo = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
- var semesterInfo = SchoolService.GetSemester(period, time:$"{json.GetProperty("time")}");
- var start = period.semesters.Where(z => z.start==1).FirstOrDefault();
- if (start!=null)
- {
- var alreadySemester = semesterInfo.date.Subtract(semesterInfo.currSemesterDate);
- var soonSemester = semesterInfo.nextSemester.Subtract(semesterInfo.date);
- var semesterStarted = Math.Abs((int)alreadySemester.TotalDays);
- var semesterEnding = Math.Abs((int)soonSemester.TotalDays);
- string currStudyYear = $"{semesterInfo.studyYear}-{start.month}-{start.day}";
- string nextStudyYear = $"{(semesterInfo.studyYear+1)}-{start.month}-{start.day}";
- DateTimeOffset.TryParse(currStudyYear, out DateTimeOffset currYear);
- DateTimeOffset.TryParse(nextStudyYear, out DateTimeOffset nextYear);
- var alreadyYear = semesterInfo.date.Subtract(currYear);
- var soonYear = nextYear.Subtract(semesterInfo.date);
- var studyYearStarted = Math.Abs((int)alreadyYear.TotalDays);
- var studyYearEnding = Math.Abs((int)soonYear.TotalDays);
- string type = string.Empty;
- //开始天数小于60天
- if (semesterStarted<=60)
- {
- type = "semesterStarted";
- }
- //结束天数小于60天
- if (semesterEnding<=60)
- {
- type = "semesterEnding";
- }
- //开始天数小于60天
- if (studyYearStarted<=60)
- {
- type = "studyYearStarted";
- }
- //结束天数小于60天
- if (studyYearEnding<=60)
- {
- type = "studyYearEnding";
- }
- string sqlClass = string.Empty;
- string idPrefix = string.Empty;
- string key =string.Empty;
- var lastSemesterDate = semesterInfo.currSemesterDate.AddDays(-1);
- var lastSemesterInfo = SchoolService.GetSemester(period, lastSemesterDate.ToUnixTimeMilliseconds());
- if (type.Contains("Started"))
- { //semesterStarted studyYearStarted
- //获取上学期的任意时间,以获取学年,学期信息。
- sqlClass = $"select value c from c where c.year >={lastSemesterInfo.studyYear-period.grades.Count+1} and c.year <={lastSemesterInfo.studyYear} and c.periodId='{period.id}' ";
- idPrefix=$"{lastSemesterInfo.studyYear}-{lastSemesterInfo.currSemester.id}-";
- key = $"SemesterStudyYearNotify:{_schoolId}:{lastSemesterInfo.studyYear}:{lastSemesterInfo.currSemester.id}:{type}";
- }
- //Ending //semesterEnding studyYearEnding
- else
- {
- sqlClass = $"select value c from c where c.year >={semesterInfo.studyYear-period.grades.Count+1} and c.year <={semesterInfo.studyYear} and c.periodId='{period.id}' ";
- idPrefix=$"{semesterInfo.studyYear}-{semesterInfo.currSemester.id}-";
- key = $"SemesterStudyYearNotify:{_schoolId}:{semesterInfo.studyYear}:{semesterInfo.currSemester.id}:{type}";
- }
- var keyExists = await _azureRedis.GetRedisClient(8).KeyExistsAsync(key);
- if (keyExists)
- {
- var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
- if (data.HasValue)
- {
- SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
- if (notify.ignore==1)
- {
- //忽略提示
- type="";
- }
- else
- {
- //已经处理过的不再处理
- if (notify.process==1)
- {
- type="";
- }
- }
- }
- }
- else
- {
- await _azureRedis.GetRedisClient(8).StringSetAsync(key, new SemesterStudyYearNotify { studyYear=semesterInfo.studyYear, semester=semesterInfo.currSemester.id, ignore=0, type=type }.ToJsonString());
- //60天 * 24 =1440小时
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(1440, 0, 0));
- }
- /*
- //2022-11-01
- var dataSemester = SchoolService.GetSemester(period, 1667232000000);
- string id = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{group.id}";
- string code = $"GroupListSemester-{school.id}";
- GroupListSemester groupListSemester = group.ToJsonString().ToObject<GroupListSemester>();
- groupListSemester.id = id;
- groupListSemester.code = code;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=dataSemester.currSemester.id;
- groupListSemester.groupListId=group.id;
- groupListSemester.studyYear=dataSemester.studyYear;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- listSemesters.Add(groupListSemester);
- */
- //已同步的学生。
- List<Student> syncedStus = new List<Student>();
- //未同步的学生
- //List<dynamic> unsyncStus = new List<dynamic>();
- //有调整的学生
- List<dynamic> editedStus = new List<dynamic>();
- if (!string.IsNullOrWhiteSpace(type))
- {
- var resultClasses = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Class>(sqlClass, $"Class-{school.id}");
- if (resultClasses.list.IsNotEmpty()) {
- string sqlStudents = $"select value c from c where c.classId in ({string.Join(",", resultClasses.list.Select(z => $"'{z.id}'"))})";
- var resultStudents = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(sqlStudents, $"Base-{school.id}");
- if (resultStudents.list.IsNotEmpty()) {
- foreach (var clazz in resultClasses.list) {
- string id = $"{idPrefix}{clazz.id}";
- string code = $"GroupListSemester-{school.id}";
- var studentList = resultStudents.list.FindAll(z => z.classId.Equals(clazz.id));
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(id, new PartitionKey(code));
- if (response.Status==200)
- {
- bool changeGroupListSemester = false;
- GroupListSemester groupListSemester = JsonDocument.Parse(response.Content).ToObject<GroupListSemester>();
- var stuslist = studentList.ExceptBy(groupListSemester.members.Select(z=>z.id), x => x.id);
- //学年学期结束 不用处理有更新编辑的学生,直接批量处理。
- if (type.Contains("Ending", StringComparison.OrdinalIgnoreCase)) {
- if (stuslist.Any() && stuslist.Count()>0)
- {
- //var stus = new
- //{
- // id=id ,
- // status=200,
- // type,
- // periodId = period.id,
- // periodName = period.name,
- // classId = clazz.id,
- // className = clazz.name,
- // students = stuslist.Select(z => new { z.id, z.name, z.picture, z._ts })
- //};
- groupListSemester.members.AddRange(stuslist.Select(z => new RMember {
- id= z.id,
- code=z.schoolId,
- name =z.name,
- type=2,
- picture=z.picture,
- gender=z.gender,
- no=z.no,
- irs=z.irs,
- classId=z.classId,
- groupId=z.groupId,
- groupName=z.groupName,
- graduate=z.graduate,
- year=z.year,
- periodId=z.periodId,
- }));
- changeGroupListSemester = true;
- }
- }
- if (type.Contains("Started", StringComparison.OrdinalIgnoreCase))
- {
- if (stuslist.Any() && stuslist.Count()>0) {
- //获取开学时间
- var kxdata = $"{semesterInfo.currSemesterDate.Year}-{semesterInfo.currSemester.month}-{semesterInfo.currSemester.day}";
- DateTimeOffset.TryParse(kxdata, out DateTimeOffset kxData);
- long time = kxData.ToUnixTimeSeconds();
- var editStu = stuslist.Where(z => z._ts>=time);
- if (editStu!=null && editStu.Count()>0) {
- var stus = new
- {
- id = id,
- status = 404,
- type,
- periodId = period.id,
- periodName = period.name,
- groupListId = clazz.id,
- name = clazz.name,
- className = clazz.name,
- school = school.id,
- no = clazz.no,
- year = clazz.year,
- studyYear = lastSemesterInfo.studyYear,
- semesterId = lastSemesterInfo.currSemester.id,
- leader = clazz.teacher?.id,
- grades = new List<int> { clazz.year },
- members = editStu.Select(z => new {
- z.id,
- code = z.schoolId,
- gender = z.gender,
- no = z.no,
- irs = z.irs,
- classId = z.classId,
- groupId = z.groupId,
- groupName = z.groupName,
- graduate = z.graduate,
- periodId = z.periodId,
- z.name,
- z.picture,
- z._ts,
- z.year
- })
- };
- editedStus.Add(stus);
- }
- var uneditStu = studentList.Where(z => z._ts<time);
- if (uneditStu!=null &&uneditStu.Count()>0)
- {
- //var stus = new
- //{
- // id = id,
- // status = 200,
- // type,
- // periodId = period.id,
- // periodName = period.name,
- // classId = clazz.id,
- // className = clazz.name,
- // students = uneditStu.Select(z => new { z.id, z.name, z.picture, z._ts })
- //};
- groupListSemester.members.AddRange(uneditStu.Select(z => new RMember
- {
- id= z.id,
- code=z.schoolId,
- name =z.name,
- type=2,
- picture=z.picture,
- gender=z.gender,
- no=z.no,
- irs=z.irs,
- classId=z.classId,
- groupId=z.groupId,
- groupName=z.groupName,
- graduate=z.graduate,
- year=z.year,
- periodId=z.periodId,
- }));
- changeGroupListSemester = true;
- }
- }
- }
- if (changeGroupListSemester) {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(groupListSemester, new PartitionKey(code));
- }
- }
- else
- {
- //学年学期结束 不用处理有更新编辑的学生,直接批量处理。
- if (type.Contains("Ending", StringComparison.OrdinalIgnoreCase))
- {
- //var stus = new
- //{
- // id = id,
- // status = 404,
- // type,
- // periodId = period.id,
- // periodName = period.name,
- // classId = clazz.id,
- // className = clazz.name,
- // students = studentList.Select(z => new { z.id, z.name, z.picture, z._ts })
- //};
- GroupListSemester groupListSemester = new GroupListSemester();
- groupListSemester.id = id;
- groupListSemester.name=clazz.name;
- groupListSemester.no=clazz.no;
- groupListSemester.periodId=period.id;
- groupListSemester.scope="school";
- groupListSemester.school=school.id;
- groupListSemester.type="class";
- groupListSemester.year=clazz.year;
- groupListSemester.studyYear=semesterInfo.studyYear;
- groupListSemester.code = code;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=semesterInfo.currSemester.id;
- groupListSemester.groupListId=clazz.id;
- groupListSemester.members.AddRange(studentList.Select(z => new RMember
- {
- id= z.id,
- code=z.schoolId,
- name =z.name,
- type=2,
- picture=z.picture,
- gender=z.gender,
- no=z.no,
- irs=z.irs,
- classId=z.classId,
- groupId=z.groupId,
- groupName=z.groupName,
- graduate=z.graduate,
- year=z.year,
- periodId=z.periodId,
- }));
- groupListSemester.scount = groupListSemester.members.Count();
- groupListSemester.leader=clazz.teacher?.id;
- groupListSemester.grades.Add(clazz.year);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- }
- //开始则需要处理当前学期有变更的学生数据
- if (type.Contains("Started", StringComparison.OrdinalIgnoreCase))
- {
- //获取开学时间
- var kxdata = $"{semesterInfo.currSemesterDate.Year}-{semesterInfo.currSemester.month}-{semesterInfo.currSemester.day}";
- DateTimeOffset.TryParse(kxdata, out DateTimeOffset kxData);
- long time = kxData.ToUnixTimeSeconds();
- //在开学日期之后编辑的学生
- var editStu = studentList.FindAll(z => z._ts>=time);
- if (editStu.IsNotEmpty()) {
- var stus = new
- {
- id = id,
- status = 404,
- type,
- periodId = period.id,
- periodName = period.name,
- groupListId = clazz.id,
- name = clazz.name,
- className = clazz.name,
- school = school.id,
- no = clazz.no,
- year = clazz.year,
- studyYear = lastSemesterInfo.studyYear,
- semesterId = lastSemesterInfo.currSemester.id,
- leader = clazz.teacher?.id,
- grades = new List<int> { clazz.year },
- members = editStu.Select(z => new { z.id,
- code = z.schoolId,
- gender = z.gender,
- no = z.no,
- irs = z.irs,
- classId = z.classId,
- groupId = z.groupId,
- groupName = z.groupName,
- graduate = z.graduate,
- periodId = z.periodId,
- z.name, z.picture, z._ts,z.year })
- };
- editedStus.Add(stus);
- }
- //在开学日期之前编辑的学生
- var uneditStu = studentList.FindAll(z => z._ts<time);
- if (uneditStu.IsNotEmpty()) {
- //var stus = new
- //{
- // id = id,
- // status = 404,
- // type,
- // periodId = period.id,
- // periodName = period.name,
- // classId = clazz.id,
- // className = clazz.name,
- // students = uneditStu.Select(z => new { z.id, z.name, z.picture, z._ts })
- //};
- GroupListSemester groupListSemester = new GroupListSemester();
- groupListSemester.id = id;
- groupListSemester.name=clazz.name;
- groupListSemester.no=clazz.no;
- groupListSemester.periodId=period.id;
- groupListSemester.scope="school";
- groupListSemester.school=school.id;
- groupListSemester.type="class";
- groupListSemester.year=clazz.year;
- groupListSemester.studyYear=lastSemesterInfo.studyYear;
- groupListSemester.code = code;
- groupListSemester.pk="GroupListSemester";
- groupListSemester.semesterId=lastSemesterInfo.currSemester.id;
- groupListSemester.groupListId=clazz.id;
- groupListSemester.members.AddRange(studentList.Select(z => new RMember
- {
- id= z.id,
- code=z.schoolId,
- name =z.name,
- type=2,
- picture=z.picture,
- gender=z.gender,
- no=z.no,
- irs=z.irs,
- classId=z.classId,
- groupId=z.groupId,
- groupName=z.groupName,
- graduate=z.graduate,
- year=z.year,
- periodId=z.periodId,
- }));
- groupListSemester.scount = groupListSemester.members.Count();
- groupListSemester.leader=clazz.teacher?.id;
- groupListSemester.grades.Add(clazz.year);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync<GroupListSemester>(groupListSemester, new PartitionKey(groupListSemester.code));
- }
- }
- }
- }
- }
- }
- }
- //已经处理过的数据则不需要在进行处理
- if (editedStus.IsEmpty() && !string.IsNullOrWhiteSpace(type))
- {
- keyExists = await _azureRedis.GetRedisClient(8).KeyExistsAsync(key);
- if (keyExists)
- {
- var data = await _azureRedis.GetRedisClient(8).StringGetAsync(key);
- if (data.HasValue)
- {
- SemesterStudyYearNotify notify = data.ToString().ToObject<SemesterStudyYearNotify>();
- notify.process = 1;
- await _azureRedis.GetRedisClient(8).StringSetAsync(key, notify.ToJsonString());
- }
- }
- type="";
- }
- else {
- periodNotify.Add(new { studyYearStarted, studyYearEnding, semesterStarted, semesterEnding, type, key, editedStus, periodId = period.id, periodName = period.name });
- }
- }
- }
- }
- return Ok(new { code = 200, periodNotify });
- }
- }
- }
|