123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885 |
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using DinkToPdf;
- using DinkToPdf.Contracts;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Service;
- namespace TEAMModelOS.Controllers.Common
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("common/study")]
- [ApiController]
- public class StudyController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly IConverter _converter;
- public IConfiguration _configuration { get; set; }
- private readonly CoreAPIHttpService _coreAPIHttpService;
- public StudyController(IConverter converter,CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing,
- IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, IConfiguration configuration)
- {
- _coreAPIHttpService = coreAPIHttpService;
- _azureCosmos = azureCosmos;
- _serviceBus = serviceBus;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _configuration = configuration;
- _converter = converter;
- }
- /// <summary>
- /// 保存研修信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("save")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Save(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("study", out JsonElement stu)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- Study study = stu.ToObject<Study>();
- string code = study.school;
- study.publish = 0;
- study.ttl = -1;
- study.progress = "going";
- if (!study.owner.Equals("area"))
- {
- study.owner = "school";
- study.code = "Study-" + code;
- study.scope = "school";
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- study.createTime = now;
- }
- if (string.IsNullOrEmpty(study.id))
- {
- study.id = Guid.NewGuid().ToString();
- await client.GetContainer("TEAMModelOS", "Common").CreateItemAsync(study, new PartitionKey($"{study.code}"));
- }
- else
- {
- if (request.TryGetProperty("ids", out JsonElement ids))
- {
- List<string> gIds = study.tchLists;
- List<string> tIds = ids.ToObject<List<string>>();
- foreach (string gId in gIds)
- {
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(gId, new PartitionKey($"GroupList"));
- if (response.Status == 200)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- GroupList group = json.ToObject<GroupList>();
- foreach (string id in tIds)
- {
- Member member = new();
- member.id = id;
- member.type = 1;
- member.code = study.school;
- group.members.Add(member);
- }
- await GroupListService.UpsertList(group, _azureCosmos, _configuration, _serviceBus);
- // await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(group, group.id, new PartitionKey($"{group.code}"));
- }
- }
- }
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}"));
- }
- return Ok(new { study });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/save()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 签到
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[Authorize(Roles = "IES")]
- //[AuthToken(Roles = "teacher,admin")]
- [HttpPost("sign-in")]
- public async Task<IActionResult> Sign(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- request.TryGetProperty("tId", out JsonElement tId);
- request.TryGetProperty("mobile", out JsonElement mobile);
- string tmdid = "";
- if (!string.IsNullOrWhiteSpace($"{mobile}"))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
- if (coreUser != null)
- {
- tmdid = coreUser.id;
- }
- }
- else
- {
- if (!string.IsNullOrWhiteSpace($"{tId}") && string.IsNullOrWhiteSpace(tmdid))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{tId}" } }, _option.Location, _configuration);
- if (coreUser != null)
- {
- tmdid = coreUser.id;
- }
- }
- }
- if (string.IsNullOrWhiteSpace(tmdid))
- {
- return Ok(new { code = HttpStatusCode.NotFound, msg = "账号不存在!" });
- }
- var client = _azureCosmos.GetCosmosClient();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"StudyRecord-{tmdid}"));
- var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Study-{code}"));
- if (sresponse.Status == (int)HttpStatusCode.OK)
- {
- var sJson = await JsonDocument.ParseAsync(sresponse.ContentStream);
- Study study = sJson.ToObject<Study>();
- if (response.Status == (int)HttpStatusCode.OK)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- StudyRecord record = json.ToObject<StudyRecord>();
- if (!string.IsNullOrEmpty(record.sign))
- {
- return Ok(new { code = 200, msg = "已经签到" });
- }
- else
- {
- record.sign = study.startTime < now ? "2" : "1";
- record.signTime = now;
- }
- await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(record, record.id, new PartitionKey($"{record.code}"));
- }
- else
- {
- StudyRecord setting = new();
- setting.id = id.GetString();
- setting.tId = tmdid;
- setting.signTime = now;
- setting.code = "StudyRecord-" + tmdid;
- setting.sign = study.startTime < now ? "2" : "1";
- if (string.IsNullOrEmpty(setting.sign) || setting.signTime == 0)
- {
- return Ok(new { code = 500, msg = "签到失败,请重新签到" });
- }
- await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(setting, new PartitionKey($"{setting.code}"));
- }
- }
- else
- {
- return Ok(new { code = HttpStatusCode.NotFound });
- }
- var srecord = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"StudyRecord-{tmdid}"));
- if (srecord.Status == (int)HttpStatusCode.OK)
- {
- return Ok();
- }
- else
- {
- return Ok(new { code = 500, msg = "签到失败,请重新签到" });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/sign-in()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /*/// <summary>
- /// 上传作业
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upload")]
- public async Task<IActionResult> Upload(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("hw", out JsonElement hw)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Study-{code}"));
- if (response.Status == (int)HttpStatusCode.OK)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- Study study = json.ToObject<Study>();
- bool flag = study.teachers.Exists(s => s.id.Equals(tId.GetString()));
- if (flag)
- {
- foreach (Setting setting in study.teachers)
- {
- if (setting.id.Equals(tId.GetString()))
- {
- setting.hwTime = now;
- setting.hw = hw.GetString();
- }
- }
- }
- else {
- Setting setting = new Setting();
- setting.id = tId.GetString();
- setting.hwTime = now;
- setting.hw = hw.GetString();
- study.teachers.Add(setting);
- }
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}"));
- }
- else
- {
- return Ok(new { code = HttpStatusCode.NotFound });
- }
- return Ok(new { code = HttpStatusCode.OK});
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/upload()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }*/
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- try
- {
- object userScope = null;
- object _standard = null;
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- string standard = null;
- HttpContext?.Items?.TryGetValue("Scope", out userScope);
- if (userScope != null && $"{userScope}".Equals(Constant.ScopeTeacher))
- {
- HttpContext?.Items?.TryGetValue("Standard", out _standard);
- standard = _standard != null && string.IsNullOrEmpty($"{userScope}") ? _standard.ToString() : null;
- }
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- var sresponse = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Study-{code}"));
- if (sresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- Study study = json.ToObject<Study>();
- //必须是本人或者这个学校的管理者才能删除
- bool flag = false;
- if (study.creatorId == userid)
- {
- flag = true;
- }
- else
- {
- if (study.scope == "school" && study.school.Equals(school))
- {
- flag = true;
- }
- }
- List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
- if (study.groupLists.Count > 0)
- {
- var group = study.groupLists;
- foreach (var gp in group)
- {
- foreach (KeyValuePair<string, List<string>> pp in gp)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- try
- {
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, study.tchLists, study.school, ps);
- await StatisticsService.DoChange(new TeacherTrainChange
- { standard = standard, tmdids = members.Select(x => x.id)?.ToList(), school = study.school, update = new HashSet<string> { StatisticsService.OfflineRecord }, statistics = 0 }, _azureCosmos);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/delete()ex\n{ex.Message}\n{ex.StackTrace},\n", GroupNames.醍摩豆服務運維群組);
- }
- if (flag)
- {
- study.status = 404;
- if (!string.IsNullOrEmpty(study.examId))
- {
- Azure.Response response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.examId, new PartitionKey($"ExamLite-{code}"));
- if (response.Status == 200)
- {
- ExamLite data = JsonDocument.Parse(response.Content).RootElement.Deserialize<ExamLite>();
- data.status = 404;
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(data, data.id, new PartitionKey($"ExamLite-{code}"));
- }
- }
- if (!string.IsNullOrEmpty(study.surveyId))
- {
- Azure.Response response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.surveyId, new PartitionKey($"Survey-{code}"));
- if (response.Status == 200)
- {
- Survey data = JsonDocument.Parse(response.Content).RootElement.Deserialize<Survey>();
- data.status = 404;
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(data, data.id, new PartitionKey($"Survey-{code}"));
- }
- }
- if (!string.IsNullOrEmpty(study.workId))
- {
- Azure.Response response = await client.GetContainer("TEAMModelOS", "Common").ReadItemStreamAsync(study.workId, new PartitionKey($"Homework-{code}"));
- if (response.Status == 200)
- {
- Homework data = JsonDocument.Parse(response.Content).RootElement.Deserialize<Homework>();
- data.status = 404;
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(data, data.id, new PartitionKey($"Homework-{code}"));
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}"));
- }
- }
- return Ok(new { id });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/delete()\n{e.Message}\n{e.StackTrace},\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find")]
- public async Task<IActionResult> Find(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.id,c.img,c.name,c.type,c.startTime,c.endTime,c.presenter,c.topic,c.address,c.owner,c.progress,c.groupLists from c where (c.status<>404 or IS_DEFINED(c.status) = false ) ";
- string continuationToken = string.Empty;
- string token = default;
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (requert.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- iscontinuation = true;
- };
- //默认不指定返回大小
- int? topcout = null;
- if (requert.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- List<object> studies = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, continuationToken: token, requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Study-{code}") }))
- {
- 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())
- {
- studies.Add(obj.ToObject<object>());
- }
- }
- if (iscontinuation)
- {
- continuationToken = item.GetContinuationToken();
- break;
- }
- }
- return Ok(new { studies });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/find()\n{e.Message}\n{e.StackTrace}\n{e .StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary")]
- public async Task<IActionResult> FindSummary(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- Study study = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Study>(id.GetString(), new PartitionKey($"Study-{code}"));
- if (study != null)
- {
- (List<RMember> tchList, List<RGroupList> classInfo) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, study.tchLists, study.school);
- List<StudyRecord> records = new();
- foreach (var member in tchList)
- {
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey($"StudyRecord-{member.id}"));
- if (response.Status == (int)HttpStatusCode.OK)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- StudyRecord record = json.ToObject<StudyRecord>();
- records.Add(record);
- }
- }
- List<ufo> ufos = new();
- if (study.teacIds != null && study.teacIds.Count > 0)
- {
- List<string> tIds = new();
- var content = new StringContent(study.teacIds.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- try
- {
- List<ufo> tmdInfos = json.ToObject<List<ufo>>();
- if (tmdInfos.IsNotEmpty())
- {
- foreach (ufo fo in tmdInfos)
- {
- fo.type = 1;
- tIds.Add(fo.id);
- }
- ufos.AddRange(tmdInfos);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_coreAPIHttpService.options.Get("Default").location}用户转换失败:{_coreAPIHttpService.options.Get("Default").url}{json}\n ", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- else
- {
- long time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- study.updateTime = time;
- await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}"));
- }
- // (List<TmdInfo> tmdInfos, List<ClassListInfo> classInfos) = await TriggerStuActivity.GetTchList(client, _dingDing, ids, $"{school}");
- //(List<TmdInfo> tchList, _) = await TriggerStuActivity.GetTchList(client, _dingDing, study.tchLists, study.school);
- return Ok(new { study, records, ufos, status = 200 });
- }
- else
- {
- return Ok(new { study, status = 404 });
- }
- }
- catch (CosmosException ex) when (ex.Status == 404)
- {
- return Ok(new { status = 404 });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/FindSummary()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { status = 404 });
- }
- }
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-by-teacher")]
- public async Task<IActionResult> FindByTeacher(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.id,c.img,c.name,c.startTime,c.type,c.endTime,c.presenter,c.topic,c.address,c.owner from c join A0 in c.teachers where A0.id = '{tId}'";
- List<object> studies = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
- {
- 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())
- {
- studies.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { studies });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/find-by-teacher()\n{e.Message}\n{e.StackTrace}\n{e .StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("find-summary-by-teacher")]
- public async Task<IActionResult> FindSummaryByTeacher(JsonElement requert)
- {
- try
- {
- if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!requert.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- List<object> studies = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select value(c) from c join A0 in c.teachers where A0.id = '{tId}' and c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
- {
- 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())
- {
- studies.Add(obj.ToObject<object>());
- }
- }
- }
- return Ok(new { studies });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},study/find-summary-by-teacher()\n{e.Message}\n{e.StackTrace}\n{e .StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,area")]
- [HttpPost("audit")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> Audit(JsonElement request)
- {
- try
- {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- if (!HttpContext.Items.TryGetValue("Standard", out object standard)) return BadRequest();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //if (!request.TryGetProperty("tId", out JsonElement tId)) return BadRequest();
- if (!request.TryGetProperty("type", out JsonElement type)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<Dictionary<string, List<string>>> acId = id.ToObject<List<Dictionary<string, List<string>>>>();
- List<string> value = new List<string>();
- List<Task> tasks = new();
- List<Task<ItemResponse<StudyRecord>>> tasky = new();
- List<(string op, string tId)> opp = new List<(string op, string tId)>();
- int statu = type.GetInt32();
- (string standard, List<string> tmdid, string school, List<string> update, int statistics) list = ($"{standard}", null, school, new List<string> { StatisticsService.OfflineRecord }, 0);
- HashSet<string> tch = new HashSet<string>();
- foreach (var aId in acId)
- {
- foreach (KeyValuePair<string, List<string>> pair in aId)
- {
- /* await foreach (var key in TeacTask(pair.Key, pair.Value, client, type.GetInt32(), now, standard, school)) {
- opp.Add((key.op,key.tId));
- };*/
- foreach (var teacId in pair.Value)
- {
- var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(pair.Key, new PartitionKey($"StudyRecord-{teacId}"));
- if (response.Status == 200)
- {
- var json = await JsonDocument.ParseAsync(response.ContentStream);
- StudyRecord study = json.ToObject<StudyRecord>();
- if (study.tId.Equals(teacId) && study.status == statu)
- {
- continue;
- }
- else
- {
- study.status = statu;
- study.aTime = now;
- }
- tasky.Add(client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(study, study.id, new PartitionKey($"{study.code}")));
- }
- else
- {
- StudyRecord setting = new()
- {
- id = pair.Key,
- tId = teacId,
- code = "StudyRecord-" + teacId,
- status = statu,
- aTime = now
- };
- tasky.Add(client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(setting, new PartitionKey($"{setting.code}")));
- }
- tch.Add($"{teacId}");
- }
- }
- }
- list.tmdid = new List<string>(tch);
- await tasky.TaskPage(10);
- if (statu == 1) {
- var messageBlobPDF= new ServiceBusMessage(new { id = tch, school, userType = "tmdid" }.ToJsonString());
- var GenPdfQueue = _configuration.GetValue<string>("Azure:ServiceBus:GenPdfQueue");
- await _serviceBus.GetServiceBusClient().SendMessageAsync(GenPdfQueue, messageBlobPDF);
- }
-
- await StatisticsService.SendServiceBus(list, _configuration, _serviceBus, client);
- return Ok(new { code = HttpStatusCode.OK });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},Study/audit()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- private async IAsyncEnumerable<(string op, string tId)> AuditTask(List<Dictionary<string, List<string>>> ids, CosmosClient client, int type, long now, object standard, string school)
- {
- List<Task> tasks = new();
- List<Task<ItemResponse<StudyRecord>>> tasky = new();
- foreach (var id in ids)
- {
- foreach (KeyValuePair<string, List<string>> pair in id)
- {
- foreach (var teacId in pair.Value)
- {
- //var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(pair.Key, new PartitionKey($"StudyRecord-{teacId}"));
- List<StudyRecord> studyRecords = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StudyRecord>(queryText: $"select value(c) from c where c.id = '{pair.Key}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StudyRecord-{teacId}") }))
- {
- studyRecords.Add(item);
- }
- if (studyRecords.Count > 0)
- {
- if (studyRecords[0].tId.Equals(teacId))
- {
- studyRecords[0].status = type;
- studyRecords[0].aTime = now;
- }
- tasky.Add(client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(studyRecords[0], studyRecords[0].id, new PartitionKey($"{studyRecords[0].code}")));
- }
- else
- {
- StudyRecord setting = new()
- {
- id = pair.Key,
- tId = teacId,
- code = "StudyRecord-" + teacId,
- status = type,
- aTime = now
- };
- tasky.Add(client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(setting, new PartitionKey($"{setting.code}")));
- }
- //tasks.Add(StatisticsService.SendServiceBus($"{standard}", $"{teacId}", $"{school}", StatisticsService.OfflineRecord, 1, _configuration, _serviceBus));
- }
- yield return ("", "");
- }
- }
- await Task.WhenAll(tasks);
- await Task.WhenAll(tasky);
- }
- private async IAsyncEnumerable<(string op, string tId)> TeacTask(string id, List<string> ids, CosmosClient client, int type, long now, object standard, string school)
- {
- List<Task> tasks = new();
- foreach (var teacId in ids)
- {
- /* var response = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(id, new PartitionKey($"StudyRecord-{teacId}"));*/
- List<StudyRecord> studyRecords = new();
- await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<StudyRecord>(queryText: $"select value(c) from c where c.id = '{id}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"StudyRecord-{teacId}") }))
- {
- studyRecords.Add(item);
- }
- string op;
- if (studyRecords.Count > 0)
- {
- if (studyRecords[0].tId.Equals(teacId))
- {
- studyRecords[0].status = type;
- studyRecords[0].aTime = now;
- }
- op = "update";
- await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(studyRecords[0], studyRecords[0].id, new PartitionKey($"{studyRecords[0].code}"));
- }
- else
- {
- StudyRecord setting = new()
- {
- id = id,
- tId = teacId,
- code = "StudyRecord-" + teacId,
- status = type,
- aTime = now
- };
- op = "insert";
- await client.GetContainer("TEAMModelOS", "Teacher").CreateItemAsync(setting, new PartitionKey($"{setting.code}"));
- }
- //tasks.Add(StatisticsService.SendServiceBus($"{standard}", $"{teacId}", $"{school}", StatisticsService.OfflineRecord, 1, _configuration, _serviceBus));
- yield return (op, teacId);
- }
- await Task.WhenAll(tasks);
- }
- [HttpPost("gen-pdf")]
- //[Authorize(Roles = Constant.Role_Root)]
- public IActionResult GenPdf(JsonElement json)
- {
- //https://article.itxueyuan.com/JAxOnG
- //http://t.zoukankan.com/hsiang-p-14608694.html
- //https://github.com/rdvojmoc/DinkToPdf
- //https://blog.csdn.net/u011966339/article/details/114964016?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-114964016-blog-118609642.pc_relevant_antiscanv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3
-
- try
- {
- var html = Constant.html.Replace("{c.stuname}", "黄总");
- html = html.Replace("{c.details}", @"<tr>
- <td> 语文学科如何在A1技术支持下进行学情分析 </td>
- <td> 信息化教学案例展示与分享 </td >
- <td> 1 </td >
- <td> 1 </td >
- <td> 2022 - 04 - 07 到 2022 - 04 - 14 </td>
- <td></td>
- <td> 扫码签到、作业提交、问卷反馈、评测活动 </td>
- <td> 已完成 </td >
- </tr> ");
- GlobalSettings globalSettings = new GlobalSettings();
- globalSettings.ColorMode = ColorMode.Color;
- globalSettings.Orientation = Orientation.Portrait;
- globalSettings.PaperSize = PaperKind.A4;
- globalSettings.Margins = new MarginSettings { Top = 25, Bottom = 25 };
- globalSettings.Out = @"E:\pdf\test.pdf";
- ObjectSettings objectSettings = new ObjectSettings();
- objectSettings.PagesCount = true;
- objectSettings.HtmlContent = html;
- WebSettings webSettings = new WebSettings();
- webSettings.DefaultEncoding = "utf-8";
- HeaderSettings headerSettings = new HeaderSettings();
- headerSettings.FontSize = 15;
- headerSettings.FontName = "fangsong";
- headerSettings.Right = "";
- // headerSettings.Line = true;
- FooterSettings footerSettings = new FooterSettings();
- footerSettings.FontSize = 12;
- footerSettings.FontName = "Ariel";
- footerSettings.Center = "校本研修活动完成情况([page]/[toPage])页";
- // footerSettings.Line = true;
- objectSettings.HeaderSettings = headerSettings;
- objectSettings.FooterSettings = footerSettings;
- objectSettings.WebSettings = webSettings;
- HtmlToPdfDocument htmlToPdfDocument = new HtmlToPdfDocument()
- {
- GlobalSettings = globalSettings,
- Objects = { objectSettings },
- };
- var a = _converter.Convert(htmlToPdfDocument);
- MemoryStream m = new MemoryStream(a);
- /* FileStream fs = new FileStream("F:\\1111111111111\\SimplePdf1.pdf", FileMode.Create, FileAccess.Write, FileShare.Read);
- m.WriteTo(fs);
- m.Close();
- fs.Close();*/
- //var doc = new HtmlToPdfDocument()
- //{
- // GlobalSettings = {
- // ColorMode = ColorMode.Color,
- // Orientation = Orientation.Portrait,
- // PaperSize = PaperKind.A4,
- // Margins = new MarginSettings() { Top = 10 },
- // Out = @"F:\test.pdf",
- // },
- // Objects = {
- // new ObjectSettings()
- // {
- // Page = "https://zhidao.baidu.com/question/175696719173618004.html",
- // },
- // }
- //};
- //_converter.Convert(doc);
- return Ok();
- // return Ok(File(a, "application/octet-stream", "SimplePdf.pdf"));
- }
- catch (Exception ex)
- {
- return BadRequest(new { ex = ex.StackTrace, exmsg = ex.Message });
- }
- }
- }
- }
|