12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432 |
- using Azure;
- using Microsoft.Azure.Cosmos;
- using Microsoft.Azure.Cosmos.Table;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.Models.Dtos;
- using TEAMModelOS.SDK.Services;
- using Microsoft.Extensions.Configuration;
- using Azure.Messaging.ServiceBus;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using Microsoft.OData.Edm;
- using System.IdentityModel.Tokens.Jwt;
- using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
- using Microsoft.OData.UriParser;
- using Azure.Core;
- using System.Security.Policy;
- using System.Net.Http.Json;
- using System.Drawing;
- using Microsoft.AspNetCore.DataProtection;
- using Newtonsoft.Json.Linq;
- using Microsoft.Extensions.Hosting;
- using Microsoft.AspNetCore.Hosting;
- using TEAMModelOS.Models.ShanDa;
- namespace TEAMModelOS.SDK
- {
- public class OpenApiService
- {
- private static List<string> weekDays = new List<string> { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
- /// <summary>
- /// 第三方获取学校列表
- /// [ApiToken(Auth = "1000", Name = "合作商获取可访问的学校列表",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<BizSchool>>> GetSchools(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId)
- {
- try
- {
- List<BizSchool> schools = new();
- var response = await _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizId, new PartitionKey("BizConfig"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- using var resJson = await JsonDocument.ParseAsync(response.Content);
- Business bizConfig = resJson.ToObject<Business>();
- schools = bizConfig.schools;
- }
- else return new ResponseData<List<BizSchool>>() { code = RespondCode.NotFound, msg = "未找到该企业" };
- return new ResponseData<List<BizSchool>>() { code = RespondCode.Ok, msg = "成功", data = schools };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSchools() 参数:bizId:{bizId} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<BizSchool>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// josn:
- /// {
- /// "roles":"",
- /// "scope":""
- /// "pageCount":"",
- /// "DESC":"",
- /// "ASC":"",
- /// "continuationToken":"",
- /// "school":"",
- /// "tmdid":""
- /// }
- /// </summary>
- /// <param name="azureCosmos"></param>
- /// <param name="dingDing"></param>
- /// <param name="id"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public static async Task<ResponseData<dynamic>> GetLessonRecordCount(AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus,
- Option _option, DingDing _dingDing, string id, string school, JsonElement json)
- {
- json.TryGetProperty("identity", out JsonElement _identity);
- string identity = "";
- if (!string.IsNullOrWhiteSpace($"{_identity}"))
- {
- identity = $"{_identity}";
- }
- json.TryGetProperty("managePage", out JsonElement _managePage);
- bool managePage = false;
- if (_managePage.ValueKind.Equals(JsonValueKind.True))
- {
- managePage = true;
- }
- StringBuilder sql = new StringBuilder();
- sql.Append("select c.id,c.groupIds,c.courseId from c ");
- Dictionary<string, object> dict = LessonService.GetLessonCond(json);
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- string tbname = "";
- string code = "";
- List<string> autoTch = new List<string>();
- string sqlPrivate = "";
- code = $"LessonRecord-{school}";
- tbname = "School";
- List<string> ids = new List<string>();
- //只查询某个老师的课例
- if (json.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- ids.Add($"{tmdid}");
- }
- else
- {
- string sqltch = "select distinct value(c.id) from c ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- int count = 0;
- string sqlShow = "";
- if (identity.Equals("student"))
- {
- string autoSql = "";
- if (autoTch.Any())
- {
- autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- string sql_status_managePage = " (c.status<>404 or IS_DEFINED(c.status) = false ) and ";
- if (managePage)
- {
- sql_status_managePage = "";
- }
- long now = DateTimeOffset.Now.ToUnixTimeMilliseconds();
- //cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} 1=1 {sqlPrivate} {sqlShow} and ");
- if (json.TryGetProperty("singleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
- {
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where ((c.tLevel=2 and c.pLevel<2 )or(c.tLevel<2 and c.pLevel=2 )) and ");
- }
- if (json.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
- {
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where c.expire>{now} and ");
- }
- List<LessonRecord> records = new List<LessonRecord>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIteratorQuery<LessonRecord>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- records.Add(item);
- }
- if (records.Any())
- {
- var groupIds = records.SelectMany(x => x.groupIds).ToHashSet();
- if (groupIds.Any())
- {
- var groups = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school, " c.id ");
- //获取已经被删除的名单。
- var idsExp = groupIds.Except(groups.Select(x => x.id));
- if (idsExp.Any())
- {
- foreach (var item in records)
- {
- int countRmv = item.groupIds.RemoveAll(x => idsExp.Contains(x));
- if (countRmv > 0)
- {
- try
- {
- LessonRecord record = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<LessonRecord>(item.id, new PartitionKey(code));
- record.groupIds = item.groupIds;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<LessonRecord>(record, item.id, new PartitionKey(code));
- }
- catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
- {
- continue;
- }
- }
- }
- }
- }
- }
- count = records.Count;
- ResponseData<dynamic> resDate = new ResponseData<dynamic>
- {
- code = RespondCode.Ok,
- msg = "成功",
- data = new
- {
- count = count,
- }
- };
- return resDate;
- }
- /// <summary>
- /// josn:
- /// {
- /// "roles":"",
- /// "scope":""
- /// "pageCount":"",
- /// "DESC":"",
- /// "ASC":"",
- /// "continuationToken":"",
- /// "school":"",
- /// "tmdid":""
- /// }
- /// </summary>
- /// <param name="azureCosmos"></param>
- /// <param name="dingDing"></param>
- /// <param name="id"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- /// <exception cref="NotImplementedException"></exception>
- public static async Task<ResponseData<dynamic>> GetLessonRecord(AzureCosmosFactory _azureCosmos, IConfiguration _configuration, AzureServiceBusFactory _serviceBus,
- Option _option, DingDing _dingDing, string id, string school, JsonElement json)
- {
- json.TryGetProperty("identity", out JsonElement _identity);
- string identity = "";
- if (!string.IsNullOrWhiteSpace($"{_identity}"))
- {
- identity = $"{_identity}";
- }
- json.TryGetProperty("managePage", out JsonElement _managePage);
- bool managePage = false;
- if (_managePage.ValueKind.Equals(JsonValueKind.True))
- {
- managePage = true;
- }
- StringBuilder sql = new StringBuilder();
- sql.Append("select value(c) from c ");
- int pageCount = 10;
- Dictionary<string, object> dict = LessonService.GetLessonCond(json);
- if (json.TryGetProperty("pageCount", out JsonElement _pageCount))
- {
- int.TryParse($"{_pageCount}", out int pcount);
- if (pcount > 0)
- {
- pageCount = pcount;
- }
- }
- if (json.TryGetProperty("DESC", out JsonElement desc))
- {
- dict.Add("@DESC", desc.ToString());
- }
- if (json.TryGetProperty("ASC", out JsonElement asc))
- {
- dict.Add("@ASC", asc.ToString());
- }
- string continuationToken = null;
- if (json.TryGetProperty("continuationToken", out JsonElement _continuationToken))
- {
- if (!string.IsNullOrEmpty($"{_continuationToken}"))
- {
- continuationToken = $"{_continuationToken}";
- }
- }
- AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
- string tbname = "";
- string code = "";
- string sqlPrivate = "";
- List<string> autoTch = new List<string>();
- code = $"LessonRecord-{school}";
- tbname = "School";
- List<string> ids = new List<string>();
- //只查询某个老师的课例
- if (json.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- ids.Add($"{tmdid}");
- }
- else
- {
- string sqltch = "select distinct value(c.id) from c ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<string>(queryText: sqltch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.Any())
- {
- string sqlTechbase = $"select distinct value(c.id) from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))}) and (array_contains(c.lessonShow,'student') or array_contains(c.lessonShow,'all')) ";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<string>(queryText: sqlTechbase, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
- {
- autoTch.Add(item);
- }
- }
- List<LessonRecord> lessonRecords = new List<LessonRecord>();
- try
- {
- string sqlShow = "";
- if (identity.Equals("student"))
- {
- string autoSql = "";
- if (autoTch.Any())
- {
- autoSql = $" or c.tmdid in ({string.Join(",", autoTch.Select(x => $"'{x}'"))})";
- }
- sqlShow = $" and (array_contains(c.show,'student') or array_contains(c.show,'all') {autoSql} ) ";
- }
- string sql_status_managePage = "(c.status<>404 or IS_DEFINED(c.status) = false ) and ";
- if (managePage)
- {
- sql_status_managePage = "";
- }
- // cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} array_length(c.groupIds)>0 {sqlPrivate} {sqlShow} and ");
- cosmosDbQuery.QueryText = cosmosDbQuery.QueryText.Replace("where", $" where {sql_status_managePage} 1=1 {sqlPrivate} {sqlShow} and ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname)
- .GetItemQueryStreamIteratorQuery(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, continuationToken: continuationToken,
- requestOptions: new QueryRequestOptions() { MaxItemCount = pageCount, PartitionKey = new PartitionKey(code) }))
- {
- using var jsonData = await JsonDocument.ParseAsync(item.Content);
- if (jsonData.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in jsonData.RootElement.GetProperty("Documents").EnumerateArray())
- {
- lessonRecords.Add(obj.ToObject<LessonRecord>());
- }
- continuationToken = item.ContinuationToken;
- break;
- }
- }
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //查询时处理已经过期的课例。防止ServiceBus未触发的。
- var expireRecords = lessonRecords.Where(x => x.expire > 0 && now > x.expire);
- try
- {
- foreach (var item in expireRecords)
- {
- //item.status = 404;
- //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync(item, item.id, new PartitionKey(item.code));
- var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
- var messageChange = new ServiceBusMessage(new { delete_id = item.id, tmdid = item.tmdid, scope = item.scope, opt = "delete", school = item.school }.ToJsonString());
- messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location},ServiceBus ,LessonRecordEvent 发送消息失败,检查是否配置正常。", GroupNames.成都开发測試群組);
- }
- var tmdids = lessonRecords.Select(x => x.tmdid).ToHashSet();
- if (tmdids != null && tmdids.Count > 0)
- {
- List<IdNameCode> codes = new List<IdNameCode>();
- string sqltmd = $"select c.id,c.name,c.picture from c where c.id in ({string.Join(",", tmdids.Select(x => $"'{x}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: sqltmd, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- codes.Add(item);
- }
- if (codes.IsNotEmpty())
- {
- lessonRecords.ForEach(x =>
- {
- var tmd = codes.Find(z => z.id.Equals(x.tmdid));
- if (tmd != null)
- {
- x.tmdname = tmd.name;
- x.tmdpicture = tmd.picture;
- }
- });
- }
- }
- var groupIds = lessonRecords.SelectMany(x => x.groupIds);
- if (groupIds.Any())
- {
- List<GroupListDto> groupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, groupIds.ToList(), school);
- lessonRecords.ForEach(x =>
- {
- List<string> groupNmae = new List<string>();
- x.groupIds.ForEach(y =>
- {
- var dto = groupLists.Find(z => z.id.Equals(y));
- string name = dto != null ? dto.name : "-";
- groupNmae.Add(name);
- });
- x.groupNames = groupNmae;
- });
- }
- ResponseData<dynamic> resDate = new ResponseData<dynamic>
- {
- code = RespondCode.Ok,
- msg = "成功",
- data = new
- {
- currCount = lessonRecords.Count,
- continuationToken,
- lessonRecords = lessonRecords.Select(x => new { x.tmdid, x.tmdname, x.tmdpicture, x.name, x.school, x.startTime, x.duration, x.courseId, x.groupIds, x.periodId, x.subjectId, x.grade, x.id, x.category })
- }
- };
- return resDate;
- }
- catch (Exception)
- {
- continuationToken = null;
- ResponseData<dynamic> resDate = new ResponseData<dynamic> { code = RespondCode.Ok, msg = "成功", data = new { currCount = 0, continuationToken = continuationToken, lessonRecords } };
- return resDate;
- }
- }
- /// <summary>
- /// 学校基本信息
- /// //[ApiToken(Auth = "1001", Name = "学校基本信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="schoolId"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetSchoolInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string schoolId)
- {
- try
- {
- ResponseData<dynamic> resDate = new();
- School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(schoolId, new PartitionKey("Base"));
- List<dynamic> period = new();
- data.period.ForEach(x => { period.Add(new { x.subjects, x.grades, x.name, x.id, x.campusId, x.semesters }); });
- if (data != null)
- {
- resDate.code = RespondCode.Ok;
- resDate.msg = "成功";
- resDate.data = new { data.id, data.name, data.areaId, data.type, data.region, data.province, data.city, data.dist, data.campuses, period };
- }
- else
- {
- resDate.code = RespondCode.NotFound;
- resDate.msg = "未找到学校信息";
- }
- return resDate;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSchoolInfo() 参数:bizId:{bizId},school:{schoolId} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 名单列表信息 获取学校的行政班,教学班,教研组,研修名单
- /// [ApiToken(Auth = "1201", Name = "名单列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<OGroupList>>> GetGroupList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- ResponseData<List<OGroupList>> resDate = new();
- List<OGroupList> groupLists = new();
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("periodId", out JsonElement periodId);
- List<GroupListGrp> tempGroupLists = new();
- //包含,学校的行政班,教学班
- 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> { $"{types}" };
- }
- if (types.IsEmpty() || types.Contains("class"))
- {
- StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year FROM c ");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- classsql.Append($" where c.periodId='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<ClassInfo>(queryText: classsql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{school}") }))
- {
- 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").GetItemQueryIteratorSql<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
- {
- groupNames.Add(gp.groupName);
- }
- ///行政班(学生搜寻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,
- groupName = groupNames
- };
- tempGroupLists.Add(group);
- }
- }
- if (types.IsEmpty() || types.Contains("teach"))
- {
- //教学班
- StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach'");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- teachsql.Append($" and c.periodId='{periodId}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIteratorSql<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();
- tempGroupLists.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").
- GetItemQueryIteratorSql<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();
- tempGroupLists.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").
- GetItemQueryIteratorSql<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();
- tempGroupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- groupLists = tempGroupLists.Select(x => new OGroupList { id = x.id, name = x.name, type = x.type, periodId = x.periodId, school = x.school, scope = x.scope, year = x.year, expire = x.expire }).ToList();
- if (groupLists.Count > 0)
- {
- resDate.code = RespondCode.Ok;
- resDate.msg = "成功";
- resDate.data = groupLists;
- }
- else
- {
- resDate.code = RespondCode.NotFound;
- resDate.msg = "未找到学校信息";
- }
- return resDate;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetGroupList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<OGroupList>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 名单成员信息,学生成员信息,包含(学生,成员)基本信息,分组等信息
- /// [ApiToken(Auth = "1202", Name = "名单成员信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_coreAPIHttpService"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetGroupMembers(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- List<OGgroup> groups = new();
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("ids", out JsonElement ids)) return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "参数错误" };
- List<string> listids = ids.ToObject<List<string>>();
- (List<RMember> members, List<RGroupList> tGroups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{school}");
- groups = tGroups.Select(x => new OGgroup
- {
- name = x.name,
- no = x.no,
- periodId = x.periodId,
- school = x.school,
- type = x.type,
- year = x.year,
- expire = x.expire,
- tcount = x.tcount,
- scount = x.scount,
- leader = x.leader,
- members = x.members,
- id = x.id
- }).ToList();
- if (bizId.Equals("cc7e900c-4881-4fe9-9c64-abb1a1f95518") || bizId.Equals("633d4d36-2cae-469a-bdcb-c52ce2e416b3") || bizId.Equals("8254bc86-aae9-4fef-9655-4fbda1bd39da"))
- {
- if (listids.Count == 1 && listids.First().Equals("TeacherAll") && !string.IsNullOrEmpty(school))
- {
- var keys = members.Select(x => x.id).ToHashSet();
- var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
- string ujson = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(ujson))
- {
- var coreUsers = ujson.ToObject<List<CoreUser>>();
- if (coreUsers.IsNotEmpty())
- {
- coreUsers.ForEach(z => {
- var mb = members.Find(x => x.id.Equals(z.id));
- if (mb != null)
- {
- mb.no = z.mobile;
- }
- });
- }
- }
- }
- }
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { groups, members } };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetGroupMembers() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 获取课程列表信息
- /// [ApiToken(Auth = "1301", Name = "获取课程列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetCourseList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("periodId", out JsonElement periodId);
- json.TryGetProperty("subjectId", out JsonElement subjectId);
- StringBuilder sql = new StringBuilder($"SELECT c.id,c.name,c.subject,c.period,c.scope,c.no,c.school FROM c where 1=1 ");
- if (!string.IsNullOrWhiteSpace($"{periodId}"))
- {
- sql.Append($" and c.period.id='{periodId}'");
- }
- if (!string.IsNullOrWhiteSpace($"{subjectId}"))
- {
- sql.Append($" and c.subject.id='{subjectId}'");
- }
- List<dynamic> courses = new List<dynamic>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
- {
- courses.Add(item);
- }
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = courses };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetCourseList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 课程详细信息
- /// [ApiToken(Auth = "1302", Name = "课程详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetCourseInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- json.TryGetProperty("courseId", out JsonElement courseId);
- var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{courseId}", new PartitionKey($"Course-{school}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- JsonDocument document = JsonDocument.Parse(response.Content);
- Course course = document.RootElement.Deserialize<Course>();
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { course.name, course.id, course.subject, course.period, course.scope, course.school, course.no, course.desc, course.schedule } };
- }
- else
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetCourseInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 获取指定学段作息
- /// [ApiToken(Auth = "1303", Name = "获取指定学段作息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetPaperExamCondition(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- json.TryGetProperty("periodId", out JsonElement _periodId);
- School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
- var period = data.period.Find(x => x.id.Equals($"{_periodId}"));
- if (period != null)
- {
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { period.subjects, period.timetable, period.grades, period.majors, weekDays } };
- }
- else
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetPaperExamCondition() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- public static async Task<ResponseData<dynamic>> getCourseTechnology(IHttpClientFactory _httpClient, DingDing _dingDing, string bizId, string school, JsonElement json, IWebHostEnvironment _environment)
- {
- try
- {
- _httpClient.CreateClient().DefaultRequestHeaders.Add("ContentLength", "0");
- HttpContent httpContent = new StringContent(new { method = "statistic/data/" }.ToJsonString());
- /*Dictionary<string, object> data = new Dictionary<string, object>();
- data.Add("method", "statistic/data/");*/
- //data.Add("params", new { method = "statistic/data/"});
- //HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("http://116.204.72.199:81/statistic/data/", data);
- var response = await _httpClient.CreateClient().PostAsync("http://116.204.72.199:81/statistic/data/", httpContent);
- //获取配置文件内容
- string path = $"{_environment.ContentRootPath}/JsonFile/Core/field.json";
- StreamReader streamReader = new(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
- StringBuilder stringBuilder = new();
- string text;
- while ((text = streamReader.ReadLine()) != null)
- {
- stringBuilder.Append(text.ToString());
- }
- streamReader.Close();
- string input = stringBuilder.ToString();
- Field fields = input.ToObject<Field>();
- List<OCourseBase> courses = new();
- List<(string name, double T, double P, int attendCount, int mCount, int groups, long time,
- List<(string name, int count)> counts, List<(string name, double score)> ps,
- List<(string name, long time)> appTimes, List<(string name, string url, int duration, long time)> vd)> scores = new();
- //List<(string name, List<(string name, int count)> counts)> eveCounts = new();
- if (response.IsSuccessStatusCode)
- {
- string responseBody = response.Content.ReadAsStringAsync().Result;
- JObject jo = JObject.Parse(responseBody.ToString());
- JArray array = jo.Value<JArray>("base");
- foreach (var ne in array)
- {
- OCourseBase @base = new();
- var tname = ne["tmdname"].Value<string>();
- var cname = ne["courseName"].Value<string>();
- var attendCount = ne["attendCount"].Value<int>();
- var mCount = ne["mCount"].Value<int>();
- var time = ne["time"].Value<long>();
- var obj = ne["events"].ToObject<List<Events>>();
- var video = ne["videos"].ToObject<List<Videos>>();
- @base.tmdname = tname;
- @base.courseName = cname;
- @base.attendCount = attendCount;
- @base.mCount = mCount;
- @base.groups = new List<string>();
- @base.time = time;
- @base.eves = obj;
- @base.videos = video;
- //events.Add(obj);
- courses.Add(@base);
- }
- foreach (var eve in courses)
- {
- var countEve = eve.eves.GroupBy(x => x.@event).Select(y => new { name = y.Key, value = y.Sum(c => c.freq) });
- double scoreA = 0;
- if (countEve.Any())
- {
- scoreA += 20;
- }
- double scoreB = 0;
- int P1Count = 0;
- int P2Count = 0;
- int P3Count = 0;
- int P4Count = 0;
- int P5Count = 0;
- List<(string name, long time)> eveTimes = new();
- List<(string name, string url, int duration, long time)> videos = new();
- foreach (var v in eve.videos)
- {
- videos.Add((v.videoName, v.video, v.duration, v.startTime));
- }
- foreach (var apps in eve.eves)
- {
- var name = fields.fields.Where(x => x.field.Equals(apps.@event)).FirstOrDefault()?.desc;
- eveTimes.Add((name, apps.createTime));
- }
- List<(string name, int count)> eves = new();
- foreach (var per in countEve)
- {
- var name = fields.fields.Where(x => x.field.Equals(per.name)).FirstOrDefault()?.desc;
- eves.Add((name, per.value));
- foreach (var evePercent in fields.fields)
- {
- //计算T分
- if (per.name.Equals(evePercent.field))
- {
- if (evePercent.dimension.Equals("小组学习"))
- {
- P1Count++;
- }
- if (evePercent.dimension.Equals("全班互动"))
- {
- P2Count++;
- }
- if (evePercent.dimension.Equals("生本决策"))
- {
- P3Count++;
- }
- if (evePercent.dimension.Equals("全班测验"))
- {
- P4Count++;
- }
- if (evePercent.dimension.Equals("个人学习"))
- {
- P5Count++;
- }
- double bScore = 0;
- if (per.value == 1)
- {
- bScore += evePercent.percent * 0.9;
- }
- else if (per.value == 2)
- {
- bScore += evePercent.percent * 0.95;
- }
- else if (per.value >= 3)
- {
- bScore += evePercent.percent;
- }
- scoreB += bScore;
- }
- }
- }
- List<(string name, double score)> PScore = new();
- double P1Score = 0;
- if (P1Count == 1)
- {
- P1Score = 18 * 0.8;
- }
- else if (P1Count == 2)
- {
- P1Score = 18 * 0.9;
- }
- else if (P1Count >= 3)
- {
- P1Score = 18;
- }
- double P2Score = 0;
- if (P2Count == 1)
- {
- P2Score = 18 * 0.8;
- }
- else if (P2Count == 2)
- {
- P2Score = 18 * 0.9;
- }
- else if (P2Count >= 3)
- {
- P2Score = 18;
- }
- double P3Score = 0;
- if (P3Count == 1)
- {
- P3Score = 18 * 0.8;
- }
- else if (P3Count == 2)
- {
- P3Score = 18 * 0.9;
- }
- else if (P3Count >= 3)
- {
- P3Score = 18;
- }
- double P4Score = 0;
- if (P4Count == 1)
- {
- P4Score = 18 * 0.8;
- }
- else if (P3Count == 2)
- {
- P4Score = 18 * 0.9;
- }
- else if (P4Count >= 3)
- {
- P4Score = 18;
- }
- double P5Score = 0;
- if (P5Count == 1)
- {
- P5Score = 18 * 0.8;
- }
- else if (P5Count == 2)
- {
- P5Score = 18 * 0.9;
- }
- else if (P5Count >= 3)
- {
- P5Score = 18;
- }
- double P6Score = (P1Score + P2Score + P3Score + P4Score + P5Score) * 0.1;
- PScore.Add(("小组学习", P1Score));
- PScore.Add(("全班互动", P2Score));
- PScore.Add(("生本决策", P3Score));
- PScore.Add(("全班测验", P4Score));
- PScore.Add(("个人学习", P5Score));
- PScore.Add(("多元评价", P6Score));
- double P = P1Score + P2Score + P3Score + P4Score + P5Score + P6Score;
- double scoreC = (scoreA + scoreB) * 0.1;
- double scoreT = scoreA + scoreB + scoreC;
- scoreT = scoreT > 0 ? Math.Round(scoreT, 2) : 0;
- P = P > 0 ? Math.Round(P, 2) : 0;
- scores.Add((eve.courseName, scoreT, P, eve.attendCount, eve.mCount, eve.groups.Count, eve.time, eves, PScore, eveTimes, videos));
- //eveCounts.Add((eve.courseName, eves));
- }
- //var eve = courses.Select(c => c.eves).ToList();
- /*using JsonDocument document = JsonDocument.Parse(responseBody.ToString());
- if (document.RootElement.TryGetProperty("base", out JsonElement AccessTokenObj))
- {
- //AccessToken = AccessTokenObj.ToString();
- }*/
- }
- var courseScore = scores.Select(c => new
- {
- c.name,
- c.T,
- c.P,
- c.attendCount,
- c.mCount,
- c.groups,
- c.time,
- count = c.counts.Select(x => new { x.name, x.count }),
- pScore = c.ps.Select(x => new { x.name, x.score }),
- appTime = c.appTimes.Select(x => new { x.name, x.time }),
- videos = c.vd.Select(x => new { x.name, x.url, x.duration, x.time })
- });
- /*var courseCount = eveCounts.Select(c => new
- {
- c.name,
- count = c.counts.Select(x => new { x.name, x.count })
- });*/
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { courseScore } };
- /*if (period != null)
- {
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { period.subjects, period.timetable, period.grades, period.majors, weekDays } };
- }
- else
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到相关课程" };*/
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/getCourseTechnology() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 物理教室列表
- /// [ApiToken(Auth = "1401", Name = "物理教室列表",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<ORoom>>> GetRoomList(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- List<ORoom> dtRooms = new();
- StringBuilder sql = new StringBuilder($"select value(c) from c where 1=1 ");
- json.TryGetProperty("openType", out JsonElement openType);
- json.TryGetProperty("no", out JsonElement no);
- if (!string.IsNullOrWhiteSpace($"{openType}"))
- {
- sql.Append($" and c.openType='{openType}'");
- }
- if (!string.IsNullOrWhiteSpace($"{no}"))
- {
- sql.Append($" and c.no='{no}'");
- }
- List<Room> rooms = new List<Room>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Room>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Room-{school}") }))
- {
- rooms.Add(item);
- }
- dtRooms = rooms.Select(s => new ORoom { id = s.id, name = s.name, x = s.x, y = s.y, openType = s.openType, style = s.style, area = s.area, address = s.address, school = school }).ToList();
- if (dtRooms.Count > 0)
- return new ResponseData<List<ORoom>>() { code = RespondCode.Ok, data = dtRooms };
- else
- return new ResponseData<List<ORoom>>() { code = RespondCode.NotFound, msg = "未找到该学校的物理教室" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetRoomList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<ORoom>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 物理教室详细
- /// [ApiToken(Auth = "1402", Name = "物理教室详细",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetRoomInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("roomId", out JsonElement roomId)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
- var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{roomId}", new PartitionKey($"Room-{school}"));
- if (response.StatusCode == System.Net.HttpStatusCode.OK)
- {
- JsonDocument document = JsonDocument.Parse(response.Content);
- Room tRoom = document.RootElement.Deserialize<Room>();
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { tRoom.id, tRoom.name, tRoom.x, tRoom.y, tRoom.openType, tRoom.style, tRoom.area, tRoom.address, school } };
- }
- else
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到物理教室详情" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetRoomInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 教师列表信息
- /// [ApiToken(Auth = "1501", Name = "教师列表信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_coreAPIHttpService"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetTeacherList(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("searchKey", out JsonElement _searchKey);
- List<CoreUser> coreUsers = new(); List<CoreUser> unjoined = new();
- IEnumerable<string> unexist = null;
- StringBuilder sql = new("select c.id,c.name ,c.picture,c.job ,c.subjectIds,c.roles from c");
- if (_searchKey.ValueKind.Equals(JsonValueKind.Array))
- {
- List<string> searchKey = _searchKey.ToObject<List<string>>();
- if (searchKey.Any())
- {
- var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
- var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
- string ujson = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(ujson))
- {
- coreUsers = ujson.ToObject<List<CoreUser>>();
- }
- if (coreUsers.Any())
- unexist = searchKey.Except(coreUsers.Select(x => x.searchKey));
- else
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "没有找到对应的教师信息", data = _searchKey };
- }
- }
- List<SchoolTeacher> teachers = new();
- //string insql = "";
- if (coreUsers.Any())
- sql.Append($" where c.id in ({string.Join(",", coreUsers.Select(x => $"'{x.id}'"))}) ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>
- (queryText: sql.ToString(), requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- teachers.Add(item);
- }
- if (coreUsers.Count > 0)
- {
- var teacherIds = coreUsers.Select(x => x.id).Except(teachers.Select(x => x.id));
- unjoined = coreUsers.FindAll(x => teacherIds.Contains(x.id));
- }
- List<dynamic> tchs = new List<dynamic>();
- teachers.Select(x => new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles }).ToList().ForEach(x =>
- {
- if (coreUsers.Count > 0)
- {
- var coreUser = coreUsers.Find(c => c.id.Equals(x.id));
- if (coreUser != null)
- {
- tchs.Add(new { x.id, coreUser.name, coreUser.picture, x.job, x.subjectIds, x.roles, coreUser.searchKey, school });
- }
- }
- else
- tchs.Add(new { x.id, x.name, x.picture, x.job, x.subjectIds, x.roles, school });
- });
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = new { tchs, unjoined = unjoined.Select(x => new { id = x.id, name = x.name, picture = x.picture, searchKey = x.searchKey }).ToList(), unexist } };
- }
- catch (Exception ex)
- {
- //await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherList() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 教师执教的班级和课程
- /// [ApiToken(Auth = "1502", Name = "教师详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetTeacherTeach(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- if (json.TryGetProperty("tmdid", out JsonElement _tmdid))
- {
- json.TryGetProperty("period", out JsonElement _period);
- List<OCourse> courses = new List<OCourse>();
- var query = $"SELECT distinct c.code,c.id,c.no,c.name,c.period,c.subject,c.scope ,c['desc'] ,c.creatorId , c.year ,s as schedule FROM c join s in c.schedule where s.teacherId='{_tmdid}' ";
- HashSet<string> classIds = new HashSet<string>();
- if (!string.IsNullOrWhiteSpace($"{_period}"))
- {
- query = $"{query} and c.period.id ='{_period}'";
- }
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<OCourse>(queryText: query,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{school}") }))
- {
- if (!string.IsNullOrWhiteSpace(item.schedule?.stulist))
- {
- classIds.Add(item.schedule?.stulist);
- }
- if (!string.IsNullOrWhiteSpace(item.schedule?.classId))
- {
- classIds.Add(item.schedule?.classId);
- }
- courses.Add(item);
- }
- List<OGroupList> groupLists = new List<OGroupList>();
- if (classIds.Any())
- {
- var tempGroupLists = await GroupListService.GetGroupListByListids(_azureCosmos.GetCosmosClient(), _dingDing, classIds.ToList(), school);
- groupLists = tempGroupLists.Select(x => new OGroupList { id = x.id, name = x.name, type = x.type, periodId = x.periodId, school = x.school, scope = x.scope, year = x.year, expire = x.expire }).ToList();
- }
- var group = courses.GroupBy(x => x.id).Select(g => new { key = g.Key, list = g.ToList() });
- List<Course> coursesR = new List<Course>();
- group.ToList().ForEach(x =>
- {
- var first = x.list.First();
- coursesR.Add(new Course
- {
- id = x.key,
- name = first.name,
- code = first.code,
- no = first.no,
- period = first.period,
- subject = first.subject,
- desc = first.desc,
- creatorId = first.creatorId,
- year = first.year,
- schedule = x.list.Select(x => x.schedule).ToList()
- });
- });
- return new ResponseData<dynamic>()
- {
- code = RespondCode.Ok,
- data = new
- {
- courses = coursesR.Select(x => new
- {
- x.id,
- school = school,
- x.name,
- x.no,
- x.period,
- x.subject,
- x.desc,
- x.creatorId,
- x.year,
- x.schedule
- }),
- groupLists
- }
- };
- }
- else
- {
- return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherTeach() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 教师详细信息
- /// [ApiToken(Auth = "1502", Name = "教师详细信息",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetTeacherInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement _tmdid);
- var responseSchoolTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
- .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Teacher-{school}"));
- var responseTch = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
- .ReadItemStreamAsync($"{_tmdid}", new PartitionKey($"Base"));
- Teacher teacher = null;
- if (responseTch.StatusCode == System.Net.HttpStatusCode.OK)
- {
- teacher = JsonDocument.Parse(responseTch.Content).RootElement.Deserialize<Teacher>();
- }
- else
- return new ResponseData<dynamic> { code = RespondCode.NotFound, msg = "账号未创建" };
- if (responseSchoolTch.StatusCode == System.Net.HttpStatusCode.OK && teacher != null)
- {
- SchoolTeacher schoolTeacher = JsonDocument.Parse(responseSchoolTch.Content).RootElement.Deserialize<SchoolTeacher>();
- return new ResponseData<dynamic> { code = RespondCode.Ok, msg = "成功", data = new { teacher.id, teacher.name, teacher.picture, schoolTeacher.job, schoolTeacher.status, schoolTeacher.roles, schoolTeacher.subjectIds, school = teacher.schools?.Find(x => x.schoolId.Equals(school)) } };
- }
- else
- return new ResponseData<dynamic> { code = RespondCode.NotFound, msg = "教师未就职该学校" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherInfo() 参数:bizId:{bizId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 教师批量导入,并加入学校。可以导入学科,但需要填写学段id
- /// [ApiToken(Auth = "1503", Name = "教师批量导入",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_coreAPIHttpService"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<OTeachers>>> GetTeacherInfo(AzureCosmosFactory _azureCosmos, CoreAPIHttpService _coreAPIHttpService, DingDing _dingDing, string bizId, string school, ImportTechDto json)
- {
- try
- {
- //如果需要同时导入学科,则需要填写学段
- List<ImportTech> impTeachers = json.teachers;
- List<string> searchKey = impTeachers.Select(x => x.id).ToList();
- string ujson = null;
- var keys = searchKey.Where(x => !string.IsNullOrWhiteSpace(x));
- if (keys.Any())
- {
- var content = new StringContent(keys.ToJsonString(), Encoding.UTF8, "application/json");
- ujson = await _coreAPIHttpService.GetUserInfos(content);
- }
- List<CoreUser> coreUsers = new List<CoreUser>();
- if (!string.IsNullOrWhiteSpace(ujson))
- {
- coreUsers = ujson.ToObject<List<CoreUser>>();
- }
- IEnumerable<string> unexist = new List<string>();
- if (coreUsers.Any())
- {
- unexist = searchKey.Except(coreUsers.Select(x => x.id));
- }
- else
- {
- return new ResponseData<List<OTeachers>>() { code = RespondCode.NotFound, msg = "没有找到对应的教师信息" };
- }
- var exist = coreUsers.Select(x => x.id);
- //注册了账号的教师
- impTeachers = impTeachers.Where(x => exist.Contains(x.id)).ToList();
- List<Teacher> teachersList = new List<Teacher>();
- List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
- string sql = $"select value(c) from c where c.id in ({string.Join(",", impTeachers.Select(x => $"'{x.id}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- teachersList.Add(item);
- }
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
- .GetItemQueryIteratorSql<SchoolTeacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- schoolTeachers.Add(item);
- }
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- School data = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(school, new PartitionKey("Base"));
- //学校学科发生变化。
- List<SchoolTeacher> schoolTeachersAdd = new List<SchoolTeacher>();
- bool baseChange = false;
- foreach (var item in impTeachers)
- {
- var teacher = teachersList.Find(x => x.id.Equals(item.id));
- var coreUser = coreUsers.Find(x => x.id.Equals(item.id));
- if (teacher != null)
- {
- var sch = teacher.schools?.Find(x => x.schoolId.Equals(school));
- if (sch == null)
- {
- if (teacher.schools.IsNotEmpty())
- {
- teacher.schools.Add(new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId });
- }
- else
- {
- teacher.defaultSchool = school;
- teacher.size = teacher.size + 1;
- teacher.schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } };
- }
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(teacher, teacher.id, new PartitionKey("Base"));
- }
- else
- {
- teacher = new Teacher
- {
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- id = coreUser.id,
- name = coreUser.name,
- picture = coreUser.picture,
- defaultSchool = school,
- size = 2,
- code = "Base",
- pk = "Base",
- schools = new List<Teacher.TeacherSchool> { new Teacher.TeacherSchool { schoolId = school, name = data.name, status = "invite", time = now, picture = data.picture, areaId = data.areaId } }
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).CreateItemAsync(teacher, new PartitionKey("Base"));
- }
- var schoolTeacher = schoolTeachers.Find(x => x.id.Equals(item.id));
- //处理导入的学科
- List<string> subjectIds = new List<string>();
- if (item.subjects.IsNotEmpty() && !string.IsNullOrWhiteSpace(item.periodId))
- {
- item.subjects.ForEach(s =>
- {
- //同名学科
- var subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.id.Equals(s.id));
- if (subject == null)
- {
- subject = data.period.Find(x => x.id.Equals(item.periodId))?.subjects?.Find(x => x.name.Equals(s.name));
- }
- else
- {
- subjectIds.Add(subject.id);
- }
- if (subject == null)
- {
- var period = data.period.Find(x => x.id.Equals(item.periodId));
- if (period != null)
- {
- period.subjects.Add(new Subject { id = s.id, name = s.name, type = 2 });
- subjectIds.Add(s.id);
- baseChange = true;
- }
- }
- });
- }
- if (schoolTeacher == null)
- {
- schoolTeacher = new SchoolTeacher
- {
- id = item.id,
- name = coreUser.name,
- picture = coreUser.picture,
- job = item.job,
- subjectIds = subjectIds,
- roles = new List<string> { "teacher" },
- permissions = new List<string> { "content-read", "exercise-read", "knowledge-read", "syllabus-read" },
- status = "invite",
- code = $"Teacher-{school}",
- pk = "Teacher",
- createTime = now,
- };
- schoolTeachersAdd.Add(schoolTeacher);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).CreateItemAsync(schoolTeacher, new PartitionKey(schoolTeacher.code));
- }
- else
- {
- if (subjectIds.IsNotEmpty())
- {
- subjectIds.ForEach(x =>
- {
- if (!schoolTeacher.subjectIds.Contains(x))
- {
- schoolTeacher.subjectIds.Add(x);
- }
- });
- }
- schoolTeacher.job = string.IsNullOrWhiteSpace(item.job) ? schoolTeacher.job : item.job;
- schoolTeachersAdd.Add(schoolTeacher);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(schoolTeacher, schoolTeacher.id, new PartitionKey(schoolTeacher.code));
- }
- }
- if (baseChange)
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(data, data.id, new PartitionKey("Base"));
- }
- return new ResponseData<List<OTeachers>>() { code = RespondCode.Ok, msg = "成功", data = schoolTeachersAdd.Select(x => new OTeachers { id = x.id, name = x.name, picture = x.picture, job = x.job, subjectIds = x.subjectIds, roles = x.roles, school = school }).ToList() };
- //return schoolTeachersAdd.Select(x => new OTeachers { id = x.id, name = x.name, picture = x.picture, job = x.job, subjectIds = x.subjectIds, roles = x.roles, school = school }).ToList();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetTeacherInfo() 参数:bizId:{bizId},school:{school},json:{json} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<OTeachers>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 查找课纲
- /// [ApiToken(Auth = "1601", Name = "查询课纲",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<OSyllabusTreeNode>>> GetSyllabus(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("volumeId", out JsonElement volumeId)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
- //if (!json.TryGetProperty("volumeCode", out JsonElement volumeCode)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
- if (!json.TryGetProperty("scope", out JsonElement scope)) return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
- var client = _azureCosmos.GetCosmosClient();
- OVolume volume = null;
- List<OSyllabusTreeNode> treeNodes = new();
- List<OSyllabusTreeNode> redt = new();
- if ($"{scope}".Equals("school"))
- {
- List<OSyllabus> delSyllabus = new();
- volume = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<OVolume>($"{volumeId}", new PartitionKey($"Volume-{school}"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<OSyllabus>(queryText: $"select value(c) from c where c.volumeId='{volumeId}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{volume.school}") }))
- {
- if (item.children.IsEmpty())
- {
- delSyllabus.Add(item);
- }
- else
- {
- List<OSyllabusTree> trees = SyllabusService.OListToTree(item.children);
- OSyllabusTreeNode otree = new() { id = item.id, scope = item.scope, trees = trees, volumeId = item.volumeId, codeval = volume.school };
- treeNodes.Add(otree);
- }
- }
- if (delSyllabus.IsNotEmpty())
- {
- await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsAsync<OSyllabus>(delSyllabus.Select(x => x.id).ToList(), $"Syllabus-{volume.school}");
- }
- }
- else
- return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.ParamsError, msg = "参数错误" };
- ResponseData<List<OSyllabusTreeNode>> responseData = new();
- //对课纲树形结构排序
- if (volume.syllabusIds.IsNotEmpty())
- {
- volume.syllabusIds.ForEach(x =>
- {
- for (int index = 0; index < treeNodes.Count; index++)
- {
- if (treeNodes[index].id == x)
- {
- redt.Add(treeNodes[index]);
- treeNodes.RemoveAt(index);
- }
- }
- });
- redt.AddRange(treeNodes);
- responseData = new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Ok, msg = "成功", data = redt };
- }
- else
- {
- responseData = new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Ok, msg = "成功", data = treeNodes };
- }
- return responseData;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetSyllabus() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<OSyllabusTreeNode>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 查询册别清单
- /// [ApiToken(Auth = "1602", Name = "查询册别",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<List<OVolume>>> GetVolumes(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- ResponseData<List<OVolume>> responseData = new();
- List<OVolume> ovolumes = new List<OVolume>();
- json.TryGetProperty("periodId", out JsonElement periodCode);
- json.TryGetProperty("subjectId", out JsonElement subjectCode);
- json.TryGetProperty("status", out JsonElement status);
- json.TryGetProperty("scope", out JsonElement scope);
- if (scope.GetString().Equals("school"))
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<OVolume>(queryText: $"select value(c) from c where c.status = {status} and c.periodId = '{periodCode}' and c.subjectId = '{subjectCode}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{school}") }))
- {
- ovolumes.Add(item);
- }
- }
- else { return new ResponseData<List<OVolume>>() { code = RespondCode.ParamsError, msg = "参数错误" }; };
- if (ovolumes.Count > 0)
- {
- responseData = new ResponseData<List<OVolume>>() { code = RespondCode.Ok, msg = "成功", data = ovolumes };
- }
- else
- responseData = new ResponseData<List<OVolume>>() { code = RespondCode.NotFound, msg = "未找到参数相关的数据" };
- return responseData;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetVolumes() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<List<OVolume>>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 查询知识
- /// [ApiToken(Auth = "1701", Name = "查询知识点",TName ="",EName ="", RWN = "R", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetKnowledges(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- try
- {
- ResponseData<dynamic> responseData = new();
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("periodId", out JsonElement periodId);
- if (!json.TryGetProperty("subjectId", out JsonElement subjectId)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误" };
- //if (!json.TryGetProperty("school_code", out JsonElement school_code)) return new ResponseData<List<Knowledge>>() { code = RespondCode.ParamsError, msg = "参数错误" };
- string code = $"Knowledge-{school}-{subjectId}";
- StringBuilder sql = new($"select value(c) from c");
- if (periodId.ValueKind.Equals(JsonValueKind.String))
- {
- sql.Append($" where c.periodId = '{periodId}'");
- }
- List<dynamic> knowledges = new();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Knowledge>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- knowledges.Add(new { item.periodId, item.subjectId, item.points, item.blocks, item.id });
- }
- if (knowledges.Any())
- {
- var data = knowledges.Select(x => new { });
- responseData = new() { code = RespondCode.Ok, msg = "成功", data = knowledges };
- }
- else
- {
- responseData = new() { code = RespondCode.NotFound, msg = "未找到相关" };
- }
- return responseData;
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetKnowledges() 参数:bizId:{bizId},school:{school},参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- /// <summary>
- /// 设置学生全面教育画像
- ///[ApiToken(Auth = "1901", Name = "设置学生全面教育画像", TName = "設置學生全面教育畫像", EName = "Set up students overall education portrait", RWN = "W", Limit = false)]
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> UpsertStudentPortrait(AzureCosmosFactory _azureCosmos, DingDing _dingDing,AzureRedisFactory _azureRedis , JsonElement json,string school=null)
- {
- try
- {
- ResponseData<dynamic> responseData = new();
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("schoolCode", out JsonElement schoolCode))
- {
- return responseData = new() { code = RespondCode.ParamsError, msg = "schoolCode为空" };
- }
- #if !DEBUG
- if (!string.IsNullOrWhiteSpace(school) && !school.Equals($"{schoolCode}", StringComparison.OrdinalIgnoreCase)) {
- return responseData = new() { code = RespondCode.ParamsError, msg = "授权学校与参数schoolCode不匹配" };
- }
- #endif
- if (!json.TryGetProperty("periodId", out JsonElement periodId))
- {
- return responseData = new() { code = RespondCode.ParamsError, msg = "periodId为空" };
- }
- if (!json.TryGetProperty("subjectId", out JsonElement subjectId))
- {
- return responseData = new() { code = RespondCode.ParamsError, msg = "subjectId为空" };
- }
- if (!json.TryGetProperty("students", out JsonElement _students) && !_students.ValueKind.Equals(JsonValueKind.Array))
- {
- return responseData = new() { code = RespondCode.ParamsError, msg = "students为空或格式错误" };
- }
- if (!$"{subjectId}".Equals("subject_sport") && !$"{subjectId}".Equals("subject_virtue") && !$"{subjectId}".Equals("subject_labour")
- && !$"{subjectId}".Equals("subject_intelligence")
- && !$"{subjectId}".Equals("subject_art"))
- {
- return responseData = new() { code = RespondCode.ParamsError, msg = "当前subjectId未开放画像业务" };
- }
- School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>($"{schoolCode}", new PartitionKey("Base"));
- List<PortraitStudent> students = _students.ToObject<List<PortraitStudent>>();
- if (students.IsEmpty()) {
- return responseData = new() { code = RespondCode.ParamsError, msg = "没有学生数据" };
- }
- List<(Student studentBase, PortraitStudent portrait)> studentsBases = new List<(Student, PortraitStudent)>();
- //学生信息不匹配的
- List<PortraitStudent> unmatchStuInfo = new List<PortraitStudent>();
- //学期不匹配的
- List<PortraitStudent> unmatchSemester = new List<PortraitStudent>();
- List<PortraitStudent> upsertDatas = new List<PortraitStudent>();
- //细项类型不匹配的
- List<PortraitStudent> unmatchItemScoreType = new List<PortraitStudent>();
- string stusql = $"select c.id,c.classId,c.name,c.year from c where c.id in ({string.Join(",", students.Select(f => $"'{f.studentId}'"))})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
- .GetItemQueryIteratorSql<Student>(queryText: stusql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{schoolCode}") }))
- {
- var student = students.Find(x => x.studentId.Equals(item.id));
- student.classId = item.classId;
- studentsBases.Add((item, student));
- //if ($"{item.classId}".Equals($"{student.classId}"))
- //{
- // studentsBases.Add((item,student));
- //}
- //else {
- // unmatchStuInfo.Add(student);
- //}
- }
- var unexist = students.FindAll(z => !studentsBases.Select(z => z.studentBase.id).Contains(z.studentId));
- if (unexist.Any())
- {
- unmatchStuInfo.AddRange(unexist);
- }
- Period period = schoolBase.period.Find(x => x.id.Equals($"{periodId}"));
- if (period == null)
- {
- return responseData = new() { code = RespondCode.NotFound, msg = "periodId不存在" };
- }
- else
- {
- bool periodChange = false;
- if (!period.semesters.Any())
- {
- //未设置学期则默认
- period.semesters.Add(new Semester
- {
- id = Guid.NewGuid().ToString(),
- name = "第一学期",
- start = 1,
- month = 9,
- day = 1
- }); period.semesters.Add(new Semester
- {
- id = Guid.NewGuid().ToString(),
- name = "第二学期",
- start = 0,
- month = 3,
- day = 1
- });
- periodChange = true;
- }
- //是否需要创建科目
- if (!$"{subjectId}".Equals("subject_art", StringComparison.OrdinalIgnoreCase) || !$"{subjectId}".Equals("subject_intelligence", StringComparison.OrdinalIgnoreCase))
- {
- var bind = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals($"{subjectId}", StringComparison.OrdinalIgnoreCase));
- if (bind == null)
- {
- string subjectName = "";
- switch (true)
- {
- case bool when $"{subjectId}".Equals("subject_sport"):
- subjectName = "体育";
- break;
- case bool when $"{subjectId}".Equals("subject_virtue"):
- subjectName = "德育";
- break;
- case bool when $"{subjectId}".Equals("subject_labour"):
- subjectName = "劳动";
- break;
- //case bool when $"{subjectId}".Equals("subject_music"):
- // subjectName = "音乐";
- // break;
- //case bool when $"{subjectId}".Equals("subject_painting"):
- // subjectName = "美术";
- // break;
- }
- if (!string.IsNullOrWhiteSpace(subjectName))
- {
- var subName = period.subjects.Find(z => z.name.Contains(subjectName));
- if (subName != null)
- {
- subName.bindId = $"{subjectId}";
- }
- else
- {
- period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = $"{subjectId}", type = 1 });
- }
- periodChange = true;
- }
- }
- }
- //是否要创建艺术类的 音乐,美术科目
- if ($"{subjectId}".Equals("subject_art", StringComparison.OrdinalIgnoreCase))
- {
- var bind_music = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals("subject_music", StringComparison.OrdinalIgnoreCase));
- if (bind_music != null)
- {
- string subjectName = "音乐";
- var subName = period.subjects.Find(z => z.name.Contains(subjectName));
- if (subName != null)
- {
- subName.bindId = "subject_music";
- }
- else
- {
- period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = "subject_music", type = 1 });
- }
- periodChange = true;
- }
- var bind_painting = period.subjects.Find(x => !string.IsNullOrWhiteSpace(x.bindId) && x.bindId.Equals("subject_painting", StringComparison.OrdinalIgnoreCase));
- if (bind_painting != null)
- {
- string subjectName = "美术";
- var subName = period.subjects.Find(z => z.name.Contains(subjectName));
- if (subName != null)
- {
- subName.bindId = "subject_painting";
- }
- else
- {
- period.subjects.Add(new Subject { id = Guid.NewGuid().ToString(), name = subjectName, bindId = "subject_painting", type = 1 });
- }
- periodChange = true;
- }
- }
- if (periodChange)
- {
- await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync<School>(schoolBase, $"{schoolCode}", new PartitionKey("Base"));
- }
- List<Semester> sortedSemesters = SchoolService.SortSemester(period.semesters);
- foreach (var studentInfo in studentsBases)
- {
- Student student = studentInfo.studentBase;
- string studentId = studentInfo.studentBase.id;
- string classId = studentInfo.studentBase.classId;
- List<SemesterData> semesterDatas = studentInfo.portrait.semesterData;
- if (semesterDatas.Any())
- {
- semesterDatas.ForEach(data =>
- {
- if (!string.IsNullOrWhiteSpace(data.semesterId))
- {
- var semester = period.semesters.Find(s => s.id.Equals(data.semesterId));
- //如果找到对应的semesterId则直接使用当前semesterId
- if (semester == null)
- {
- //先处理,最后再检查。
- data.semesterId = $"{data.semesterId}--semesterId学期无效";
- if (data.semester > 0)
- {
- int count = period.semesters.Count();
- if (count >= data.semester)
- {
- data.semesterId = sortedSemesters[data.semester - 1].id;
- }
- else
- {
- data.semesterId = $"{data.semester}--semester学期无效";
- }
- }
- else
- {
- data.semesterId = $"{data.semester}--semester学期无效";
- //无效的学期数
- }
- }
- }
- else
- {
- data.semesterId = $"{data.semesterId}--semesterId学期无效";
- if (data.semester > 0)
- {
- int count = period.semesters.Count();
- if (count >= data.semester)
- {
- data.semesterId = sortedSemesters[data.semester - 1].id;
- }
- else
- {
- data.semesterId = $"{data.semester}--semester学期无效";
- }
- }
- else
- {
- data.semesterId = $"{data.semester}--semester学期无效";
- //无效的学期数
- }
- }
- });
- var noSemesterDatas = semesterDatas.Where(z => z.semesterId.Contains("学期无效")).ToList();
- if (noSemesterDatas.Any())
- {
- unmatchSemester.Add(new PortraitStudent
- {
- studentId = studentInfo.portrait.studentId,
- name = studentInfo.portrait.name,
- classId = studentInfo.portrait.classId,
- semesterData = noSemesterDatas,
- });
- }
- var okSemesterDatas = semesterDatas.Where(z => !z.semesterId.Contains("学期无效"));
- if (okSemesterDatas.Any())
- {
- upsertDatas.Add(new PortraitStudent
- {
- studentId = studentInfo.portrait.studentId,
- name = studentInfo.portrait.name,
- classId = studentInfo.portrait.classId,
- semesterData = okSemesterDatas.ToList(),
- });
- }
- var ids = okSemesterDatas.Select(k => $"{k.year}-{k.semesterId}-{studentId}");
- if (ids.Any())
- {
- List<OverallEducation> overallEducations = new List<OverallEducation>();
- string sql = $"select value c from c where c.id in ({string.Join(",", ids.Select(f => $"'{f}'"))})" +
- $" and c.studentId ='{studentId}' and c.schoolCode='{schoolCode}' and c.periodId='{periodId}' and c.classId='{classId}'";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student)
- .GetItemQueryIteratorSql<OverallEducation>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"OverallEducation-{schoolCode}") }))
- {
- overallEducations.Add(item);
- }
- var nodbids = ids.Except(overallEducations.Select(x => x.id));
- var newDatas = semesterDatas.FindAll(k => nodbids.Contains($"{k.year}-{k.semesterId}-{studentId}"));
- var updateDatas = semesterDatas.FindAll(k => overallEducations.Select(z => z.id).Contains($"{k.year}-{k.semesterId}-{studentId}"));
- List<OverallEducation> newOverallEducations = new List<OverallEducation>();
- newDatas.ForEach(z =>
- {
- //处理新增的学生学期画像
- var overallEducation = newOverallEducations.Find(o => o.id.Equals($"{z.year}-{z.semesterId}-{studentId}") && o.code.Equals($"OverallEducation-{schoolCode}"));
- if (overallEducation == null)
- {
- overallEducation = new OverallEducation
- {
- id = $"{z.year}-{z.semesterId}-{studentId}",
- code = $"OverallEducation-{schoolCode}",
- pk = "OverallEducation",
- ttl = -1,
- name = student.name,
- classId = student.classId,
- schoolCode = $"{schoolCode}",
- semesterId = z.semesterId,
- year = z.year,
- periodId = $"{periodId}",
- stuYear = student.year,
- studentId = student.id,
- };
- newOverallEducations.Add(overallEducation);
- }
- });
- if (newOverallEducations.Any())
- {
- (newOverallEducations, unmatchItemScoreType) = FillSemesterData(studentId, $"{subjectId}", newOverallEducations, unmatchItemScoreType, newDatas,period);
- foreach (var edu in newOverallEducations)
- {
- await client.GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemAsync(edu, new PartitionKey(edu.code));
- string key = $"OverallEducation:{edu.schoolCode}:{edu.periodId}:{edu.year}:{edu.semesterId}:{edu.classId}";
- await _azureRedis.GetRedisClient(8).HashSetAsync(key, edu.studentId, edu.ToJsonString());
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 * 24, 0, 0));
- }
- }
- if (overallEducations.Any())
- {
- (overallEducations, unmatchItemScoreType) = FillSemesterData(studentId, $"{subjectId}", overallEducations, unmatchItemScoreType, updateDatas, period);
- foreach (var edu in overallEducations)
- {
- await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(edu, edu.id, new PartitionKey(edu.code));
- string key = $"OverallEducation:{edu.schoolCode}:{edu.periodId}:{edu.year}:{edu.semesterId}:{edu.classId}";
- await _azureRedis.GetRedisClient(8).HashSetAsync(key, edu.studentId, edu.ToJsonString());
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 * 24, 0, 0));
- }
- }
- }
- }
- }
- }
- return responseData = new() { data = new { unmatchStuInfo, unmatchSemester, unmatchItemScoreType, upsertDatas }, code = RespondCode.Ok, msg = "成功" };
- }
- catch (CosmosException cex) when (cex.StatusCode == System.Net.HttpStatusCode.NotFound)
- {
- return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "学校编码不存在" };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/UpsertStudentPortrait() ,参数json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务端异常" };
- }
- }
- public static (List<OverallEducation> overallEducations, List<PortraitStudent> unmatchItemScoreType) FillSemesterData(string studentId, string subjectId, List<OverallEducation> overallEducations,List<PortraitStudent> unmatchItemScoreType, List<SemesterData> semestersDatas,Period period)
- {
- foreach (var z in semestersDatas)
- {
- var oedu = overallEducations.Find(x => x.id.Equals($"{z.year}-{z.semesterId}-{studentId}"));
- if (oedu != null)
- {
- List<EducationScore> educationScores = null;
- switch (true)
- {
- case bool when $"{subjectId}".Equals("subject_sport"):
- educationScores = oedu.sports;
- break;
- case bool when $"{subjectId}".Equals("subject_virtue"):
- educationScores = oedu.virtue;
- break;
- case bool when $"{subjectId}".Equals("subject_labour"):
- educationScores = oedu.labour;
- break;
- case bool when $"{subjectId}".Equals("subject_intelligence"):
- {
- educationScores = oedu.intelligence;
- //对评测需要验证 细项的具体信息
- bool isunmatch = false;
- foreach (var v in z.itemScore)
- {
- var subject = period.subjects.Find(b => b.id.Equals(v.type));
- if (subject == null)
- {
- isunmatch = true;
- }
- }
- if (isunmatch)
- {
- unmatchItemScoreType.Add(new PortraitStudent { classId = oedu.classId, name = oedu.name, studentId = oedu.studentId, semesterData = new List<SemesterData> { z } });
- continue;
- }
- break;
- }
- case bool when $"{subjectId}".Equals("subject_art"):
- {
- educationScores = oedu.art;
- //对艺术评测需要验证 细项的具体信息
- bool isunmatch = false;
- foreach (var v in z.itemScore)
- {
- var subject = period.subjects.Find(b =>!string .IsNullOrWhiteSpace(b.bindId) && b.bindId.Equals(v.type));
- if (subject == null)
- {
- isunmatch = true;
- }
- }
- if (isunmatch)
- {
- unmatchItemScoreType.Add(new PortraitStudent { classId = oedu.classId, name = oedu.name, studentId = oedu.studentId, semesterData = new List<SemesterData> { z } });
- continue;
- }
- break;
- }
- default:
- educationScores = new List<EducationScore>();
- break;
- }
- var edu = educationScores.Find(m => m.examId.Equals(z.examId));
- z.totalScore = z.totalScore <= 0 ? 100 : z.totalScore;
- if (edu == null)
- {
- edu = new EducationScore();
- educationScores.Add(edu);
- }
- edu.examId = z.examId;
- edu.examDate = z.examDate;
- edu.examName = z.examName;
- edu.examType = z.examType;
- edu.excellenceRate = z.excellenceRate;
- edu.totalScore = z.totalScore;
- edu.rate = z.sumScore / z.totalScore;
- edu.level = z.sumScore / z.totalScore;
- edu.sumScore = z.sumScore;
- edu.passRate = z.passRate;
- edu.itemScore = z.itemScore;
- }
- }
- return (overallEducations, unmatchItemScoreType);
- }
- public static void GenApiTableRecord(AzureStorageFactory azureStorage)
- {
- //在开发模式时,自检 [ApiToken(Auth = "1")] 有重复的接口 https://teammodelos.table.core.chinacloudapi.cn/IESOpenApi
- (List<OpenApi> openApis, List<ApiTokenAttribute> attributes) = ReflectorExtensions.GetOpenApi(new string[] { "TEAMModelOS" });
- openApis.GroupBy(x => $"{x.PartitionKey}{x.RowKey}").ToList().ForEach(x =>
- {
- if (x.Count() > 1)
- {
- throw new Exception($"接口Auth重复定义{x.ToList()}");
- }
- });
- var table = azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
- openApis = openApis.OrderBy(x => x.RowKey).ToList();
- string tbqurey = $"PartitionKey {QueryComparisons.Equal} 'IES5-API' and RowKey {QueryComparisons.GreaterThanOrEqual} '{openApis.First().RowKey}' and RowKey {QueryComparisons.LessThanOrEqual} '{openApis.Last().RowKey}' ";
- var apiResult = table.ExecuteQuerySegmented(new TableQuery<OpenApi>().Where(tbqurey), null);
- List<OpenApi> apis = apiResult.Results;
- //数据库历史数据处理
- apis.ForEach(x =>
- {
- var api = openApis.Find(z => z.RowKey.Equals(x.RowKey));
- if (api != null)
- {
- x.auth = api.auth;
- x.name = api.name;
- x.type = api.type;
- x.url = api.url;
- x.method = api.method;
- }
- });
- openApis.RemoveAll(x => apis.Select(z => z.RowKey).Contains(x.RowKey));
- openApis.AddRange(apis);
- _ = table.SaveOrUpdateAll<OpenApi>(openApis);
- string dataopenApis = openApis.ToJsonString();
- (List<WebHook> webHooks, List<ApiTokenAttribute> _attributes) = ReflectorExtensions.GetWebHook(new string[] { "TEAMModelOS.SDK" });
- webHooks.GroupBy(x => $"{x.PartitionKey}{x.RowKey}").ToList().ForEach(x =>
- {
- if (x.Count() > 1)
- {
- throw new Exception($"接口Auth重复定义{x.ToList()}");
- }
- });
- webHooks = webHooks.OrderBy(x => x.RowKey).ToList();
- tbqurey = $"PartitionKey {QueryComparisons.Equal} 'IES5-WEBHOOK' and RowKey {QueryComparisons.GreaterThanOrEqual} '{webHooks.First().RowKey}' and RowKey {QueryComparisons.LessThanOrEqual} '{webHooks.Last().RowKey}' ";
- var hookResult = table.ExecuteQuerySegmented(new TableQuery<WebHook>().Where(tbqurey), null);
- List<WebHook> hooks = hookResult.Results;
- //数据库历史数据处理
- hooks.ForEach(x =>
- {
- var api = webHooks.Find(z => z.RowKey.Equals(x.RowKey));
- if (api != null)
- {
- x.auth = api.auth;
- x.name = api.name;
- x.ename = api.ename;
- x.tname = api.tname;
- x.type = api.type;
- x.url = api.url;
- x.method = api.method;
- x.notice = api.notice;
- }
- });
- webHooks.RemoveAll(x => hooks.Select(z => z.RowKey).Contains(x.RowKey));
- webHooks.AddRange(hooks);
- _ = table.SaveOrUpdateAll<WebHook>(webHooks);
- string datawebHooks = webHooks.ToJsonString();
- }
- /// <summary>
- /// 学生登录信息
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetLoginStuInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, Option _option, string bizId, string school, JsonElement json)
- {
- if (!json.TryGetProperty("idToken", out JsonElement _idToken)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "idToken参数错误", data = null };
- JwtSecurityToken jwt = new($"{_idToken}");
- var iss = jwt.Payload.Iss;
- var stuId = jwt.Payload.Sub;
- var scId = jwt.Payload.Azp;
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //if (!string.IsNullOrWhiteSpace($"{_idToken}") && JwtAuthExtension.ValidateApiToken($"{_idToken}", _option.JwtSecretKey))
- //{
- // JwtSecurityToken jwt = new($"{_idToken}");
- //}
- OStudent student = new();
- jwt.Payload.TryGetValue("name", out object stuName);
- jwt.Payload.TryGetValue("picture", out object stuPicture);
- if (!jwt.Payload.TryGetValue("scope", out object scope)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:scope", data = null };
- if (!jwt.Payload.TryGetValue("roles", out object _roles)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:roles", data = null };
- jwt.Payload.TryGetValue("permissions", out object permissions);
- jwt.Payload.TryGetValue("standard", out object standard);
- jwt.Payload.TryGetValue("area", out object area);
- jwt.Payload.TryGetValue("website", out object website);
- List<string> roles = $"{_roles}".ToObject<List<string>>();
- if (roles.Contains("student") && $"{scope}".Equals("student"))
- {
- if (!string.IsNullOrEmpty(stuId) && !string.IsNullOrEmpty(scId))
- {
- if (school.Equals(scId))
- {
- var responseStu = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(stuId, new PartitionKey($"Base-{scId}"));
- if (responseStu.StatusCode == System.Net.HttpStatusCode.OK)
- {
- JsonDocument jsonD = JsonDocument.Parse(responseStu.Content);
- student = jsonD.RootElement.ToObject<OStudent>();
- switch (student.gender)
- {
- case "M":
- student.gender = "男";
- break;
- case "F":
- student.gender = "女";
- break;
- case "N":
- student.gender = "保密";
- break;
- }
- }
- else
- { return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "未找到该学生", data = new { id = stuId, schoolId = scId } }; }
- }
- else
- { return new ResponseData<dynamic>() { code = RespondCode.NotFound, msg = "headers和idToken中的学校ID不匹配", data = null }; }
- }
- else
- { return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:Sub/scId", data = null }; }
- }
- else
- { return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "参数错误:roles/Azp", data = null }; }
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = student };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetLoginStuInfo() 参数:stu:{stuId},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务器错误" };
- }
- }
- /// <summary>
- /// 获取学生详细信息
- /// </summary>
- /// <param name="_azureCosmos"></param>
- /// <param name="_dingDing"></param>
- /// <param name="bizId"></param>
- /// <param name="school"></param>
- /// <param name="json"></param>
- /// <returns></returns>
- public static async Task<ResponseData<dynamic>> GetStudentInfo(AzureCosmosFactory _azureCosmos, DingDing _dingDing, string bizId, string school, JsonElement json)
- {
- if (!json.TryGetProperty("ids", out JsonElement _ids)) return new ResponseData<dynamic>() { code = RespondCode.ParamsError, msg = "idToken参数错误", data = null };
- try
- {
- List<string> ids = _ids.ToObject<List<string>>();
- List<OStudent> student = new();
- //List<OStudent> tmdId = new();
- string sqlStu = $"select value(c) from c ";
- if (ids.Count > 0)
- sqlStu = $"select value(c) from c where c.id in ({string.Join(",", ids.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<OStudent>(queryText: sqlStu, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{school}") }))
- {
- student.Add(item);
- }
- //string sqlTmd = $"select value(c) from c join s in c.schools where c.id in ({string.Join(",", ids.Select(s => $"'{s}'"))}) and s.schoolId='{school}'";
- //await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIteratorSql<OStudent>(queryText: sqlTmd, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- //{
- // tmdId.Add(item);
- //}
- return new ResponseData<dynamic>() { code = RespondCode.Ok, msg = "成功", data = student };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OpenApi,{Environment.GetEnvironmentVariable("Option:Location")} OpenApiService/GetLoginStuInfo() 参数:学生id集合:{_ids},school:{school},json:{json.ToJsonString()} \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return new ResponseData<dynamic>() { code = RespondCode.Error, msg = "服务器错误" };
- }
- }
- public static async Task<ResponseData<dynamic>> UpsertSchoolItem(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureRedisFactory azureRedis, JsonElement jsonElement, string school)
- {
- return new ResponseData<dynamic>() { };
- }
- }
- /*
- {
- "id": "", //题目id,id值为空则新增,不为空尝试更新,更新失败则新增
- "level": 1, //1-5题目难度
- "knowledge": [
- "知识点1",
- "知识点2"
- ], //知识点
- "answer": [
- "答案1",
- "答案2"
- ], //答案, "单选题","多选题","有序多选题","判断题"等的答案为[A,B,C,D,E]等数组,如果是填空题答案为字符串数组,问答题答案为字符串。
- "explain": "解析",
- "type": "single", //题目类型,"single": "单选题", "multiple": "多选题", "sortmultiple": "有序多选题", "judge": "判断题", "complete": "填空题", "subjective": "问答题", "compose": "综合题"
- "pid": "综合题父级题目id",
- "field": 1, //布鲁姆认知层次 1:记忆|2:理解|3:应用|4:分析|:5评价|6:创造
- "subject": "语文", //学科,语文/数学/英语/物理/化学/地理/历史/生物/政治, 如果有其他学科,按学科名称传递即可。
- "grade": [
- "1",
- "2",
- "3",
- "4"
- ], //年级,1-6年级/1-5年级(小学),7-9年级/6-9年级(初中),10-12年级(高中)
- "question": "题干信息",
- "option":[{"code":"A","value":"选项A的内容"},{ "code":"B","value":"选项B的内容"}],//单选,多选,有序多选题,判断题的选项。其中判断题可为[{"code":"A","value":"正确/对"},{"code":"B","value":"错误/错"}]
- "children":[
- {}//子题目,包含题型"单选题", "多选题", "有序多选题", "判断题", "填空题", "问答题"
- ]
- }
- **/
- /// <summary>
- ///
- ///
- /// </summary>
- public class OItem
- {
- /// <summary>
- /// //题目id,id值为空则新增,不为空尝试更新,更新失败则新增
- /// </summary>
- public string id { get; set; }
- /// <summary>
- /// 1-5题目难度
- /// </summary>
- public int level { get; set; }
- /// <summary>
- /// 知识点
- /// </summary>
- public List<string> knowledge { get; set; } = new List<string>();
- /// <summary>
- /// 答案, "单选题","多选题","有序多选题","判断题"等的答案为[A,B,C,D,E]等数组,如果是填空题答案为字符串数组,问答题答案为字符串。
- /// </summary>
- public List<string> answer { get; set; } = new List<string>();
- /// <summary>
- /// 解析
- /// </summary>
- public string explain { get; set; }
- /// <summary>
- /// 题目类型,"single": "单选题", "multiple": "多选题", "sortmultiple": "有序多选题", "judge": "判断题", "complete": "填空题", "subjective": "问答题", "compose": "综合题"
- /// </summary>
- public string type { get; set; }
- /// <summary>
- /// 综合题父级题目id,当前题目是某一综合题的子题时才填写,否则为null,
- /// </summary>
- public string pid { get; set; }
- /// <summary>
- /// 布鲁姆认知层次 1:记忆|2:理解|3:应用|4:分析|:5评价|6:创造
- /// </summary>
- public int field { get; set; } = 1;
- /// <summary>
- /// 学科,语文/数学/英语/物理/化学/地理/历史/生物/政治, 如果有其他学科,按学科名称传递即可。
- /// </summary>
- public string subject { get; set; }
- /// <summary>
- /// 年级,1-6年级/1-5年级(小学),7-9年级/6-9年级(初中),10-12年级(高中)
- /// </summary>
- public List<int> grade { get; set; } = new List<int>();
- /// <summary>
- /// 题干信息
- /// </summary>
- public string question { get; set; }
- /// <summary>
- /// 单选,多选,有序多选题,判断题的选项。其中判断题可为[{"code":"A","value":"正确/对"},{"code":"B","value":"错误/错"}]
- /// </summary>
- public List<CodeValue> option { get; set; } = new List<CodeValue>();
- /// <summary>
- /// 子题目,包含题型"单选题", "多选题", "有序多选题", "判断题", "填空题", "问答题"
- /// </summary>
- public List<OItem> children { get; set; } = new List<OItem>();
- }
- public class OCourseBase
- {
- public string tmdname { get; set; }
- public string courseName { get; set; }
- public int attendCount { get; set; }
- public int mCount { get; set; }
- public List<string> groups { get; set; }
- public long time { get; set; }
- public List<Events> eves { get; set; }
- public List<Videos> videos { get; set; }
- }
- public class Events
- {
- public string @event { get; set; }
- public int freq { get; set; }
- public long createTime { get; set; }
- }
- public class Videos
- {
- public string videoName { get; set; }
- public string video { get; set; }
- public int duration { get; set; }
- public long startTime { get; set; }
- }
- }
|