123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- using Azure;
- using Microsoft.Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos;
-
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.Filter;
- using Microsoft.Extensions.Hosting;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.SDK.Models.Dtos;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- //
- [Route("common/volume")]
- [ApiController]
- public class VolumeController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly SnowflakeId _snowflakeId;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- private readonly IConfiguration _configuration;
- public VolumeController(IConfiguration configuration, CoreAPIHttpService coreAPIHttpServic, IWebHostEnvironment environment, AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
- {
- _azureCosmos = azureCosmos;
- _snowflakeId = snowflakeId;
- _dingDing = dingDing;
- _option = option?.Value;
- _environment = environment;
- _coreAPIHttpService = coreAPIHttpServic;
- _configuration = configuration;
- }
- /*
- {
- "id": "册别id",
- "code": "学校编码/教师编码",
- "scope": "school/private"
- }
- */
- /// <summary>
- /// 删除册别
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("delete")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> Delete(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- string sql = $"select value(c) from c where c.volumeId='{id}'";
- List<Syllabus> syllabus = new List<Syllabus>();
- if (scope.ToString().Equals("school"))
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Syllabus>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") })) {
- syllabus.Add(item);
- }
- if (syllabus.IsNotEmpty())
- {
- foreach (var s in syllabus) {
- if (s.auth.IsNotEmpty()) {
- foreach (var a in s.auth) {
- try {
- Share share = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Share>(s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
- share.agree = -1;
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Share>(share, s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
- } catch (Exception ex) {
- ///仅用于处理查不到该数据的问题
- }
- }
- }
- }
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemsStreamAsync(syllabus.Select(x => x.id).ToList(), $"Syllabus-{code}");
- }
- return Ok(new { code = response.StatusCode });
- }
- else
- {
- var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"Volume-{code}"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<Syllabus>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Syllabus-{code}") }))
- {
- syllabus.Add(item);
- }
- if (syllabus.IsNotEmpty())
- {
- foreach (var s in syllabus)
- {
- if (s.auth.IsNotEmpty())
- {
- foreach (var a in s.auth)
- {
- try
- {
- Share share = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Share>(s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
- share.agree = -1;
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Share>(share, s.id, new PartitionKey($"Share-{a.type}-{a.tmdid}"));
- }
- catch (Exception ex)
- {
- ///仅用于处理查不到该数据的问题
- }
- }
- }
- }
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemsStreamAsync(syllabus.Select(x => x.id).ToList(), $"Syllabus-{code}");
- }
- return Ok(new { code = response.StatusCode });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},VolumeController:Delete\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- /*
- {
- "periodId": "学段id",
- "subjectId": "科目id",//
- "status": 1,//状态
- "code": "学校编码或者tmdid",
- "scope": "school/private" 如果是私人课纲 则学段科目id可以为空
- }
- */
- /// <summary>
- /// 查找册别
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("find")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin,student")]
- public async Task<IActionResult> Find(JsonElement request) {
- try {
- List<Volume> volumes = new List<Volume>();
- request.TryGetProperty("periodId", out JsonElement periodCode);
- request.TryGetProperty("subjectId", out JsonElement subjectCode);
- request.TryGetProperty("status", out JsonElement status);
-
- if (request.TryGetProperty("code", out JsonElement code))
- {
- request.TryGetProperty("scope", out JsonElement scope);
- //私有课纲
- if (scope.GetString().Equals("private"))
- {
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<Volume>(queryText: $"select value(c) from c where c.status = {status}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{code}") }))
- {
- volumes.Add(item);
- }
- }
- else if (scope.GetString().Equals("school"))
- {
- request.TryGetProperty("gradeIds", out JsonElement _gradeIds);
- string sql = $"select value(c) from c where c.status = {status} and c.periodId = '{periodCode}' and c.subjectId = '{subjectCode}'";
- if (_gradeIds.ValueKind.Equals(JsonValueKind.Array))
- {
- List<int> gradeIds = _gradeIds.EnumerateArray().Select(x => x.GetInt32()).ToList();
- sql= $"{sql} and c.gradeId in ({string.Join(",", gradeIds)})";
- }
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<Volume>(queryText:sql , requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{code}") }))
- {
- volumes.Add(item);
- }
- }
- }
- else { return BadRequest(); };
- volumes= volumes.OrderBy(x => x.order).ToList();
- return Ok(new { volumes });
- } catch (Exception ex) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},VolumeController:find\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //{"code":"hbcn/1528783259","scope":"school/private","update":"order","data":[{"key":"1","value":1}]}
- /// <summary>
- /// 批量更新相同的属性。
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("update-same-property")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> UpsertSameProperty(JsonElement request) {
- var client = _azureCosmos.GetCosmosClient();
- request.TryGetProperty("code", out JsonElement _code);
- request.TryGetProperty("scope", out JsonElement _scope);
- request.TryGetProperty("update", out JsonElement _update);
- request.TryGetProperty("data", out JsonElement _data);
- string tbname = $"{_scope}".Equals("school") ? "School" : "Teacher";
- List<Dictionary<string, object>> dicts = _data.ToObject<List<Dictionary<string, object>>>();
- foreach (var dict in dicts)
- {
- try
- {
- Volume volume = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<Volume>($"{dict["key"]}", new PartitionKey($"Volume-{_code}"));
- bool modify = false;
- switch (true)
- {
- //修改排序
- case bool when $"{_update}".Equals("order", StringComparison.OrdinalIgnoreCase):
- if (int.TryParse($"{dict["value"]}", out int order))
- {
- volume.order = order;
- modify= true;
- }
- break;
- }
- if (modify) {
- await client.GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<Volume>(volume, volume.id, new PartitionKey($"Volume-{_code}"));
- }
- }
- catch (Exception ex)
- {
- continue;
- }
- }
- return Ok(new { status=200});
- }
- /*
-
- {
- "id": "册别id",
- "code": "学校编码或教师id",
- "periodId": "学段id",
- "subjectId": "学科id",
- "gradeId": "年级id",
- "semesterId": "学期id",
- "status": 1,
- "name": "册别名",
- "creatorId": "创建者id",
- "school": "学校编码",
- "scope": "school|private"
- }
- */
- /// <summary>
- /// 新增册别
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "teacher")]
- [HttpPost("upsert")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> Upsert(Volume request) {
- //var client = _azureCosmos.GetCosmosClient();
- //if (request.editors != null && request.editors.Count > 5)
- //{
- // return BadRequest("共编人数大于5人!");
- // // throw new BizException("共编人数大于5人!");
- //}
- request.pk = "Volume";
- request.ttl = -1;
- request.code = "Volume-" + request.code;
- // 检查册别条件相同的是否存在
- List<string> coeditIds = new List<string>();
- string code = "Volume-";
- if (request.scope.Equals("private"))
- {
- code = $"Volume-{request.creatorId}";
- }
- else if (request.scope.Equals("school"))
- {
- code = $"Volume-{request.school}";
- }
- request.createTime= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- request.code = code;
- ///表示更新
- if (!string.IsNullOrEmpty(request.id))
- {
- try {
- if (request.scope.Equals("school"))
- {
- Volume volume= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Volume>(request.id, new PartitionKey(request.code));
- var exceptIds= volume.auth.Select(x => x.tmdid).Except(request.auth.Select(y => y.tmdid));
- if (exceptIds.Any()) {
- coeditIds.AddRange(exceptIds);
- }
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Volume>(request, request.id, new PartitionKey(request.code));
- }
- else if (request.scope.Equals("private")) {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Volume>(request, request.id, new PartitionKey(request.code));
- }
-
- }
- catch (Exception ex) {
- return BadRequest(new { error = ResponseCode.FAILED });
- }
- }
- //表示新增,则需要检查是否重复
- else {
- try
- {
- StringBuilder sql = new StringBuilder("select value(c) from c where c.status = 1 ");
- //私人课纲 只检查是否重名
- if (request.scope.Equals("private"))
- {
- sql.Append($" and c.name = '{request.name}' ");
- List<Volume> volumes = new List<Volume>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher")
- .GetItemQueryIteratorSql<Volume>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(request.code) }))
- {
- volumes.Add(item);
- }
- if (volumes.Count > 0)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST });
- }
- }
- //学校课纲检查 学段 科目 年级 学期
- else if (request.scope.Equals("school")
- && !string.IsNullOrEmpty(request.periodId)
- && !string.IsNullOrEmpty(request.subjectId)
- && request.gradeId>=0
- && !string.IsNullOrEmpty(request.semesterId))
- {
- sql.Append($" and c.periodId = '{request.periodId}' and c.subjectId = '{request.subjectId}'" +
- $" and c.gradeId = {request.gradeId} and c.semesterId = '{request.semesterId}' and c.name = '{request.name}' ");
- List<Volume> volumes = new List<Volume>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School")
- .GetItemQueryIteratorSql<Volume>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(request.code) })) {
- volumes.Add(item);
- }
- if (volumes.Count>0)
- {
- return Ok(new { error = ResponseCode.DATA_EXIST });
- }
- }
- else {
- return BadRequest(new { error = ResponseCode.PARAMS_ERROR });
- }
-
- request.id = System.Guid.NewGuid().ToString();
- if (request.scope.Equals("private"))
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync(request, new PartitionKey(request.code));
- }
- else {
- coeditIds = request.auth.Select(x => x.tmdid).ToList() ;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(request, new PartitionKey(request.code));
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},VolumeController:Upsert\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- ///处理更新 分享及共编的数据
- //if (request.auth.IsNotEmpty()) {
- // long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- // foreach (var au in request.auth) {
- // var share= new Share
- // {
- // id = request.id,
- // code = $"Share-{au.tmdid}",
- // pk = "Share",
- // ttl = -1,
- // scode=request.code,
- // issuer=request.creatorId,
- // createTime= now,
- // school=request.school,
- // scope=request.scope
- // };
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(share, new PartitionKey($"{share.code}"));
- // }
- //}
- if (coeditIds.IsNotEmpty()) {
- School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(request.school, new PartitionKey("Base"));
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", coeditIds.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIteratorSql<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, "coedit_volume", Constant.NotifyType_IES5_Contect,
- new Dictionary<string, object> { { "tmdname", request.creatorName }, { "tmdid", request.creatorId },{ "schoolName",school.name }, { "schoolId",school.id }, { "volumeId", request.id }, { "volumeName", request.name } },
- _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- return Ok(request);
- }
- }
- }
|