123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519 |
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using Microsoft.Extensions.Options;
- using Azure.Cosmos;
- using System.Text.Json;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models;
- using TEAMModelBI.Models;
- using TEAMModelOS.SDK.Extension;
- using System.Text;
- using TEAMModelBI.Tool;
- using MathNet.Numerics.LinearAlgebra.Double;
- namespace TEAMModelBI.Controllers.Census
- {
- [Route("lesson")]
- [ApiController]
- public class LessonSticsController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureStorageFactory _azureStorage;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- public LessonSticsController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureFactory, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureFactory;
- _dingDing = dingDing;
- _option = option?.Value;
- }
- /// <summary>
- /// 查询课例数量
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-count")]
- public async Task<IActionResult> GetCount(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- if (!jsonElement.TryGetProperty("term", out JsonElement term)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var (start, end) = TimeHelper.GetTermStartOrEnd(DateTime.Now);
- object totals = new();
- StringBuilder sqlTxt = new($"select COUNT(c.id) AS totals from c where c.pk='LessonRecord'");
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- List<SchoolLen> schoolLens = new();
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- foreach (var itemId in schoolIds)
- {
- School school = new();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- SchoolLen schoolLen = new() { id = itemId, name = school.name != null ? school.name : itemId };
- //string sqlTxt = $"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'";
- sqlTxt.Append($" WHERE c.code='LessonRecord-{itemId}'");
- if (bool.Parse($"{term}") == true)
- {
- sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
- }
- schoolLen.totals = await CommonFind.FindTotals(cosmosClient, sqlTxt.ToString(), new List<string>() { "School" });
- schoolLens.Add(schoolLen);
- }
- totals = schoolLens;
- }
- else
- {
- sqlTxt.Append($" where c.pk='LessonRecord'");
- if (bool.Parse($"{term}") == true)
- {
- sqlTxt.Append($" and c.startTime >= {start} and c.startTime <= {end}");
- }
- totals = await CommonFind.FindTotals(cosmosClient, sqlTxt.ToString(), new List<string>() { "School" });
- }
- return Ok(new { state = 200, totals });
- }
- /// <summary>
- /// 统计所有课例数量
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-total")]
- public async Task<IActionResult> GetCount()
- {
- try
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- string lessonSql = $"select COUNT(c.id) AS totals from c where c.pk='LessonRecord'";
- long total = await CommonFind.FindTotals(cosmosClient, lessonSql, new List<string>() { "School" });
- return Ok(new { state = 200, total });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /lesson/get-total \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 管家所关联的课例数据
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-assiist")]
- public async Task<IActionResult> GetAssiist(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<SchoolLen> schoolLens = new();
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- foreach (var itemId in schoolIds)
- {
- School school = new();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(itemId, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- SchoolLen schoolLen = new() { id = itemId, name = school != null ? school.name : itemId };
- string sqlTxt = $"SELECT COUNT(c.id) AS totals FROM c WHERE c.code='LessonRecord-{itemId}'";
- schoolLen.totals = await CommonFind.FindTotals(cosmosClient, sqlTxt, new List<string>() { "School" });
- schoolLens.Add(schoolLen);
- }
- return Ok(new { state = 200, schoolLens });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /lesson/get-assiist {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 统计所有的课例数据
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-diccount")]
- public async Task<IActionResult> GetDicCount(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- jsonElement.TryGetProperty("years", out JsonElement _years);
- int years = DateTime.UtcNow.Year;
- if (!string.IsNullOrEmpty($"{_years}"))
- {
- years = _years.GetInt32();
- }
- List<SchoolLen> schoolLens = new();
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- foreach (string schoolId in schoolIds)
- {
- School school = new();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(schoolId, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- SchoolLen schoolLen = new() { id = schoolId, name = school != null ? school.name : schoolId };
- List<List<double>> begin = new();
- await foreach (var lcount in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{schoolId}-{years}") }))
- {
- begin.Add(lcount.beginCount);
- }
- schoolLen.totals = (long)DenseMatrix.OfColumns(begin).ColumnSums().Sum();
- schoolLens.Add(schoolLen);
- }
- return Ok(new { state = 200, schoolLens });
- }
- else
- {
- List<List<double>> begin = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText: "select value(c) from c where c.pk='LessonCount'", requestOptions: new QueryRequestOptions() { }))
- {
- begin.Add(item.beginCount);
- }
- var count = DenseMatrix.OfColumns(begin).ColumnSums().Sum();
- return Ok(new { state = 200, count });
- }
- }
- /// <summary>
- /// 顾问关联的学校统计本学期的课例
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-termcount")]
- public async Task<IActionResult> GetTermCount(JsonElement jsonElement)
- {
- if (jsonElement.TryGetProperty("tmdId", out JsonElement tmdId)) BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<SchoolLen> schoolLens = new();
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"{tmdId}");
- foreach (var scid in schoolIds)
- {
- School school = new();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(scid, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- SchoolLen schoolLen = new() { id = scid, name = !string.IsNullOrEmpty(school.name) ? school.name : scid };
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- int year = (dateTime.Month <= 8 && dateTime.Month >= 3) ? dateTime.Year : dateTime.Year - 1;
- long stime = DateTimeOffset.Parse($"{year}-9-1").ToUnixTimeMilliseconds();
- //long etime = DateTimeOffset.Parse($"{year}-2-{((year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 29 : 28)}").ToUnixTimeMilliseconds();
- double totals = 0;
- var syear = DateTimeOffset.FromUnixTimeMilliseconds(stime).Year;
- var tyear = DateTimeOffset.UtcNow.Year;
- var tday = DateTimeOffset.UtcNow.DayOfYear;
- //今年多少天
- int tdays = (tyear % 4 == 0 && tyear % 100 != 0 || tyear % 400 == 0) ? 366 : 365;
- //去年多少天
- int pydays = (syear % 4 == 0 && syear % 100 != 0 || syear % 400 == 0) ? 366 : 365;
- List<LessonCount> scount = new();
- List<LessonCount> tcount = new();
- DenseMatrix dense = null;
- var queryClass = $"select value(c) from c ";
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonCount>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{syear}") }))
- {
- scount.Add(item);
- }
- if (tyear > syear)
- {
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonCount>(queryText: queryClass, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonCount-{scid}-{tyear}") }))
- {
- tcount.Add(item);
- }
- if (tcount.Count > 0)
- {
- List<List<double>> be = new();
- foreach (var item in tcount)
- {
- be.Add(item.beginCount);
- }
- dense = DenseMatrix.OfColumns(be);
- }
- }
- if (scount.Count > 0)
- {
- List<List<double>> begin = new();
- foreach (LessonCount lesson in scount)
- {
- begin.Add(lesson.beginCount);
- }
- var matrix = DenseMatrix.OfColumns(begin);
- //求本学期
- var sdays = DateTimeOffset.FromUnixTimeMilliseconds(stime).DayOfYear;
- if (tday - sdays < 0)
- {
- //var tmatrix = DenseMatrix.OfColumns(scount.beginCount);
- //跨年后开始到本学期结束
- double endMonth = 0;
- if (null != dense)
- {
- endMonth = dense.SubMatrix(0, tday, 0, dense.ColumnCount).ColumnSums().Sum();
- }
- var startMonth = matrix.SubMatrix(sdays - 1, pydays - sdays, 0, matrix.ColumnCount).ColumnSums().Sum();
- totals = (endMonth + startMonth);
- }
- else
- {
- var allMonth = matrix.SubMatrix(sdays - 1, tday - sdays + 1, 0, matrix.ColumnCount).ColumnSums().Sum();
- totals = allMonth;
- }
- }
- schoolLen.totals = (long)totals;
- schoolLens.Add(schoolLen);
- }
- return Ok(new { state = 200, schoolLens });
- }
- /// <summary>
- /// 统计区级课例
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-areacount")]
- public async Task<IActionResult> GetAreaCount(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- List<string> schools = new();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- schools = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{areaId}'", "Base");
- //所有的课程记录
- List<LessonRecord> records = new();
- List<string> tecIds = new();
- foreach (var school in schools)
- {
- string sqlTxt = $"select value(c) from c where c.code='LessonRecord-{school}'";
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<LessonRecord>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{school}") }))
- {
- records.Add(item);
- }
- }
- tecIds = await CommonFind.FindRolesId(cosmosClient, schools);
- foreach (var tecId in tecIds)
- {
- string sqlTxt = $"select value(c) from c";
- await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<LessonRecord>(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"LessonRecord-{tecId}") }))
- {
- records.Add(item);
- }
- }
- int dayCount = 0;
- var (dayStart, dayEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
- records.ForEach(x => { if (x.startTime >= dayStart && x.startTime <= dayEnd) dayCount += 1; });
- int weekCount = 0;
- var (weekStart, weekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
- records.ForEach(x => { if (x.startTime >= weekStart && x.startTime <= weekEnd) weekCount += 1; });
- int monthCount = 0;
- var (monthStart, monthEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
- records.ForEach(x => { if (x.startTime >= monthStart && x.startTime <= monthEnd) monthCount += 1; });
- int termCount = 0;
- var (termStart, termEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
- records.ForEach(x => { if (x.startTime >= termStart && x.startTime <= termEnd) termCount += 1; });
- double teachCount = records.Where(r => r.tmdid != null).Where((x, i) => records.FindIndex(z => z.tmdid == x.tmdid) == i).ToList().Count;
- return Ok(new { state = 200, lessonCount = records.Count, teachCount, dayCount, weekCount, monthCount, termCount });
- }
- /// <summary>
- /// 统计区级一年每周的课例数据趋势
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-weekcount")]
- public async Task<IActionResult> GetWeekCount(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
- Dictionary<int, double> weeks = new();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- int year = DateTimeOffset.UtcNow.Year;
- int dayOfweek = (int)DateTimeOffset.Parse($"{year}-1-1").DayOfWeek;
- var sqlTxts = "select value(c) from c";
- List<LessonCount> scount = new();
- List<LessonCount> tcount = new();
- List<string> schools = await CommonFind.FindSchoolIds(cosmosClient, $"select c.id from c where c.areaId='{areaId}'", "Base");
- foreach (var sId in schools)
- {
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<LessonCount>(queryText:sqlTxts,requestOptions:new QueryRequestOptions() { PartitionKey =new PartitionKey($"LessonCount-{sId}-{year}")}))
- {
- scount.Add(item);
- }
- }
- List<string> teacIds = await CommonFind.FindRolesId(cosmosClient, schools);
- 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 (sweeks > 0)
- {
- for (int i = 1; i <= sweeks; i++)
- {
- if (i == 1)
- {
- var bsum = bmatrix.SubMatrix(dayYear, dd, 0, bmatrix.ColumnCount).ColumnSums().Sum();
- dayYear += dd;
- weeks.Add(i, bsum);
- }
- else
- {
- var bsum = bmatrix.SubMatrix(dayYear, 7, 0, bmatrix.ColumnCount).ColumnSums().Sum();
- dayYear += 7;
- weeks.Add(i, 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);
- }
- }
- return Ok(new { state = 200, weeks });
- }
- /// <summary>
- /// 依据课例Id获取课例详情 数据管理工具——查询工具
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-info")]
- public async Task<IActionResult> GetInfo(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("lessonId", out JsonElement lessonId)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<object> lessons = new();
- string sqlTxt = $"select * from c where c.id='{lessonId}'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions: new QueryRequestOptions() { }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- lessons.Add(obj.ToObject<object>());
- }
- }
- return Ok(new { state = 200, lessons });
- }
- public record SchoolLen
- {
- public string id { get; set; }
- public string name { get; set;}
- public long totals { get; set; }
- }
- }
- }
|