123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- using System;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.IO;
- using System.Net;
- using System.Net.Http;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Azure.Cosmos;
- using Azure.Storage.Blobs;
- using DocumentFormat.OpenXml.Bibliography;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Azure.Functions.Worker;
- using Microsoft.Azure.Functions.Worker.Http;
- using NUnit.Framework.Constraints;
- using StackExchange.Redis;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
- using TEAMModelOS.SDK.Models.Service.BI;
- using TEAMModelOS.SDK.Models.Service.BIStatsWay;
- namespace TEAMModelOS.FunctionV4.HttpTrigger
- {
- public class BIHttpTrigger
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- public BIHttpTrigger(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- }
- /// <summary>
- /// 学校信息BI中间件更新
- /// </summary>
- /// <param name="req"></param>
- /// <returns></returns>
- [Function("set-sc-birelation")]
- public async Task<HttpResponseData> upSchoolBIRelation([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req)
- {
- var response = req.CreateResponse(HttpStatusCode.OK);
- dynamic jsondata = new ExpandoObject();
- try
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- string data = await new StreamReader(req.Body).ReadToEndAsync();
- var json = JsonDocument.Parse(data).RootElement;
- School school = new();
- jsondata = json;
- if (json.TryGetProperty("school", out JsonElement _school))
- {
- school = _school.ToObject<School>();
- }
- string type = "";
- BIRelation bIRelation = new();
- var resBiRel = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school.id, new PartitionKey("BIRel"));
- if (resBiRel.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(resBiRel.ContentStream);
- bIRelation = fileJson.ToObject<BIRelation>();
- }
- else
- bIRelation.id = school.id;
- string aName = null;
- if (!string.IsNullOrEmpty($"{school.areaId}"))
- aName = await CosmosQueryHelper.GetStr(cosmosClient, "Normal", $"select value(c.name) from c where c.id='{school.areaId}'", "Base-Area");
- bIRelation.name = school.name;
- bIRelation.picture = school.picture;
- bIRelation.region = school.region;
- bIRelation.province = school.province;
- bIRelation.city = school.city;
- bIRelation.dist = school.dist;
- bIRelation.address = school.address;
- bIRelation.areaId = school.areaId;
- bIRelation.size = school.size;
- bIRelation.scale = school.scale;
- bIRelation.upDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- bIRelation.areaName = aName;
- if (resBiRel.Status == 200)
- {
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<BIRelation>(bIRelation, bIRelation.id, new PartitionKey("BIRel"));
- type = "update";
- }
- else
- {
- await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<BIRelation>(bIRelation, new PartitionKey("BIRel"));
- type = "add";
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, $"birelation-{type}", $"触发更新学校信息表中间件", _dingDing);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"stats-sc-info,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- return response;
- }
- /// <summary>
- /// 统计学校的信息
- /// </summary>
- /// <param name="req"></param>
- /// <returns></returns>
- [Function("stats-sc-info")]
- public async Task<HttpResponseData> StatsSchoolInfo([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req)
- {
- var response = req.CreateResponse(HttpStatusCode.OK);
- dynamic jsondata = new ExpandoObject();
- try
- {
- string scId = null;
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- string data = await new StreamReader(req.Body).ReadToEndAsync();
- var json = JsonDocument.Parse(data).RootElement;
- jsondata = json;
- if (json.TryGetProperty("schoolId", out JsonElement _schoolId))
- {
- scId = $"{_schoolId}";
- }
- if (string.IsNullOrEmpty(scId))
- {
- return response;
- }
- bool locKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"Train:Statistics:Lock:{scId}");
- if (!locKey)
- {
- await _azureRedis.GetRedisClient(8).SetAddAsync($"Train:Statistics:Lock:{scId}", new RedisValue(scId));
- DateTime minutes = DateTime.UtcNow.AddMinutes(15); //15分钟
- await _azureRedis.GetRedisClient(8).KeyExpireAsync($"Train:Statistics:Lock:{scId}", minutes);
- bool isExist = true;
- StatsInfo statsInfo = new();
- var scDataStats = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{scId}", new PartitionKey("Stats"));
- if (scDataStats.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(scDataStats.ContentStream);
- statsInfo = fileJson.ToObject<StatsInfo>();
- }
- else
- isExist = false;
- statsInfo = await SchoolStatsWay.GetSingleSc(cosmosClient, scId);
- statsInfo.upTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (isExist)
- statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<StatsInfo>(statsInfo, statsInfo.id, new PartitionKey("Stats"));
- else
- statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<StatsInfo>(statsInfo, new PartitionKey("Stats"));
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "trigger-schoolStats", $"触发更新统计数据库", _dingDing);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"stats-sc-info,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- return response;
- }
- /// <summary>
- /// 处理传过来的信息加入到统计信息中
- /// </summary>
- /// <param name="req"></param>
- /// <returns></returns>
- [Function("set-scstats-type")]
- public async Task<HttpResponseData> SetSchoolStatsType([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestData req)
- {
- var response = req.CreateResponse(HttpStatusCode.OK);
- dynamic jsondata = new ExpandoObject();
- try
- {
- string scId = null,type = null;
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- string data = await new StreamReader(req.Body).ReadToEndAsync();
- var json = JsonDocument.Parse(data).RootElement;
- jsondata = json;
- long careDate = 0;
- int cnt = 0;
-
- DateTimeOffset dateOff = DateTimeOffset.UtcNow;
- if (!json.TryGetProperty("scId", out JsonElement _schoolId))
- {
- scId = $"{_schoolId}";
- }
- if (!json.TryGetProperty("type", out JsonElement _type))
- {
- type = $"{_type}";
- }
- if (string.IsNullOrEmpty(scId) && string.IsNullOrEmpty(type))
- {
- await _dingDing.SendBotMsg($"set-scstats-type, {req.Body};转换后:{json}", GroupNames.成都开发測試群組);
- return response;
- }
- if (!json.TryGetProperty("cnt", out JsonElement _cnt))
- {
- cnt = int.Parse($"{_cnt}");
- }
- if (!json.TryGetProperty("date", out JsonElement _date))
- {
- careDate = long.Parse($"{_date}");
- }
- else
- {
- careDate = dateOff.ToUnixTimeMilliseconds();
- }
- long currDay = dateOff.ToUnixTimeMilliseconds();
- var (lastDays, lastDaye) = TimeHelper.GetStartOrEnd(dateOff.AddDays(-1));//昨天开始/结束时间
- var (DayS, DayE) = TimeHelper.GetStartOrEnd(dateOff); //今天开始时间结束时间
- var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dateOff, "lastweek"); //计算上周开始/结束时间
- var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateOff, "week"); //计算本周开始/结束时间
- var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dateOff, "lastterm"); //计算上学期开始/结束时间
- var (termS, termE) = TimeHelper.GetStartOrEnd(dateOff, "term"); //计算本学期开始/结束时间
- var (lastYearS, lastYearE) = TimeHelper.GetStartOrEnd(dateOff, "lastYear"); //计算去年开始/结束时间
- var (yearS, yearE) = TimeHelper.GetStartOrEnd(dateOff, "year"); //计算今年开始/结束时间
- StatsInfo statsInfo = new();
- var resStsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(scId, new PartitionKey("BIRel"));
- if (resStsInfo.Status == 200)
- {
- using var fileJson = await JsonDocument.ParseAsync(resStsInfo.ContentStream);
- statsInfo = fileJson.ToObject<StatsInfo>();
- }
- else
- {
- ScBase scBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<ScBase>(scId, new PartitionKey("Base"));
- statsInfo.id = scBase.id;
- statsInfo.name = scBase.name;
- statsInfo.picture = scBase.picture;
- statsInfo.size = scBase.size;
- statsInfo.scCreateTime = scBase.createTime;
- statsInfo.areaId = scBase.areaId;
- statsInfo.upTime = currDay;
- }
- switch ($"{type}")
- {
- case "Exam":
- if (statsInfo.upTime < DayS && statsInfo.upTime >= lastDays)
- {
- statsInfo.activity.lastDay = statsInfo.activity.dayCnt;
- statsInfo.activity.year[dateOff.DayOfYear-1] += statsInfo.activity.dayCnt;
- }
- if (DayS <= statsInfo.upTime && statsInfo.upTime <= DayE)
- {
- statsInfo.activity.dayCnt += cnt;
- statsInfo.activity.exam += cnt;
- statsInfo.activity.year[dateOff.DayOfYear] += cnt;
- }
-
- statsInfo.activity.cnt += cnt;
- break;
- case "Survey":
- break;
- case "Vote":
- break;
- case "Homework":
- break;
- case "Less":
- break;
- case "stu":
- break;
- case "tch":
- break;
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"set-scstats-type,{ex.Message}\n{ex.StackTrace}\n{jsondata.ToJsonString()}", GroupNames.成都开发測試群組);
- }
- return response;
- }
- }
- }
|