1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059 |
- using Azure.Cosmos;
- using HTEXLib.COMM.Helpers;
- using MathNet.Numerics.LinearAlgebra;
- using MathNet.Numerics.LinearAlgebra.Double;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using Newtonsoft.Json;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Net.Http.Json;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Models;
- using TEAMModelBI.Tool;
- using TEAMModelBI.Tool.CosmosBank;
- using TEAMModelBI.Tool.Extension;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Service.BI;
- namespace TEAMModelBI.Controllers.BISchool
- {
- [Route("schoolcheck")]
- [ApiController]
- public class SchoolController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly IConfiguration _configuration;
- private readonly NotificationService _notificationService;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly HttpClient _httpClient;
- public SchoolController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, AzureRedisFactory azureRedis, IConfiguration configuration, NotificationService notificationService, CoreAPIHttpService coreAPIHttpService, HttpClient httpClient)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _notificationService = notificationService;
- _coreAPIHttpService = coreAPIHttpService;
- _httpClient = httpClient;
- }
- /// <summary>
- /// 查询未加入区域的学校 //已对接
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-notarea")]
- public async Task<IActionResult> GetNotAreaSchool(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("areaId", out JsonElement areaId);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- //默认不指定返回大小
- int? pageSize = null;
- string continuationToken = string.Empty;
- string pageToken = default;
- if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
- {
- if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
- {
- pageSize = tempPageSize;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (pageSize != null && pageSize.Value > 0)
- {
- iscontinuation = true;
- }
- if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
- {
- pageToken = ContToken.GetString();
- }
- StringBuilder sqltxt = new($"SELECT c.id,c.name,c.schoolCode,c.province,c.city,c.dist,c.picture,c.period,c.areaId,c.standard,c.manyAreas FROM c");
- if (!string.IsNullOrEmpty($"{areaId}"))
- {
- sqltxt.Append($" WHERE c.areaId !='{areaId}'");
- }
- else
- {
- sqltxt.Append($" WHERE c.areaId ='' and c.standard = ''");
- }
- List<NotAreaSchool> tempNotAreaSchools = new();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: sqltxt.ToString(), continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- NotAreaSchool notAreaSchool = new()
- {
- id = obj.GetProperty("id").GetString(),
- name = obj.GetProperty("name").GetString(),
- schoolCode = obj.GetProperty("schoolCode").GetString(),
- picture = obj.GetProperty("picture").GetString(),
- period = obj.GetProperty("period").ToObject<List<Period>>().Select(x => x.name).ToList(),
- province = obj.GetProperty("province").GetString(),
- city = obj.GetProperty("city").GetString(),
- dist = obj.GetProperty("dist").GetString(),
- areaId = obj.GetProperty("areaId").GetString(),
- standard = obj.GetProperty("standard").GetString()
- };
- try
- {
- notAreaSchool.areas = obj.GetProperty("manyAreas").ToObject<List<SchoolArea>>();
- }
- catch { }
- tempNotAreaSchools.Add(notAreaSchool);
- }
- if (iscontinuation)
- {
- continuationToken = item.GetContinuationToken();
- break;
- }
- }
- }
- List<NotAreaSchool> notAreaSchools = new();
- tempNotAreaSchools.ForEach(nas =>
- {
- if (nas.areas == null)
- notAreaSchools.Add(nas);
- else
- {
- var not = nas.areas.Find(f => f.areaId == $"{areaId}");
- if (not == null)
- notAreaSchools.Add(nas);
- }
- });
- //if (!string.IsNullOrEmpty($"{areaId}"))
- // notAreaSchools = notAreaSchools.Select(na => new NotAreaSchool { id = na.id, name = na.name, schoolCode = na.schoolCode, picture = na.picture, period = na.period, province = na.province, city = na.city = na.city, dist = na.dist, manyAreas = new List<ManyArea> { na.manyAreas.Find(m => m.areaId != $"{areaId}") } }).ToList();
- return Ok(new { state = 200, continuationToken, pageSize, notAreaSchools });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-notarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 学校加入区 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales")]
- [HttpPost("set-schooljoinarea")]
- public async Task<IActionResult> SetSchoolJoinArea(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("standard", out JsonElement standard)) return BadRequest();
- if (!jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode)) return BadRequest();
- if (!jsonElement.TryGetProperty("areaId", out JsonElement _areaId)) return BadRequest();
- jsonElement.TryGetProperty("areaName", out JsonElement areaName);
- jsonElement.TryGetProperty("isDefault", out JsonElement isDefault);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var isManyArea = false;
- if (!string.IsNullOrEmpty($"{isDefault}"))
- {
- isManyArea = true;
- }
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- List<string> schoolCodes = _schoolCode.ToObject<List<string>>();
- StringBuilder msg = new($"{_tmdName}【{_tmdId}】操作学校加入区域功能,加入的区域:{standard},学校ID:{string.Join("|", schoolCodes.ToArray())}");
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- var responseSet = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemStreamAsync($"{_areaId}", new PartitionKey("AreaSetting"));
- if (responseSet.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(responseSet.ContentStream);
- AreaSetting delSet = fileJson.ToObject<AreaSetting>();
- if (!string.IsNullOrEmpty(delSet.accessConfig))
- return Ok(new { state = 401, msg = "区域已经规定了,不能切换能能力" });
- }
- if (schoolCodes.Count > 0)
- {
- foreach (var tempCode in schoolCodes)
- {
- School school = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(tempCode, new PartitionKey("Base"));
- if (school != null)
- {
- if (isManyArea)
- {
- if (school.areas == null)
- school.areas = new List<SchoolArea>() { new SchoolArea() { areaId = $"{_areaId}", name = $"{areaName}", status = "join" } };
- else
- {
- var marea = school.areas.Find(ma => ma.areaId == $"{_areaId}");
- if (marea == null)
- school.areas.Add(new SchoolArea() { areaId = $"{_areaId}", name = $"{areaName}", status = $"join" });
- }
- }
- school.standard = $"{standard}";
- school.areaId = $"{_areaId}";
- msg.Append($"{school.name}【{school.id}】学校移除多区域的名单:");
- List<Teacher> teachers = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(queryText: $"SELECT value(c) FROM c join s in c.schools where s.schoolId ='{school.id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- teachers.Add(item);
- }
- foreach (var item in teachers)
- {
- msg.Append($"{item.name}[{item.id}]");
- var tchSchool = item.schools.Find(f => f.schoolId.Equals($"{school.id}") && f.areaId.Equals($"{_areaId}"));
- if (tchSchool == null)
- {
- Teacher.TeacherSchool teacherSchool = new() { schoolId = school.id, name = school.name, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = school.picture, areaId = school.areaId };
- item.schools.Add(teacherSchool);
- await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(item, item.id, new PartitionKey("Base"));
- }
- }
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey(school.code));
- }
- }
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", msg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/set-schooljoinarea \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据学校编号查询学校信息 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-schoolid")]
- public async Task<IActionResult> GetSchoolId(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- AssistSchool schoolAssists = new(); //返回学校列表集合
- string sqlTxt = $"select c.id,c.code,c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.size,c.address,c.picture,c.type,c.scale,c.areaId,c.standard,c.period from c where c.id='{schoolId}'";
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<AssistSchool>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schoolAssists = itemSchool;
- }
- if (schoolAssists.id != null)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolAssists.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssists.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssists.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssists.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- }
- schoolAssists.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolAssists.id, "assist");
- schoolAssists.lessonCount = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(count(c.id)) from c ", $"LessonRecord-{schoolAssists.id}");
- return Ok(new { state = 200, schoolAssists });
- }
- else return Ok(new { state = 404, msg = "未找到该学校!" });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /schoolcheck/get-schoolid \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 修改学校信息 //已对接
- /// </summary>
- /// <param name="school"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc,assist,sales")]
- [HttpPost("upd-school")]
- public async Task<IActionResult> UpdSchool(School school, [FromHeader] string site)
- {
- try
- {
- School schoolInfo = new School();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- string _auth = HttpContext.GetXAuth("AuthToken");
- var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey($"Base"));
- if (response.Status == 200)
- {
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.schools where A1.schoolId='{school.id}'";
- List<Teacher> teachers = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<Teacher>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- teachers.Add(item);
- }
- foreach (var item in teachers)
- {
- Teacher.TeacherSchool teacherSchool = item.schools.Find(x => x.schoolId.Equals(school.id));
- if (teacherSchool != null)
- {
- teacherSchool.name = school.name;
- teacherSchool.picture = school.picture;
- teacherSchool.areaId = school.areaId;
- }
- await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(item, item.id, new PartitionKey($"Base"));
- }
- schoolInfo = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey($"Base"));
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "school-update", $"{tmdName}【{tmdId}】修改学校信息,学校和ID:{school.name}【{school.id}】", _dingDing, httpContext: HttpContext);
- }
- else return Ok(new { state = 400, message = "请求错误!" });
- return Ok(new { state = 200, schoolInfo });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/upd-school \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 顾问学校空间使用情况
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-assistspace")]
- public async Task<IActionResult> GetAssistSchoolSpace(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- List<string> schools = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- List<SchoolSpace> schoolSpaces = new();
- foreach (var sid in schools)
- {
- School school = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(sid, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- long teach = 0;
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{sid}") }))
- {
- var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
- {
- teach = _size.GetInt32();
- break;
- }
- }
- }
- SchoolSpace schoolSpace = new() { id = sid, name = school != null ? school.name : sid };
- Space space = new Space();
- long blobsize = 0; //使用大小
- RedisValue value = default;
- value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", sid);
- if (value != default && !value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out blobsize))
- {
- }
- }
- else
- {
- var client = _azureStorage.GetBlobContainerClient(sid);
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- space.useSize = (long)size.Item1; space.tSize = teach; space.catalogSize = size.Item2;
- schoolSpace.space = space;
- schoolSpaces.Add(schoolSpace);
- continue;
- }
- Dictionary<string, double?> catalog = new Dictionary<string, double?>();
- SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{sid}");
- if (Scores != null)
- {
- foreach (var score in Scores)
- {
- double val = score.Score;
- string key = score.Element.ToString();
- catalog.Add(key, val);
- }
- space.useSize = blobsize; space.tSize = teach; space.catalogSize = catalog;
- schoolSpace.space = space;
- schoolSpaces.Add(schoolSpace);
- continue;
- }
- else
- {
- var client = _azureStorage.GetBlobContainerClient(sid);
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", sid, size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{sid}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{sid}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- space.useSize = (long)size.Item1;
- space.tSize = teach;
- space.catalogSize = size.Item2;
- schoolSpace.space = space;
- schoolSpaces.Add(schoolSpace);
- continue;
- }
- }
- return Ok(new { state = 200, schoolSpaces });
- }
- /// <summary>
- /// 修改顾问学校 //已经对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-aistschool")]
- public async Task<IActionResult> SetAssistSchool(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement parKey)) return BadRequest();
- jsonElement.TryGetProperty("userId", out JsonElement userId);
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (!jsonElement.TryGetProperty("schoolIds", out JsonElement jsSchoolIds)) return BadRequest();
- if (!jsonElement.TryGetProperty("busy", out JsonElement busy)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- List<string> schoolIds = jsSchoolIds.ToObject<List<string>>();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var cosmosClient = _azureCosmos.GetCosmosClient();
- string divide = _option.Location;
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- Dictionary<string, object> dic = new() { { "PartitionKey", $"{parKey}" } };
- if (!string.IsNullOrEmpty($"{userId}"))
- {
- dic.Add("userId", $"{userId}");
- }
- if (string.IsNullOrEmpty($"{userId}") && string.IsNullOrEmpty($"{tmdId}"))
- {
- return Ok(new { state = 400, msg = "钉钉账户或醍摩豆账户需要至少要传一个!" });
- }
- Dictionary<string, List<string>> noSchools = new();
- List<DingDingUserInfo> ddUserInfoList = await table.FindListByDict<DingDingUserInfo>(dic);
- List<DingDingUserInfo> updUsers = new();
- if (ddUserInfoList.Count > 0)
- {
- foreach (var ddInfo in ddUserInfoList)
- {
- if (schoolIds.Count > 0)
- {
- if (string.IsNullOrEmpty(ddInfo.tmdId))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddInfo.mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- ddInfo.tmdId = coreUser.id;
- ddInfo.tmdName = coreUser.name;
- ddInfo.tmdMobile = coreUser.mobile;
- ddInfo.picture = coreUser.picture;
- ddInfo.mail = coreUser.mail;
- }
- else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- //List<string> moblie = new() { $"{ddInfo.mobile}" };
- //var content = new StringContent(moblie.ToJsonString(), Encoding.UTF8, "application/json");
- //string json = await _coreAPIHttpService.GetUserInfos(content);
- //if (!string.IsNullOrEmpty(json))
- //{
- // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
- // foreach (var tmd in json_id)
- // {
- // ddInfo.tmdId = tmd.GetProperty("id").ToString();
- // ddInfo.tmdName = tmd.GetProperty("name").ToString();
- // ddInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
- // ddInfo.picture = tmd.GetProperty("picture").ToString();
- // ddInfo.mail = tmd.GetProperty("mail").ToString();
- // }
- //}
- //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- }
- List<string> noSchool = await SchoolWay.SchoolAdviser(cosmosClient, ddInfo, schoolIds, $"{busy}");
- if (noSchool.Count > 0)
- {
- noSchools.Add(ddInfo.tmdId, noSchool);
- }
- }
- List<string> userSchoolAdv = new(ddInfo.schoolIds.Split("|", StringSplitOptions.RemoveEmptyEntries));
- if ($"{busy}".Equals("add"))
- {
- userSchoolAdv.AddRange(schoolIds);
- ddInfo.schoolIds = userSchoolAdv.Count > 0 ? string.Join("|", userSchoolAdv) : "";
- }
- if ($"{busy}".Equals("del"))
- {
- var temp = userSchoolAdv.Where(p => !schoolIds.Any(x => x == p)).ToList();
- ddInfo.schoolIds = temp.Count > 0 ? string.Join("|", temp) : "";
- }
- updUsers.Add(ddInfo);
- }
- }
- updUsers = await table.SaveOrUpdateAll(updUsers);
- if (noSchools.Count > 0)
- return Ok(new { state = 201, recUsers = updUsers, noSchools });
- else
- return Ok(new { state = 200, recUsers = updUsers });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-aistschool \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据学校ID查学校管理员信息 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-scmanage")]
- public async Task<IActionResult> GetSchoolManage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- List<BaseInfo> scManages = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<BaseInfo>(queryText: $"select c.id,c.name,c.picture from c where ARRAY_CONTAINS(c.roles,'admin',true) and c.code='Teacher-{scId}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{scId}") }))
- {
- scManages.Add(item);
- }
- return Ok(new { state = RespondCode.Ok, scManages });
- }
- /// <summary>
- /// 设置学校管理员 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-manage")]
- public async Task<IActionResult> SetSchoolManage(JsonElement jsonElement)
- {
- try
- {
- var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- if (!jsonElement.TryGetProperty("tmdName", out JsonElement tmdName)) return BadRequest();
- jsonElement.TryGetProperty("tmdPic", out JsonElement picture);
- if (!jsonElement.TryGetProperty("scId", out JsonElement schoolId)) return BadRequest();
- if (!jsonElement.TryGetProperty("scName", out JsonElement schoolName)) return BadRequest();
- jsonElement.TryGetProperty("scPic", out JsonElement scpicture);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- StringBuilder strMsg = new($"{_tmdName}【{_tmdId}】账户将{tmdName}【{tmdId}】");
- Teacher teacher = null;
- SchoolTeacher schoolTeacher = null;
- var resTeacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Base"));
- if (resTeacher.Status == 200)
- {
- using var tchJson = await JsonDocument.ParseAsync(resTeacher.ContentStream);
- teacher = tchJson.ToObject<Teacher>();
- var existArea = teacher.schools.Find(f => f.schoolId.Equals($"{schoolId}"));
- if (existArea == null)
- {
- teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = "" });
- teacher = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- strMsg.Append($"账户基础信息添加学校,");
- }
- }
- else
- {
- teacher.id = $"{tmdId}";
- teacher.name = $"{tmdName}";
- teacher.picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}";
- teacher.pk = "Base";
- teacher.code = "Base";
- teacher.size = 1;
- teacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- //教师存在,在该教师信息中添加要管理的学校信息
- teacher.schools.Add(new Teacher.TeacherSchool { schoolId = $"{schoolId}", name = $"{schoolName}", status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), picture = string.IsNullOrEmpty($"{scpicture}") ? "" : $"{scpicture}", areaId = "" });
- teacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- strMsg.Append($"添加基础信息,并添加学校");
- }
- if (teacher != null)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{schoolId}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- schoolTeacher = json.ToObject<SchoolTeacher>();
- if (!schoolTeacher.roles.Contains("admin"))
- {
- schoolTeacher.roles.Add("admin");
- schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, schoolTeacher.id, new PartitionKey($"Teacher-{schoolId}"));
- strMsg.Append($"设置管理员,学校信息{schoolName}【{schoolId}】");
- }
- else
- return Ok(new { state = RespondCode.Conflict, schoolTeacher = "已经是该校的管理人员" });
- }
- else
- {
- schoolTeacher = new()
- {
- id = $"{tmdId}",
- code = $"Teacher-{schoolId}",
- roles = new List<string> { "admin", "teacher" },
- job = "管理员",
- name = $"{tmdName}",
- picture = string.IsNullOrEmpty($"{picture}") ? "" : $"{picture}",
- status = "join",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- pk = "Teacher",
- ttl = -1
- };
- schoolTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<SchoolTeacher>(schoolTeacher, new PartitionKey($"Teacher-{schoolId}"));
- strMsg.Append($"新建学校管理员,学校信息{schoolName}【{schoolId}】");
- }
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】账户创建{tmdName}【{tmdName}】账户,并设学校管理员。学校ID:{schoolId}。", _dingDing, httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, teacher, schoolTeacher });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-schoolme \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 移除学校管理员 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("del-manage")]
- public async Task<IActionResult> DelSchoolManage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- SchoolTeacher scTeacher = null;
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{tmdId}", new PartitionKey($"Teacher-{scId}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- scTeacher = json.ToObject<SchoolTeacher>();
- if (scTeacher.roles.Contains("admin"))
- {
- scTeacher.roles.Remove("admin");
- scTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(scTeacher, scTeacher.id, new PartitionKey($"Teacher-{scId}"));
- }
- else
- return Ok(new { state = RespondCode.NotFound, msg = "该账户不是管理员" });
- }
- else
- return Ok(new { state = RespondCode.NotFound, msg = "未找到醍摩豆管理员信息" });
- return Ok(new { state = RespondCode.Ok, scTeacher });
- }
- /// <summary>
- /// 删除学校、学校相关的教师、学生 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,rdc")]
- [HttpPost("set-del")]
- public async Task<IActionResult> DelSchool(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- List<string> schools = schoolId.ToObject<List<string>>();
- jsonElement.TryGetProperty("site", out JsonElement site);
- string _auth = HttpContext.GetXAuth("AuthToken");
- var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- StringBuilder msg = new();
- List<DelSchoolRel> delSchoolRels = new();
- foreach (var tempId in schools)
- {
- List<string> scTchIds = new();
- List<string> scStuIds = new();
- string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{tempId}") }))
- {
- scTchIds.Add(item);
- }
- string scStuSql = $"select value(c.id) from c";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Student").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{tempId}") }))
- {
- scStuIds.Add(item);
- }
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{tempId}", new PartitionKey($"Base"));
- if (response.Status == 204)
- msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{tempId}");
- else
- delSchoolRels.Add(new DelSchoolRel() { id = $"{tempId}", code = "Base", type = 1, status = response.Status });
- foreach (var item in scTchIds)
- {
- //学校教师信息
- var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{tempId}"));
- if (tchRespnse.Status == 204)
- msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
- else
- delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{tempId}", type = 2, status = response.Status });
- //教师基础信息
- var tchBaseResponse = await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync($"{item}", new PartitionKey("Base"));
- if (tchBaseResponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- Teacher teacher = json.ToObject<Teacher>();
- var tempSc = teacher.schools.Find(f => f.schoolId.Equals($"{tempId}"));
- if (tempSc != null)
- {
- teacher.schools.Remove(tempSc);
- await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
- }
- }
- else
- delSchoolRels.Add(new DelSchoolRel { id = $"{item}", code = "Base", type = 2, status = response.Status });
- }
- //删除学校学生
- foreach (var item in scStuIds)
- {
- var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{tempId}"));
- if (stuRespnse.Status == 204)
- msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
- else
- delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{tempId}", type = 3, status = response.Status });
- }
- }
- //string scTecSql = $"select value(c.id) from c where ARRAY_LENGTH(c.roles) > 0 and c.status = 'join'";
- //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scTecSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{schoolId}") }))
- //{
- // scTchIds.Add(item);
- //}
- //string scStuSql = $"select value(c.id) from c";
- //await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<string>(queryText: scStuSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolId}") }))
- //{
- // scStuIds.Add(item);
- //}
- //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{schoolId}", new PartitionKey($"Base"));
- //if (response.Status == 204)
- // msg.AppendLine($"{tmdName}【{tmdId}】删除学校,删除状态:{response.Status},删除ID:{schoolId}");
- //else
- // delSchoolRels.Add(new DelSchoolRel() { id = $"{schoolId}", code = "Base", type = 1, status = response.Status });
- //foreach (var item in scTchIds)
- //{
- // var tchRespnse = await cosmosClient.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync($"{item}", new PartitionKey($"Teacher-{schoolId}"));
- // if (tchRespnse.Status == 204)
- // msg.AppendLine($"删除教师,删除状态:{tchRespnse.Status},删除ID:{item}");
- // else
- // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Teacher-{schoolId}", type = 2, status = response.Status });
- //}
- //foreach (var item in scStuIds)
- //{
- // var stuRespnse = await cosmosClient.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync($"{item}", new PartitionKey($"Base-{schoolId}"));
- // if (stuRespnse.Status == 204)
- // msg.AppendLine($"删除学生,删除状态:{stuRespnse.Status},删除ID:{item}");
- // else
- // delSchoolRels.Add(new DelSchoolRel() { id = $"{item}", code = $"Base-{schoolId}", type = 3, status = response.Status });
- //}
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "set-del", msg.ToString(), _dingDing, httpContext: HttpContext);
- if (delSchoolRels.Count > 0)
- return Ok(new { state = 201, delSchoolRels });
- else
- return Ok(new { state = 200 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/set-del \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 依据学校统计 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolcnt")]
- public async Task<IActionResult> GetSchoolCnt(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- DateTimeOffset dtime = DateTimeOffset.UtcNow;
- var (weekS, weekE) = TimeHelper.GetStartOrEnd(dtime, "week");
- var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dtime, "lastweek");
- var (termS, termE) = TimeHelper.GetStartOrEnd(dtime, "term");
- var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dtime, "lastterm");
- var (yearS, yearE) = TimeHelper.GetStartOrEnd(dtime, "year");
- var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(dtime, "lastYear");
- int tecCnt = 0;// 教师数量
- int classCnt = 0; //班级
- int stuCnt = 0; //学生
- int roomCnt = 0; //智慧教室
- int lesCnt = 0; //课例总数
- int weekLesCnt = 0; //本周课例
- int lastWeekLesCnt = 0; //上周课例
- int weekACTCnt = 0; //本周活动
- int lastWeekACTCnt = 0; //上周活动
- int termLesCnt = 0; //本学期课例
- int lastTermLesCnt = 0; //上学学期课例
- int termACTCnt = 0; //本学期活动
- int lastTermActCnt = 0; //上学学期活动
- int yearLesCnt = 0; //今年课例
- int lastYearLesCnt = 0; //去年课例
- int yearACTCnt = 0; //今年活动
- int lastYearACTCnt = 0; //去年活动
- SchoolInfo schoolInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolInfo>($"{schoolId}", new PartitionKey("Base"));
- if (schoolInfo != null)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolInfo.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolInfo.serial = serial.ToObject<List<ProductSumInfos>>();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolInfo.service = service.ToObject<List<ProductSumInfos>>();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolInfo.hard = hard.ToObject<List<SchoolProductSumDataHard>>();
- }
- }
- schoolInfo.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolInfo.id, "assist");
- string currencySql = "select value(count(c.id)) from c";
- tecCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Teacher-{schoolInfo.id}"); // 教师数量
- classCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Class-{schoolInfo.id}"); //班级
- stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", currencySql, $"Base-{schoolInfo.id}"); //学生
- roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"Room-{schoolInfo.id}"); //智慧教室
- lesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", currencySql, $"LessonRecord-{schoolInfo.id}"); //课例总数
- weekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {weekS} and c.startTime<= {weekE}", $"LessonRecord-{schoolInfo.id}"); //本周课例
- lastWeekLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastWeekS} and c.startTime<= {lastWeekE}", $"LessonRecord-{schoolInfo.id}"); //上周课例
- termLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {termS} and c.startTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期课例
- lastTermLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastTermS} and c.startTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期课例
- yearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {yearS} and c.startTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年课例
- lastYearLesCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{currencySql} where c.startTime >= {lastYearS} and c.startTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年课例
- int ACTCnt = 0; //活动
- foreach (var type in StaticValue.activityTypes)
- {
- ACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}'");
- weekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {weekS} and c.createTime <= {weekE} "); //本周活动
- lastWeekACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastWeekS} and c.createTime <= {lastWeekE} "); //上周活动
- termACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {termS} and c.createTime <= {termE}", $"LessonRecord-{schoolInfo.id}"); //本学期活动
- lastTermActCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastTermS} and c.createTime <= {lastTermE}", $"LessonRecord-{schoolInfo.id}"); //上学学期活动
- yearACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {yearS} and c.createTime <= {yearE}", $"LessonRecord-{schoolInfo.id}"); //今年活动
- lastYearACTCnt += await CommonFind.GetSqlValueCount(cosmosClient, "Common", $"{currencySql} where c.pk='{type}' and c.school='{schoolInfo.id}' and c.createTime >= {lastYearS} and c.createTime <= {lastYearE}", $"LessonRecord-{schoolInfo.id}"); //去年活动
- }
- //取得購買紀錄
- List<object> order = await GetOrderHisFromCoreBBAsync(schoolId.GetString());
- return Ok(new { state = RespondCode.Ok, tecCnt, classCnt, stuCnt, roomCnt, lesCnt, weekLesCnt, lastWeekLesCnt, weekACTCnt, lastWeekACTCnt, termLesCnt, lastTermLesCnt, termACTCnt, lastTermActCnt, yearLesCnt, lastYearLesCnt, yearACTCnt, lastYearACTCnt, schoolInfo, ACTCnt, buy = new { yearS, yearE, lastYearS, lastYearE, order } });
- }
- else
- return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校信息!" });
- }
- /// <summary>
- /// 通过学校Id 统计学校信息 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-analyse")]
- public async Task<IActionResult> GetAnalyse(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- RecSchool recSchool = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- recSchool = json.ToObject<RecSchool>();
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
- var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
- var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
- var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
- int tchCnt = 0; //教师数量
- int stuCnt = 0; //学校数量
- int roomCnt = 0; //智慧教室数量
- int lessAllCant = 0; //课例总数
- int lessLastdayCnt = 0; //昨天的课例
- int lessDayCnt = 0; //今天的课例
- int lessLastYearCnt = 0; //去年的课例
- int lessYearCnt = 0; //今年的课例
- double allInterCnt = 0; //所有互动
- double lastDayInterCnt = 0; // 昨天课例互动
- double interCnt = 0; // 今天课例互动
- double lastYearInterCnt = 0; // 去年课例互动
- double yearInterCnt = 0; // 今年课例互动
- int allActCnt = 0; //所有活动
- int lastActCnt = 0; //昨天活动
- int actCnt = 0; //今天活动
- int lastYearActCnt = 0; //去年活动
- int yearActCnt = 0; //今年活动
- string commSql = "select value(count(c.id)) from c ";
- tchCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Teacher-{schoolId}");
- stuCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", commSql, $"Base-{schoolId}");
- roomCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"Room-{schoolId}");
- lessAllCant = await CommonFind.GetSqlValueCount(cosmosClient, "School", commSql, $"LessonRecord-{schoolId}");
- string lessCode = $"LessonRecord-{schoolId}";
- string lessLastdaySql = $"{commSql} where c.startTime >= {lastDays} and c.startTime <= {lastDaye} ";
- lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql, lessCode);
- string lessDaySql = $"{commSql} where c.startTime >= {days} and c.startTime <= {daye} ";
- lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql, lessCode);
- string lessLastYarSql = $"{commSql} where c.startTime >= {lastYears} and c.startTime <= {lastYeare} ";
- lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql, lessCode);
- string lessYearSql = $"{commSql} where c.startTime >= {years} and c.startTime <= {yeare} ";
- lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql, lessCode);
- //课例互动
- string strInterSql = $"select value(sum(c.clientInteractionAverge)) from c";
- allInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", strInterSql, lessCode);
- string lastdayInterSql = $"{strInterSql} where c.startTime >= { lastDays} and c.startTime <= {lastDays} ";
- lastDayInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastdayInterSql, lessCode);
- string dayInterSql = $"{strInterSql} where c.startTime >= { days} and c.startTime <= {daye} ";
- interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", dayInterSql, lessCode);
- string lastYarInterSql = $"{strInterSql} where c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
- lastYearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", lastYarInterSql, lessCode);
- string yearInterSql = $"{strInterSql} where c.startTime >= { years} and c.startTime <= {yeare} ";
- yearInterCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", yearInterSql, lessCode);
- //活动
- allActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: $"and c.school='{schoolId}'");
- string lastActSql = $" and c.school='{schoolId}' and c.createTime >= {lastDays} and c.createTime <= {lastDays}";
- lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
- string actSql = $" and c.school='{schoolId}' and c.createTime >= {days} and c.createTime <= {daye}";
- actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
- string lastYearActSql = $" and c.school='{schoolId}' and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
- lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
- string yearActSql = $" and c.school='{schoolId}' and c.createTime >= {years} and c.createTime <= {yeare}";
- yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
- return Ok(new { state = 200, recSchool, tchCnt, stuCnt, roomCnt, lessAllCant, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, allInterCnt, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, allActCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
- }
- /// <summary>
- /// 学校每周课例趋势 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schooldate")]
- public async Task<IActionResult> GetSchoolDate(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- List<double> weekTrend = new();
- int year = DateTimeOffset.UtcNow.Year;
- int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
- int currentTime = DateTimeOffset.UtcNow.DayOfYear / 7 + 1;
- int currentTime1 = DateTimeOffset.UtcNow.DayOfYear / 7;
- //获取当前学期所有的课程记录
- List<LessAnalyse> records = new List<LessAnalyse>();
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessAnalyse>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{schoolId}") }))
- {
- records.Add(item);
- }
- List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(records);
- var subs = records.GroupBy(x => x.subjectId).Where(w => !string.IsNullOrEmpty(w.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
- var gradeCnt = grades.Select(x => new { x.name, x.periodId, value = x.count });
- var subCnt = subs.Select(x => new { name = x.key, value = x.count });
- List<LessonCount> scount = new();
- List<LessonCount> tcount = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{schoolId}-{year}") }))
- {
- scount.Add(item);
- }
- List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, new List<string>() { $"{schoolId}" });
- foreach (var tId in teacIds)
- {
- var sqlTxtt = $"select value(c) from c where c.id='{tId}'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<LessonCount>(queryText: sqlTxtt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{year}") }))
- {
- tcount.Add(item);
- }
- }
- int days = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? days = 366 : days = 365;
- List<List<double>> lessons = new();
- if (scount.Count > 0)
- {
- foreach (LessonCount item in scount)
- {
- lessons.Add(item.beginCount);
- }
- }
- if (tcount.Count > 0)
- {
- foreach (LessonCount item in tcount)
- {
- lessons.Add(item.beginCount);
- }
- }
- if (lessons.Count > 0)
- {
- var bmatrix = DenseMatrix.OfColumns(lessons);
- //开学第一周周内开课
- if (dayOfweek == 0)
- {
- dayOfweek = 7;
- }
- //第一周多少天
- var dd = 7 - dayOfweek + 1;
- //一年有几周
- int sweeks = days / 7;
- //查询天数
- int dayYear = 0;
- if (currentTime > 0)
- {
- for (int i = 0; i <= currentTime; i++)
- {
- if (i == 0)
- {
- var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
- dayYear += dd;
- //weeks.Add(i, bsum);
- weekTrend.Add(bsum);
- }
- else
- {
- var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
- dayYear += 7;
- //weeks.Add(i, bsum);
- weekTrend.Add(bsum);
- }
- }
- }
- //最后一周是否有余
- int stary = days - dayYear;
- if (stary > 0 && stary < 7)
- {
- var bsum = bmatrix.SubMatrix(dayYear, stary - 1, 0, bmatrix.ColumnCount).ColumnSums().Sum();
- //weeks.Add((sweeks + 1), bsum);
- weekTrend.Add(bsum);
- }
- }
- return Ok(new { state = 200, gradeCnt, subCnt, weekTrend });
- }
- /// <summary>
- /// 顾问学校基础统计、以及排行 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-assisscbase")]
- public async Task<IActionResult> GetAssistSchoolCnt(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- int scAllCnt = 0; //学校
- int tchAllCnt = 0; //教师数量
- int tchMonthCnt = 0; //教师本月新增
- int stuAllCnt = 0; //所有学校学生
- int lessAllCnt = 0; //课例总数
- int lessMthCnt = 0; //本月新增
- List<ScRankCnt> scRankCnts = new(); //学校开课、上传, 课例排名
- var (start, end) = TimeHelper.GetStartOrEnd(dateTime, "month");
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- if (schoolIds.Count > 0)
- {
- string scIdSql = BICommonWay.ManyScSql("c.schoolId", schoolIds);
- string stuSql = $"select value(count(c.id)) from c where {scIdSql}";
- stuAllCnt = await CommonFind.GetSqlValueCount(cosmosClient, "Student", stuSql);
- string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
- string lessMoSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= {start} and c.startTime <= {end}";
- lessMthCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql);
- List<SchoolBase> scInfos = new();
- string scInfoSql = $"select c.id,c.name,c.code,c.picture from c ";
- string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
- scInfos = await CommonFind.GetObject<SchoolBase>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
- List<string> tchMonIds = new();
- foreach (var item in scInfos)
- {
- ScRankCnt lessRankCnt = new() { id = item.id, name = item.name, code = item.code, picture = item.picture };
- string tchSql = $"select value(count(c.id)) from c where array_contains(c.roles,'teacher',true) and c.createTime >= {start} and c.createTime <= {end}";
- tchMonthCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchSql, $"Teacher-{item.id}");
- string tchAllSql = $"select value(count(c.id)) from c where ARRAY_CONTAINS(c.roles,'teacher',true) and c.status = 'join'";
- tchAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", tchAllSql, $"Teacher-{item.id}");
- string lessALLSql = "select value(count(c.id)) from c where c.pk='LessonRecord'";
- lessAllCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", lessALLSql, $"LessonRecord-{item.id}");
- string lessUpSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 0";
- lessRankCnt.openCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessMoSql, $"LessonRecord-{item.id}");
- string lessSql = $"select value(count(c.id)) from c where c.pk='LessonRecord' and c.upload = 1";
- lessRankCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessSql, $"LessonRecord-{item.id}");
- string interactSql = $"select value(sum(c.clientInteractionCount)) from c where c.pk='LessonRecord'";
- lessRankCnt.interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", interactSql, $"LessonRecord-{item.id}");
- string actSql = $" and c.school='{item.id}'";
- lessRankCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
- scRankCnts.Add(lessRankCnt);
- }
- scAllCnt = schoolIds.Count();
- tchMonthCnt = tchMonIds.Distinct().Count();
- }
- return Ok(new { state = RespondCode.Ok, scAllCnt, tchAllCnt, tchMonthCnt, stuAllCnt, lessAllCnt, lessMthCnt, scRankCnts });
- }
- /// <summary>
- /// 一年学校和多个学校的课例、互动、活动统计分析 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-assissc")]
- public async Task<IActionResult> GetAssisSc(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- jsonElement.TryGetProperty("schoolId", out JsonElement schooId);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- List<YearCnt> yearCnts = new(); //当前的课例,活动,互动统计
- string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
- string scSql = null;
- if (!string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}"))
- {
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- if (schoolIds.Count == 0) return Ok(new { state = RespondCode.Ok, yearCnts, });
- scSql = BICommonWay.ManyScSql("c.school", schoolIds);
- }
- if (!string.IsNullOrEmpty($"{schooId}") && string.IsNullOrEmpty($"{tmdId}"))
- scSql = $"c.school = '{schooId}'";
- if ((string.IsNullOrEmpty($"{tmdId}") && string.IsNullOrEmpty($"{schooId}")) || (!string.IsNullOrEmpty($"{tmdId}") && !string.IsNullOrEmpty($"{schooId}")))
- return Ok(new { state = RespondCode.ParamsError, msg = "参数错误" });
- List<MonthStartEnd> mthStartEnds = await TimeHelper.GetYearSataMthCtMth(DateTimeOffset.UtcNow);
- if (mthStartEnds.Count > 0)
- {
- foreach (var item in mthStartEnds)
- {
- YearCnt yearCnt = new() { name = item.yearMonth };
- string selessSql = $"{strSql} and {scSql.ToString()} and c.startTime >= { item.start} and c.startTime <= {item.end}";
- yearCnt.lessCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", selessSql);
- string interactSql = $"select value(sum(c.clientInteractionAverge)) from c where c.pk='LessonRecord' and {scSql} and c.startTime >= { item.start} and c.startTime <= {item.end}";
- yearCnt.interCnt = await CommonFind.GetSqlValueDoubleCounnt(cosmosClient, "School", interactSql);
- string mthActSql = $"and {scSql} and c.createTime >= {item.start} and c.createTime <= {item.end}";
- yearCnt.actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: mthActSql);
- yearCnts.Add(yearCnt);
- }
- }
- return Ok(new { state = RespondCode.Ok, yearCnts, });
- }
- /// <summary>
- /// 顾问学校统计 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-assissccnt")]
- public async Task<IActionResult> GetAssisScCnt(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- var (days, daye) = TimeHelper.GetStartOrEnd(dateTime);
- var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateTime.AddDays(-1));
- var (years, yeare) = TimeHelper.GetStartOrEnd(dateTime, "year");
- var (lastYears, lastYeare) = TimeHelper.GetStartOrEnd(dateTime, "lastYear");
- int lessAll = 0; //所以课例
- int lessLastdayCnt = 0; //昨天的课例
- int lessDayCnt = 0; //今天的课例
- int lessLastYearCnt = 0; //去年的课例
- int lessYearCnt = 0; //今年的课例
- int interAll = 0; //所有互动总数
- int lastDayInterCnt = 0; // 昨天课例互动
- int interCnt = 0; // 今天课例互动
- int lastYearInterCnt = 0; // 去年课例互动
- int yearInterCnt = 0; // 今年课例互动
- int actAllCnt = 0; //所有活动
- int lastActCnt = 0; //昨天活动
- int actCnt = 0; //今天活动
- int lastYearActCnt = 0; //去年活动
- int yearActCnt = 0; //今年活动
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- if (schoolIds.Count > 0)
- {
- string scSql = BICommonWay.ManyScSql("c.school", schoolIds);
- string strSql = "SELECT value(count(c.id)) FROM c where c.pk='LessonRecord'";
- //课例
- lessAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"{strSql} and {scSql}");
- string lessLastdaySql = $"{strSql} and {scSql} and c.startTime >= { lastDays} and c.startTime <= {lastDaye} ";
- lessLastdayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastdaySql);
- string lessDaySql = $"{strSql} and {scSql} and c.startTime >= { days} and c.startTime <= {daye} ";
- lessDayCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessDaySql);
- string lessLastYarSql = $"{strSql} and {scSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
- lessLastYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessLastYarSql);
- string lessYearSql = $"{strSql} and {scSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
- lessYearCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lessYearSql);
- //课例互动
- string strInterSql = $"select value(sum(c.clientInteractionAverge)) from c where c.pk='LessonRecord' and {scSql}";
- interAll = await CommonFind.GetSqlValueCount(cosmosClient, "School", strInterSql);
- string lastdayInterSql = $"{strInterSql} and c.startTime >= { lastDays} and c.startTime <= {lastDaye} ";
- lastDayInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lastdayInterSql);
- string dayInterSql = $"{strInterSql} and c.startTime >= { days} and c.startTime <= {daye} ";
- interCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", dayInterSql);
- string lastYarInterSql = $"{strInterSql} and c.startTime >= { lastYears} and c.startTime <= {lastYeare} ";
- lastYearInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", lastYarInterSql);
- string yearInterSql = $"{strInterSql} and c.startTime >= { years} and c.startTime <= {yeare} ";
- yearInterCnt = await CommonFind.GetSqlValueCount(cosmosClient, "School", yearInterSql);
- //活动
- string actAllSql = $"and {scSql} ";
- actAllCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actAllSql);
- string lastActSql = $"and {scSql} and c.createTime >= {lastDays} and c.createTime <= {lastDaye}";
- lastActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastActSql);
- string actSql = $"and {scSql} and c.createTime >= {days} and c.createTime <= {daye}";
- actCnt = await ActivityWay.GetCnt(cosmosClient, condSql: actSql);
- string lastYearActSql = $" and {scSql} and c.createTime >= {lastYears} and c.createTime <= {lastYeare}";
- lastYearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: lastYearActSql);
- string yearActSql = $"and {scSql} and c.createTime >= {years} and c.createTime <= {yeare}";
- yearActCnt = await ActivityWay.GetCnt(cosmosClient, condSql: yearActSql);
- }
- return Ok(new { state = RespondCode.Ok, lessAll, lessLastdayCnt, lessDayCnt, lessLastYearCnt, lessYearCnt, interAll, lastDayInterCnt, interCnt, lastYearInterCnt, yearInterCnt, actAllCnt, lastActCnt, actCnt, lastYearActCnt, yearActCnt });
- }
- /// <summary>
- /// 查询学校基础信息,和学校年级、科目数据统计 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-ratio")]
- public async Task<IActionResult> GetRatio(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("schoolId", out JsonElement schoolId)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- AnSchool school = new(); //学校基础基础信息
- int serial = 0; //学校软体数量
- int service = 0; //学校服务数量
- int hard = 0; //学校硬件数量
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{schoolId}", new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<AnSchool>();
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "未找到该学校" });
- List<LessAnalyse> lessAnalyses = new();
- await foreach (var lessItem in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessAnalyse>(queryText: "select c.id,c.code,c.periodId,c.subjectId,c.grade from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school.id}") }))
- {
- lessAnalyses.Add(lessItem);
- }
- List<(string name, string periodId, int count)> grades = LessonStatisWay.GetGradeCount(lessAnalyses);
- var subs = lessAnalyses.GroupBy(x => x.subjectId).Where(y => !string.IsNullOrEmpty(y.Key)).Select(y => new { key = y.Key, count = y.ToList().Count }).ToList();
- var gradeCnt = grades.Select(x => new { x.name, x.periodId,value = x.count });
- var subCnt = subs.Select(x => new { name = x.key, value = x.count });
- var responseProduct = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(school.id, new PartitionKey("ProductSum"));
- if (responseProduct.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(responseProduct.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement _serial) && !_serial.ValueKind.Equals(JsonValueKind.Null))
- {
- serial = _serial.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement _service) && !_service.ValueKind.Equals(JsonValueKind.Null))
- {
- service = _service.ToObject<List<SchoolProductSumData>>().Count;//.Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement _hard) && !_hard.ValueKind.Equals(JsonValueKind.Null))
- {
- hard = _hard.ToObject<List<SchoolProductSumDataHard>>().Count();//.Select(x => x.prodCode).ToList();
- }
- }
- return Ok(new { state = RespondCode.Ok, school, gradeCnt, subCnt, serial, service, hard });
- }
- /// <summary>
- /// 通过tmdID 账户查询学校专业和模组 //已对接
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-proded")]
- public async Task<IActionResult> GetProdEd(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return Ok(new { state = RespondCode.ParamsError, nsg = "参数错误" });
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- int adCnt = 0;
- int allCnt = 0;
- List<ScProdEd> scInfos = new();
- List<string> products = new();
- if (schoolIds.Count > 0)
- {
- string scInfoSql = $"select c.id,c.name,c.code,c.picture,c.type,c.size,c.scale from c ";
- string idSql = BICommonWay.ManyScSql("c.id", schoolIds);
- scInfos = await CommonFind.GetObject<ScProdEd>(cosmosClient, "School", $"{scInfoSql} where {idSql}", "Base");
- string serialSql = "SELECT value(count(ARRAY_LENGTH(c.deviceBound))) FROM c ";
- string serialAllSql = "SELECT value(sum((c.deviceMax))) FROM c";
- if (schoolIds.Count > 0)
- {
- foreach (var scProd in scInfos)
- {
- adCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialSql, $"Product-{scProd.id}");
- allCnt += await CommonFind.GetSqlValueCount(cosmosClient, "School", serialAllSql, $"Product-{scProd.id}");
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- List<string> serials = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- scProd.serial = serials;
- products.AddRange(serials);
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- List<string> services = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- scProd.service = services;
- products.AddRange(services);
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- List<string> hards = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- scProd.hard = hards;
- products.AddRange(hards);
- }
- }
- }
- //scInfos.ForEach(async scProd =>
- //{
- // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(scProd.id, new PartitionKey("ProductSum"));
- // if (response.Status == 200)
- // {
- // using var json = await JsonDocument.ParseAsync(response.ContentStream);
- // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- // {
- // scProd.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- // }
- // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- // {
- // scProd.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- // }
- // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- // {
- // scProd.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- // }
- // }
- //});
- }
- }
- var productAn = products.GroupBy(g => g).Select(s => new { key = s.Key, cnt = s.ToList().Count }).ToList();
- return Ok(new { state = RespondCode.Ok, allCnt, adCnt, scInfos, productAn });
- }
- /// <summary>
- /// 通过学校Id查询详情 数据管理工具——查询工具
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-info")]
- public async Task<IActionResult> GetSchool(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- StringBuilder sqlTxt = new StringBuilder("select * from c");
- if (!string.IsNullOrEmpty($"{schoolId}"))
- {
- sqlTxt.Append($" where c.id='{schoolId}'");
- }
- List<School> schools = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- schools.Add(obj.ToObject<School>());
- }
- }
- }
- return Ok(new { state = 200, schools });
- }
- /// <summary>
- /// 依据区域Id查询区域空间统计
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-spance")]
- public async Task<IActionResult> GetAreaSpace(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("areaId", out JsonElement areaId);
- jsonElement.TryGetProperty("schoolId", out JsonElement schoolId);
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.Global))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- long allSize = 0; //全部大小
- int teacherSpace = 0; //学校分配给教师的空间
- long useSize = 0; //已使用大小
- Dictionary<string, double?> useSpaceInfo = new(); //学校使用详情
- //查询区域所有学校
- if (!string.IsNullOrEmpty($"{areaId}"))
- {
- List<string> schools = new();
- schools = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{areaId}'", "Base");
- allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"select value(sum(c.size)) from c where c.areaId='{areaId}'", "Base"); //区域所有学校空间
- foreach (var school in schools)
- {
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT sum(c.size) as size FROM c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school}") }))
- {
- var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var elmt in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (elmt.TryGetProperty("size", out JsonElement _size) && _size.ValueKind.Equals(JsonValueKind.Number))
- {
- teacherSpace += _size.GetInt32();
- break;
- }
- }
- }
- long blobsize = 0;
- RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{school}");
- if (!value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out blobsize))
- {
- }
- }
- else
- {
- var storageClient = _azureStorage.GetBlobContainerClient("school");
- var size = await storageClient.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{school}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- useSize += size.Item1.Value;
- useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
- //useSpaceInfo = (from e in useSpaceInfo.Concat(size.Item2) group e by e.Key into g select new { Name = g.Key, value = g.Sum(kvp => kvp.Value) }).ToDictionary(item => item.Name, item => item.value); //linq 方式合并
- }
- SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{school}");
- if (Scores != null)
- {
- Dictionary<string, double?> catalog = new();
- foreach (var score in Scores)
- {
- double val = score.Score;
- string key = score.Element.ToString();
- catalog.Add(key, val);
- }
- useSpaceInfo = useSpaceInfo.Concat(catalog).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
- }
- else
- {
- var client = _azureStorage.GetBlobContainerClient("school");
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{school}", size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{school}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{school}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- useSize += size.Item1.Value;
- useSpaceInfo = useSpaceInfo.Concat(size.Item2).GroupBy(g => g.Key).ToDictionary(k => k.Key, k => k.Sum(kvp => kvp.Value)); //lamebda表达式
- }
- }
- }
- //查询学校
- if (!string.IsNullOrEmpty($"{schoolId}"))
- {
- allSize = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(c.size) FROM c where c.id='{schoolId}'", "Base");
- teacherSpace = await CommonFind.GetSqlValueCount(cosmosClient, "School", $"SELECT value(sum(c.size)) FROM c", $"Teacher-{schoolId}");
- long blobsize = 0;
- RedisValue value = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolId}");
- if (!value.IsNullOrEmpty)
- {
- JsonElement record = value.ToString().ToObject<JsonElement>();
- if (record.TryGetInt64(out blobsize))
- {
- useSize = blobsize;
- }
- }
- else
- {
- var storageClient = _azureStorage.GetBlobContainerClient("school");
- var size = await storageClient.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Bolb:Catalog:{schoolId}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Bolb:Catalog:school", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- useSpaceInfo = size.Item2;
- }
- Dictionary<string, double?> catalog = new();
- SortedSetEntry[] Scores = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Blob:Catalog:{schoolId}");
- if (Scores != null)
- {
- foreach (var score in Scores)
- {
- double val = score.Score;
- string key = score.Element.ToString();
- catalog.Add(key, val);
- }
- useSpaceInfo = catalog;
- }
- else
- {
- var client = _azureStorage.GetBlobContainerClient("school");
- var size = await client.GetBlobsCatalogSize();
- await _azureRedis.GetRedisClient(8).HashSetAsync($"Blob:Record", $"{schoolId}", size.Item1);
- foreach (var key in size.Item2.Keys)
- {
- await _azureRedis.GetRedisClient(8).SortedSetRemoveAsync($"Blob:Catalog:{schoolId}", key);
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Blob:Catalog:{schoolId}", key, size.Item2[key].HasValue ? size.Item2[key].Value : 0);
- }
- useSize = size.Item1.Value;
- useSpaceInfo = size.Item2;
- }
- }
- return Ok(new { state = 200, allSize, useSize, teacherSpace, useSpaceInfo });
- }
- /// <summary>
- /// 移交学校顾问
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-shift")]
- public async Task<IActionResult> GetShift(JsonElement jsonElement)
- {
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- if (!jsonElement.TryGetProperty("school", out JsonElement _school)) return BadRequest();
- //if (!jsonElement.TryGetProperty("teacher", out JsonElement _teacher)) return BadRequest();
- if (!jsonElement.TryGetProperty("shiftTeacher", out JsonElement _shiftTeacher)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- }
- SchoolTeacher schoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
- if (schoolTeacher.roles.IsNotEmpty() && schoolTeacher.roles.Contains("assist"))
- {
- schoolTeacher.roles.Remove("assist");
- SchoolTeacher newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<SchoolTeacher>($"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
- if (!newSchoolTeacher.roles.Contains("assist"))
- {
- newSchoolTeacher.roles.Add("assist");
- newSchoolTeacher = await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(newSchoolTeacher, $"{_shiftTeacher}", new PartitionKey($"Teacher-{_school}"));
- }
- await cosmosClient.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<SchoolTeacher>(schoolTeacher, $"{_tmdId}", new PartitionKey($"Teacher-{_school}"));
- School schoolBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{_school}", new PartitionKey($"Base"));
- //发送消息实体
- string shiftCode = "shift-assist";
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"BI:{_option.Location}:{_school}",
- to = new List<string> { $"{_shiftTeacher}" },
- label = $"{shiftCode}_school",
- body = new { location = _option.Location, biz = shiftCode, tmdid = $"{_tmdId}", tmdname = $"{_tmdName}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- if (notification != null)
- {
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);//站内发送消息
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "schoolTeacher-add", $"{_tmdName}【{_tmdId}】移交顾问给{newSchoolTeacher.name}【{newSchoolTeacher.id}】", _dingDing, httpContext: HttpContext);
- return Ok(new { state = 200 });
- }
- else { return Ok(new { status = 201, msg = $"{_tmdName}【{_tmdId}】账号不是顾问" }); }
- }
- #region 购买记录
- /// <summary>
- /// 取得CoreBB學校訂單履歷資訊 暂时这样处理
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- private async Task<List<object>> GetOrderHisFromCoreBBAsync(string schoolCode)
- {
- List<object> result = new List<object>();
- try
- {
- string url = _configuration.GetValue<string>("HaBookAuth:CoreBBAPI") + "/ies5/get-school-order";
- string AccessToken = await getCoreAccessToken();
- _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
- string paramJson = JsonConvert.SerializeObject(new { school_code = schoolCode });
- var content = new StringContent(paramJson, Encoding.UTF8, "application/json");
- HttpResponseMessage responseMessage = await _httpClient.PostAsync(url, content);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string responseBody = responseMessage.Content.ReadAsStringAsync().Result;
- result = System.Text.Json.JsonSerializer.Deserialize<List<object>>(responseBody.ToString());
- }
- return result;
- }
- catch (Exception ex)
- {
- return result;
- }
- }
- private async Task<string> getCoreAccessToken()
- {
- string AccessToken = "";
- try
- {
- string Url = _configuration.GetValue<string>("HaBookAuth:CoreAPI") + "/oauth2/token";
- string GrantType = "device";
- string ClientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- string Secret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var content = new { grant_type = GrantType, client_id = ClientID, client_secret = Secret };
- var response = await _httpClient.PostAsJsonAsync($"{Url}", content);
- if (response.IsSuccessStatusCode)
- {
- string responseBody = response.Content.ReadAsStringAsync().Result;
- using (JsonDocument document = JsonDocument.Parse(responseBody.ToString()))
- {
- if (document.RootElement.TryGetProperty("access_token", out JsonElement AccessTokenObj))
- {
- AccessToken = AccessTokenObj.ToString();
- }
- }
- }
- return AccessToken;
- }
- catch (Exception ex)
- {
- return AccessToken;
- }
- }
- #endregion
- #region 顾问学校统计返回值
- public record ScRankCnt : SchoolBase
- {
- public int openCnt { get; set; }
- public int lessCnt { get; set; }
- public int interCnt { get; set; }
- public int actCnt { get; set; }
- }
- public record SchoolBase
- {
- public string id { get; set; }
- public string code { get; set; }
- public string name { get; set; }
- public string picture { get; set; }
- }
- #endregion
- /// <summary>
- /// 未加入区域的学校
- /// </summary>
- public record NotAreaSchool
- {
- public string id { get; set; }
- public string name { get; set; }
- public string schoolCode { get; set; }
- public string picture { get; set; }
- public List<string> period { get; set; }
- public string province { get; set; }
- public string city { get; set; }
- public string dist { get; set; }
- public string areaId { get; set; }
- public string standard { get; set; }
- public List<SchoolArea> areas { get; set; } = new List<SchoolArea>();
- }
- /// <summary>
- /// 学校空间使用情况
- /// </summary>
- public record SchoolSpace
- {
- public string id { get; set; }
- public string name { get; set; }
- public Space space { get; set; }
- }
- /// <summary>
- /// 空间
- /// </summary>
- public record Space
- {
- /// <summary>
- /// 已使用空间
- /// </summary>
- public long useSize { get; set; }
- /// <summary>
- /// 分配教师空间
- /// </summary>
- public long tSize { get; set; }
- /// <summary>
- /// 空间类型
- /// </summary>
- public Dictionary<string, double?> catalogSize { get; set; }
- }
- public record DelSchoolRel
- {
- public string id { get; set; }
- public string code { get; set; }
- /// <summary>
- /// 未删除的类型 1 学校 2教师 3学生
- /// </summary>
- public int type { get; set; }
- public int status { get; set; }
- }
- }
- }
|