123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687 |
- using Microsoft.Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models.Dto;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.Models;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.Filter;
- using Azure.Storage.Blobs.Models;
- using TEAMModelOS.SDK.Models.Cosmos.Inner;
- using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
- using System.Net.Http;
- using TEAMModelOS.SDK.Models.Cosmos;
- using Azure.Messaging.ServiceBus;
- using Azure.Storage.Sas;
- using TEAMModelOS.SDK.Models.Cosmos;
- using Microsoft.Extensions.Configuration;
- using System.IO;
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.SDK.Services;
- using TEAMModelOS.SDK.Models.Service.BI;
- namespace TEAMModelOS.Controllers
- {
- /// <summary>
- /// 投票活动
- /// </summary>
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("common/survey")]
- [ApiController]
- public class SurveyController : ControllerBase
- {
- private readonly AzureRedisFactory _azureRedis;
- 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 IHttpClientFactory _clientFactory;
- public IConfiguration _configuration { get; set; }
- public SurveyController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option,
- AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, IHttpClientFactory clientFactory, IConfiguration configuration)
- {
- _snowflakeId = snowflakeId;
- _serviceBus = serviceBus;
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- _azureRedis = azureRedis;
- _azureStorage = azureStorage;
- _clientFactory = clientFactory;
- _configuration = configuration;
- }
- /// <summary>
- /// 新增 或 修改投票活动
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("upsert")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin", Permissions = "schoolAc-upd")]
- public async Task<IActionResult> Upsert(Survey request)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- request.code = request.pk + "-" + request.code;
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- request.createTime = now;
- request.ttl = -1;
- //如果设置的时间是小于当前时间则立即发布
- if (request.startTime <= 0)
- {
- request.startTime = now;
- }
- if (string.IsNullOrEmpty(request.id))
- {
- request.id = Guid.NewGuid().ToString();
- if (string.IsNullOrEmpty(request.progress))
- {
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- }
- var messageBlob = new ServiceBusMessage();
- string blobcntr = null;
- if (request.scope.Equals("school"))
- {
- blobcntr = request.school;
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"survey/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"survey", name = $"{request.school}" }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- blobcntr = request.creatorId;
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"survey/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"survey", name = $"{request.creatorId}" }, _serviceBus, _configuration, _azureRedis);
- }
- request.recordUrl = $"/survey/{request.id}/record.json";
- var cods = new { records = new List<string>(), userids = new List<string>(), question = new List<QuestionRecord>() };
- await _azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(cods.ToJsonString(), "survey", $"{request.id}/record.json");
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, request.school, "Survey", 1);//BI统计增/减量
- }
- else
- {
- string blobcntr = null;
- var response = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(request.id, new PartitionKey($"{request.code}"));
- if (request.scope.Equals("school"))
- {
- blobcntr = request.school;
- request.size = await _azureStorage.GetBlobContainerClient(request.school).GetBlobsSize($"survey/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"survey", name = $"{request.school}" }, _serviceBus, _configuration, _azureRedis);
- }
- else
- {
- blobcntr = request.creatorId;
- request.size = await _azureStorage.GetBlobContainerClient(request.creatorId).GetBlobsSize($"survey/{request.id}");
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = $"survey", name = $"{request.creatorId}" }, _serviceBus, _configuration, _azureRedis);
- }
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- var info = json.ToObject<Survey>();
- /* if (info.progress.Equals("going"))
- {
- return Ok(new { v = "活动正在进行中" });
- }*/
- if (string.IsNullOrEmpty(request.progress))
- {
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- }
- //request.progress = info.progress;
- request.recordUrl = $"/survey/{request.id}/record.json";
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(request, info.id, new PartitionKey($"{info.code}"));
- }
- else
- {
- if (string.IsNullOrEmpty(request.progress))
- {
- if (request.startTime > now)
- {
- request.progress = "pending";
- }
- else
- {
- request.progress = "going";
- }
- }
- request.recordUrl = $"/survey/{request.id}/record.json";
- var cods = new { records = new List<string>(), userids = new List<string>(), question = new List<QuestionRecord>() };
- await _azureStorage.GetBlobContainerClient(blobcntr).UploadFileByContainer(cods.ToJsonString(), "survey", $"{request.id}/record.json");
- request = await client.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync(request, new PartitionKey($"{request.code}"));
- await BIStats.SetTypeAddStats(client, _dingDing, request.school, "Survey", 1);//BI统计增/减量
- }
- }
- return Ok(new { survey = request });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/save()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(ex.StackTrace);
- }
- }
- /// <summary>
- /// 查询问卷调查,用于列表,编辑,查看
- /// </summary>
- /// <data>
- ///Survey-学校/教师编码 活动分区 !"code":"hbcn"/1606285227
- ///时间筛选范围开始时间 默认30天之前 ?"stime":1608274766154
- ///时间筛选范围结束时间 默认当前时间 ?"etime":1608274766666
- ///每页大小 ?"count":10/null/Undefined
- ///分页Token ?"continuationToken":Undefined/null/"[{\"token\":\"+RID:~omxMAP3ipcSEEwAAAAAAAA==#RT:2#TRC:20#ISV:2#IEO:65551#QCF:1#FPC:AYQTAAAAAAAAiRMAAAAAAAA=\",\"range\":{\"min\":\"\",\"max\":\"FF\"}}]"
- /// 当前状态 ?"progress":Undefined/null/"" 表示两种状态都要查询/ "going"/"finish" 表示查询进行中/ 或者已完成 学生端只能查询正在进行或已经结束 going 已发布|finish 已结束
- /// </data>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-read,schoolAc-upd")]
- public async Task<IActionResult> Find(JsonElement request)
- {
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- //必须有学校或者教师编码
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- //开始时间,
- var stimestamp = "";
- if (request.TryGetProperty("stime", out JsonElement stime))
- {
- if (long.TryParse($"{stime}", out long data))
- {
- stimestamp = $" and c.createTime >= {data} ";
- };
- };
- //默认当前时间
- var etimestamp = "";
- if (request.TryGetProperty("etime", out JsonElement etime))
- {
- if (long.TryParse($"{etime}", out long data))
- {
- etimestamp = $" and c.createTime <= {data} ";
- };
- };
- var progresssql = "";
- if (request.TryGetProperty("progress", out JsonElement progress))
- {
- if (!progress.ValueKind.Equals(JsonValueKind.Undefined) && !progress.ValueKind.Equals(JsonValueKind.Null) && progress.ValueKind.Equals(JsonValueKind.String))
- {
- progresssql = $" and c.progress='{progress}' ";
- }
- }
- string token = null;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (int.TryParse($"{jcount}", out int data))
- {
- topcout = data;
- }
- };
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("token", out JsonElement continuation))
- {
- //指定了cancellationToken 表示需要进行分页
- if (!continuation.ValueKind.Equals(JsonValueKind.Null) && !continuation.ValueKind.Equals(JsonValueKind.Undefined))
- {
- token = continuation.GetString();
- }
- };
- List<Survey> surveys = new List<Survey>();
- var client = _azureCosmos.GetCosmosClient();
- var query = $"select c.owner, c.id,c.name,c.code,c.startTime,c.endTime,c.progress,c.classes,c.scope,c.school,c.targetType from c where (c.status<>404 or IS_DEFINED(c.status) = false ) and c.ttl=-1 {stimestamp} {etimestamp} {progresssql} ";
- if (string.IsNullOrEmpty(school))
- {
- query = $"{query} and c.scope='private' ";
- }
- query = $"{query} order by c.createTime desc ";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query, continuationToken: token,
- requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Survey-{code}") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (!string.IsNullOrEmpty(school))
- {
- obj.TryGetProperty("scope", out JsonElement scope);
- obj.TryGetProperty("school", out JsonElement sco);
- //只能查出相关学校的
- if (!scope.GetString().Equals("private") && !string.IsNullOrEmpty(sco.GetString()) && sco.GetString().Equals(school))
- {
- surveys.Add(obj.ToObject<Survey>());
- }
- //和自己私人发布的
- if (scope.GetString().Equals("private"))
- {
- surveys.Add(obj.ToObject<Survey>());
- }
- }
- else
- {
- surveys.Add(obj.ToObject<Survey>());
- }
- }
- }
- if (iscontinuation)
- {
- token = item.ContinuationToken;
- break;
- }
- }
- //var query = $"select c.id,c.name,c.code,c.startTime,c.endTime,c.progress,c.classes from c where c.createTime >= {stimestamp} and c.createTime <= {etimestamp} {progresssql } ";
- //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIteratorSql(queryText: query,
- // requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey($"Survey-{code}") }))
- //{
- // using var json = await JsonDocument.ParseAsync(item.Content);
- // if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- // {
- // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- // {
- // surveys.Add(obj.ToObject<JsonElement>());
- // }
- // //如果需要分页则跳出
- // if (iscontinuation)
- // {
- // continuationToken = item.ContinuationToken;
- // break;
- // }
- // }
- //}
- return Ok(new { surveys, token });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/find()\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest(ex.StackTrace);
- }
- }
- ///<summary>
- /// 查询问卷调查,用于创建者列表,编辑,查看,作答人员查看
- /// </summary>
- /// <data>
- /// ! "id":"3c075347-75ef-4bcb-ae03-68678d02d5ef",
- /// ! "code":"Survey-hbcn"/"code":"Survey-1606285227"
- /// </data>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-id")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-read,schoolAc-upd")]
- public async Task<IActionResult> FindById(JsonElement request)
- {
- Survey survey = null;
- //活动id
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.GetString(), new PartitionKey($"{code}"));
- if (survey != null)
- {
- return Ok(new { survey, status = 200 });
- }
- else
- {
- return Ok(new { survey, status = 404 });
- }
- }
- catch (CosmosException ex)
- {
- return Ok(new { survey, status = 404 });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/survey/find-id\n{ex.Message}\n{ex.StackTrace}\n{id}\n{code} ", GroupNames.醍摩豆服務運維群組);
- return Ok(new { survey, status = 404 });
- }
- }
- /// <summary>
- /// 删除问卷调查 TODO 使用ttl删除,并处理相关事务逻辑
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("delete")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin", Permissions = "schoolAc-upd")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- Survey survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemAsync<Survey>(id.GetString(), new PartitionKey($"{code}"));
- bool flag = false;
- //必须是本人或者这个学校的管理者才能删除
- if (survey.creatorId == userid)
- {
- flag = true;
- }
- else
- {
- if (survey.scope.Equals("school") && survey.school.Equals(school))
- {
- flag = true;
- }
- }
- if (flag)
- {
- //使用ttl删除,并处理相关事务逻辑
- survey.status = 404;
- survey = await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync(survey, survey.id, new PartitionKey($"{survey.code}"));
- _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
- _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
- //删除blob 相关资料
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, $"{code}".Replace("Survey-", ""), new List<string> { Path.Combine("survey", survey.id) + "/" });
- //通知删除信息
- await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "delete", root = $"survey", name = $"{code}".Replace("Survey-", "") }, _serviceBus, _configuration, _azureRedis);
- await _dingDing.SendBotMsg($"{_option.Location}-问卷调查【{survey.name}-{survey.id}】被删除", GroupNames.醍摩豆服務運維群組);
- return Ok(new { flag });
- }
- else
- {
- return Ok(new { flag });
- }
- }
- catch (Exception e)
- {
- return BadRequest(e.StackTrace);
- }
- }
- /// <summary>
- /// 问卷答案提交
- /// </summary>
- /// <redis>
- /// Survey:Record:e6b887f8-adb5-3677-bcc7-3b36450909df_Survey-1595321354 {"C":2,"A":2,"other":2}
- /// </redis>
- /// <param name="request">
- /// !"id":"aaaa"
- /// !"code":"Survey-hbcn"/"code":"Survey-1606285227"
- /// !"record":[["A","B"],["A"],["D"],[],["建议提升服务质量"]]
- /// </param>
- /// <returns>
- /// msgid=0投票失败,1提交成功,2不在时间范围内,3不在发布范围内,6未设置投票项
- /// </returns>
- [ProducesDefaultResponseType]
- [HttpPost("answer")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-upd,schoolAc-read")]
- public async Task<IActionResult> Answer(JsonElement request)
- {
- object userScope = null;
- object _standard = null;
- 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();
- if (request.TryGetProperty("userid", out JsonElement _userid))
- {
- (int msgid, int taskStatus) = await ActivityStudentService.Answer(_dingDing, _option, request, _azureCosmos, _azureRedis, $"{userid}", school, _azureStorage, standard, _serviceBus, _configuration);
- return Ok(new { msgid, taskStatus });
- }
- else { return Ok(new { msgid = 0 }); }
- }
- /// <summary>
- /// 问卷答案提交
- /// </summary>
- /// <redis>
- /// Survey:Record:e6b887f8-adb5-3677-bcc7-3b36450909df_Survey-1595321354 {"C":2,"A":2,"other":2}
- /// </redis>
- /// <param name="request">
- /// !"id":"aaaa"
- /// !"code":"Survey-hbcn"/"code":"Survey-1606285227"
- /// </param>
- /// <returns>
- /// msgid=0投票失败,1提交成功,2不在时间范围内,3不在发布范围内,6未设置投票项
- /// </returns>
- [ProducesDefaultResponseType]
- [HttpPost("answered-list")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-upd,schoolAc-read")]
- public async Task<IActionResult> AnsweredList(JsonElement request)
- {
- // var (userid, _, _, _) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return BadRequest();
- }
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code))
- {
- return BadRequest();
- }
- List<string> userids = new List<string>();
- var values = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{id}");
- if (values != default && values.Length > 0)
- {
- foreach (var val in values)
- {
- userids.Add(val);
- }
- }
- return Ok(new { userids = userids });
- }
- /// <summary>
- /// 问卷答案提交
- /// </summary>
- /// <redis>
- /// Survey:Record:e6b887f8-adb5-3677-bcc7-3b36450909df_Survey-1595321354 {"C":2,"A":2,"other":2}
- /// </redis>
- /// <param name="request">
- /// !"id":"aaaa"
- /// !"code":"Survey-hbcn"/"code":"Survey-1606285227"
- /// </param>
- /// <returns>
- /// msgid=0投票失败,1提交成功,2不在时间范围内,3不在发布范围内,6未设置投票项
- /// </returns>
- [ProducesDefaultResponseType]
- [HttpPost("answered")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-upd,schoolAc-read")]
- public async Task<IActionResult> Answered(JsonElement request)
- {
- var (userid, _, _, _) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return BadRequest();
- }
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code))
- {
- return BadRequest();
- }
- List<string> userids = new List<string>();
- var answered = await _azureRedis.GetRedisClient(8).SetContainsAsync($"Survey:Submit:{id}", userid);
- return Ok(new { answered = answered });
- }
- /// <summary>
- /// 问卷记录 当活动没结算且没有BlobUrl时则调用此接口
- /// </summary>
- /// <redis>
- /// {"C":2,"A":2,"other":2}
- /// </redis>
- /// <param name="request">
- /// !"id":"aaaa"
- /// !"code":"Survey-hbcn"/"code":"Survey-1606285227"
- /// </param>
- /// <returns>
- /// </returns>
- [ProducesDefaultResponseType]
- [HttpPost("record")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student", Permissions = "schoolAc-upd,schoolAc-read")]
- public async Task<IActionResult> Record(JsonElement request)
- {
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return BadRequest();
- }
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code))
- {
- return BadRequest();
- }
- //获取问卷记录
- var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{id}");
- List<dynamic> res = new List<dynamic>();
- foreach (var rcd in records)
- {
- var value = rcd.Value.ToString().ToObject<JsonElement>();
- res.Add(new { index = rcd.Name.ToString(), ans = value });
- }
- return Ok(new { records = res });
- }
- /*[ProducesDefaultResponseType]
- [HttpPost("draft-record")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> DraftRecord(JsonElement request)
- {
- try
- {
- //活动ID
- if (!request.TryGetProperty("activityId", out JsonElement activityId))
- {
- return BadRequest();
- }
- //学生ID
- if (!request.TryGetProperty("stuId", out JsonElement stuId))
- {
- return BadRequest();
- }
- if (!request.TryGetProperty("survey", out JsonElement survey))
- {
- return BadRequest();
- }
- var client = _azureCosmos.GetCosmosClient();
- //获取问卷记录
- DraftSurvey draft = new()
- {
- id = activityId.GetString(),
- ttl = -1,
- code = $"DraftSurvey-{stuId}",
- stuId = stuId.GetString(),
- JsonElement = survey
- };
- await client.GetContainer("TEAMModelOS", "Student").UpsertItemAsync(draft, new PartitionKey($"{draft.code}"));
- return Ok(new { records = draft });
- }
- catch (Exception)
- {
- return Ok(new { code = 500 });
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("find-draft")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> findDraft(JsonElement request)
- {
- try
- {
- //活动ID
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return BadRequest();
- }
- if (!request.TryGetProperty("stuId", out JsonElement stuId))
- {
- return BadRequest();
- }
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer("TEAMModelOS", "Student").ReadItemStreamAsync(id.GetString(), new PartitionKey($"DraftSurvey-{stuId}"));
- DraftSurvey draft = new();
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- draft = json.ToObject<DraftSurvey>();
- }
- return Ok(new { records = draft });
- }
- catch (Exception)
- {
- return Ok(new { code = 500 });
- }
- }*/
- }
- }
|