12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184 |
- using Azure.Cosmos;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using Azure;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using Azure.Messaging.ServiceBus;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Filter;
- using HTEXLib.COMM.Helpers;
- using System.Text;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.Extensions.Hosting;
- using OpenXmlPowerTools;
- using TEAMModelOS.SDK.Models.Dtos;
- using Microsoft.AspNetCore.Hosting;
- using Azure.Core;
- using static TEAMModelOS.SDK.Services.ActivityStudentService;
- using static TEAMModelOS.SDK.GroupListService;
- using DocumentFormat.OpenXml.Bibliography;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("grouplist")]
- [ApiController]
- public class GroupListController : ControllerBase
- {
- private AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly AzureServiceBusFactory _serviceBus;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureStorageFactory _azureStorage;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- private const string SummarySql = " c.id,c.code,c.name,c.no,c.periodId,c.scope,c.school,c.creatorId,c.type,c.year,c.tcount,c.scount,c.leader ,c.froms ,c.joinLock ,c.review,c.limitCount ,c.expire,c.qrcodeExpire,c.qrcodeDays ,c.grades ";
- public IConfiguration _configuration { get; set; }
- public GroupListController(IWebHostEnvironment environment, CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, DingDing dingDing, IOptionsSnapshot<Option> option,
- AzureServiceBusFactory serviceBus, AzureStorageFactory azureStorage, IConfiguration configuration, AzureRedisFactory azureRedis)
- {
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _option = option?.Value;
- _serviceBus = serviceBus;
- _configuration = configuration;
- _azureStorage = azureStorage;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- _azureRedis=azureRedis;
- }
- //学生获取自己已经加入的名单。
- [ProducesDefaultResponseType]
- [HttpPost("get-student-joined-grouplist")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "admin,teacher,student")]
- public async Task<IActionResult> GetMyCourseAndGroupList(JsonElement json)
- {
- var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- object scope = null;
- HttpContext?.Items.TryGetValue("Scope", out scope);
- int memberType = 2;
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- memberType = 2;
- // Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- memberType = 1;
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- memberType = 1;
- }
- List<GroupListGrp> groups = await GroupListService.GetMemberInGroupList(_coreAPIHttpService, client, _dingDing, userid, memberType, school, new List<string> { "class", "teach" });
- return Ok(new { groups = groups });
- }
- /// <summary>
- /// 扫码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("scan-code-join-list")]
- public async Task<IActionResult> ScanCodeJoinList(JsonElement json)
- {
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- json.TryGetProperty("school", out JsonElement school);
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("id_token", out JsonElement id_token);
- var jwt = new JwtSecurityToken(id_token.GetString());
- var id = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object name);
- jwt.Payload.TryGetValue("lang", out object lang);
- jwt.Payload.TryGetValue("picture", out object picture);
- try
- {
- TmdUser tmduser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(id, new PartitionKey("Base"));
- }
- catch (CosmosException ex)
- {
- if (ex.Status == 404)
- {
- //如果沒有,則初始化Teacher基本資料到Cosmos
- TmdUser tmduser = new TmdUser
- {
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- id = id,
- pk = "Base",
- code = "Base",
- name = name?.ToString(),
- picture = picture?.ToString(),
- //创建账号并第一次登录IES5则默认赠送1G
- defaultSchool = null,
- schools = new List<TmdUser.School>(),
- lang= lang?.ToString(),
- };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(tmduser, new PartitionKey("Base"));
- }
- }
- int year = DateTimeOffset.UtcNow.Year;
- (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", id, type: 1, $"{school}", year, $"{name}", $"{picture}", $"{lang}");
- //没有TmdUser时
- if (data.status == 0)
- {
- await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
- List<string> ids = new List<string>();
- if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
- {
- ids.Add(data.stuList.creatorId);
- }
- else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
- {
- //通知管理员
- string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.IsNotEmpty())
- {
- string bizcode = "scan-join";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- // _coreAPIHttpService.PushNotify(idNameCodes, $"scan-join_groupList", Constant.NotifyType_IES5_Course, new Dictionary<string, object> { { "tmdid", id }, { "tmdname", name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- return Ok(new { data.stuList, data.status });
- }
- else
- {
- return Ok(new { data.status });
- }
- }
- /// <summary>
- /// 根据邀请码加入名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher,student")]
- [HttpPost("input-code-join-list")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> InputCodeJoinList(JsonElement json)
- {
- string head_lang = _option.Location.Contains("China") ? "zh-cn" : "zh-tw";
- if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
- {
- head_lang = $"{_lang}";
- }
- if (!json.TryGetProperty("stuListNo", out JsonElement _stuListNo)) return BadRequest();
- var (userid, _name, _picture, school) = HttpContext.GetAuthTokenInfo();
- object scope = null;
- int type = 0;
- string no = null;
- var client = _azureCosmos.GetCosmosClient();
- HttpContext?.Items.TryGetValue("Scope", out scope);
- int year = DateTimeOffset.UtcNow.Year;
- if ($"{scope}".Equals(Constant.ScopeStudent))
- {
- type = 2;
- Student student = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>(userid, new PartitionKey($"Base-{school}"));
- no = student.no;
- year = student.year;
- }
- if ($"{scope}".Equals(Constant.ScopeTmdUser))
- {
- type = 1;
- }
- if ($"{scope}".Equals(Constant.ScopeTeacher))
- {
- type = 1;
- }
- (int status, GroupList stuList, Member member) data = await GroupListService.CodeJoinList(client, _azureRedis, $"{_stuListNo}", userid, type, school, year, _name, _picture, head_lang);
- if (data.status == 0)
- {
- await GroupListService.UpsertList(data.stuList, _azureCosmos, _configuration, _serviceBus);
- List<string> ids = new List<string>();
- if (data.stuList.scope.Equals("private") && !string.IsNullOrEmpty(data.stuList.creatorId))
- {
- ids.Add(data.stuList.creatorId);
- }
- else if (data.stuList.scope.Equals("school") && !string.IsNullOrEmpty(data.stuList.school))
- {
- //通知管理员
- string sql = "select distinct value(c.id) from c where array_contains(c.roles,'admin')";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<string>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Teacher-{school}") }))
- {
- ids.Add(item);
- }
- }
- if (ids.IsNotEmpty())
- {
- string bizcode = "scan-join";
- string sql = $"select c.id, c.name ,c.lang as code from c where c.id in ({string.Join(",", ids.Select(x => $"'{x}'"))})";
- List<IdNameCode> idNameCodes = new List<IdNameCode>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<IdNameCode>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idNameCodes.Add(item);
- }
- _coreAPIHttpService.PushNotify(idNameCodes, $"{bizcode}_school", Constant.NotifyType_IES5_Course,
- new Dictionary<string, object> { { "tmdid", userid }, { "tmdname", _name }, { "groupListName", data.stuList.name }, { "groupListId", data.stuList.id } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- return Ok(new { data.stuList, data.status });
- }
- else
- {
- return Ok(new { data.status });
- }
- }
- /// <summary>
- /// 获取名单的tags
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin,teacher,student")]
- [HttpPost("get-grouplist-tags")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistTags(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- var (id, _, _, school) = HttpContext.GetAuthTokenInfo();
- object scope = null;
- StringBuilder sql = new StringBuilder($"SELECT {SummarySql} ,A1.tag FROM c " +
- $" join A1 in c. members where A1.id='{id}' and A1.tag<>null ");
- HttpContext?.Items.TryGetValue("Scope", out scope);
- if (!string.IsNullOrEmpty(school) && $"{scope}".Equals(Constant.ScopeStudent))
- {
- sql.Append($" and A1.code='{school}'");
- }
- List<dynamic> groupLists = new List<dynamic>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school}") }))
- {
- groupLists.Add(item);
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
- GetItemQueryIterator<dynamic>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList") }))
- {
- groupLists.Add(item);
- }
- return Ok(new { groupLists });
- }
- /// <summary>
- /// 获取发布活动的名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-activity-grouplist")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetActivityGrouplist(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement tmdid);
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- if (!json.TryGetProperty("opt", out JsonElement opt)) { return BadRequest(); }
- json.TryGetProperty("periodId", out JsonElement periodId);
- long nowtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- List<GroupListGrp> groupLists = new List<GroupListGrp>();
- switch (true)
- {
- //我管理的
- case bool when $"{opt}".Equals("manage", StringComparison.OrdinalIgnoreCase):
- //包含,学校的行政班,教学班
- json.TryGetProperty("type", out JsonElement _type);
- List<string> types = null;
- if (_type.ValueKind.Equals(JsonValueKind.Array))
- {
- types = _type.ToObject<List<string>>();
- }
- else if (_type.ValueKind.Equals(JsonValueKind.String))
- {
- types = new List<string> { $"{_type}" };
- }
- if (types.IsEmpty() || types.Contains("class"))
- {
- StringBuilder classsql = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year,c.no FROM c where ( c.graduate = 0 or IS_DEFINED(c.graduate) = false )");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- classsql.Append($" and c.periodId='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: classsql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
- {
- int scount = 0;
- HashSet<string> groupNames = new HashSet<string>();
- string gpsql = $"SELECT distinct c.id, c.groupId,c.groupName FROM c where c.classId='{item.id}' ";
- await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
- {
- if (!string.IsNullOrWhiteSpace(gp.groupName))
- {
- groupNames.Add(gp.groupName);
- }
- scount += 1;
- }
- ///行政班(学生搜寻classId动态返回)class
- GroupListGrp group = new GroupListGrp
- {
- id = item.id,
- code = $"GroupList-{schoolId}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = $"{schoolId}",
- type = "class",
- year = item.year,
- expire=0,
- groupName = groupNames,
- scount= scount
- };
- groupLists.Add(group);
- }
- }
- if (types.IsEmpty() || types.Contains("teach"))
- {
- //教学班
- StringBuilder teachsql = new StringBuilder($" SELECT distinct value(c) FROM c where c.type='teach' and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- teachsql.Append($" and c.periodId='{periodId}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: teachsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (types.IsEmpty() || types.Contains("research"))
- {
- //教研组
- StringBuilder researchsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='research'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: researchsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- if (types.IsEmpty() || types.Contains("yxtrain"))
- {
- //研修名单
- StringBuilder yxtrainsql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<GroupList>(queryText: yxtrainsql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- return Ok(new { groupLists });
- case bool when $"{opt}".Equals("teach", StringComparison.OrdinalIgnoreCase):
- //我执教的
- //从学校的课程和个人课程搜寻与我相关的课程对应的名单。
- List<TeachCourse> teachCourses = new List<TeachCourse>();
- if (!string.IsNullOrEmpty($"{schoolId}"))
- {
- var schoolQuery = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- schoolQuery.Append($" and c.period.id='{periodId}' ");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").
- GetItemQueryIterator<TeachCourse>(queryText: schoolQuery.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolId}") }))
- {
- teachCourses.Add(item);
- }
- }
- var query = new StringBuilder($"select distinct c.name,c.id, c.scope,c.subject,c.period,A0 schedule from c join A0 in c.schedule where A0.teacherId = '{tmdid}'");
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").
- GetItemQueryIterator<TeachCourse>(queryText: query.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{tmdid}") }))
- {
- teachCourses.Add(item);
- }
- var classIds = teachCourses.Select(x => x.schedule).Where(y => !string.IsNullOrEmpty(y.classId)).Select(x => x.classId).Distinct().ToList();
- var schedule = teachCourses.Where(y => !string.IsNullOrEmpty(y.schedule.stulist)).Distinct().ToList();
- //var schedule = teachCourses.Select(x => new { schedule = x.schedule.Where(mm=>!string.IsNullOrEmpty(mm.stulist)), scope = x.scope }).ToList();
- if (classIds.IsNotEmpty())
- {
- string insql = string.Join(",", classIds.Select(x => $"'{x}'"));
- query = new StringBuilder($"SELECT c.id,c.name,c.periodId ,c.year FROM c where c.id in ({insql}) and ( c.graduate = 0 or IS_DEFINED(c.graduate) = false) ");
- ///行政班(学生搜寻classId动态返回)class
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ClassInfo>(queryText: query.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Class-{schoolId}") }))
- {
- HashSet<string> groupNames = new HashSet<string>();
- string gpsql = $"SELECT distinct c.groupId,c.groupName FROM c where c.classId='{item.id}'and c.groupName <>null";
- await foreach (var gp in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: gpsql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{schoolId}") }))
- {
- groupNames.Add(gp.groupName);
- }
- GroupListGrp group = new GroupListGrp
- {
- id = item.id,
- code = $"GroupList-{schoolId}",
- name = item.name,
- periodId = item.periodId,
- scope = "school",
- school = $"{schoolId}",
- type = "class",
- expire=0,
- year = item.year,
- groupName = groupNames
- };
- groupLists.Add(group);
- }
- }
- if (schedule.IsNotEmpty())
- {
- var privateList = schedule.Where(x => x.scope.Equals("private")).Select(x => x.schedule.stulist).Distinct();
- if (privateList.Count() > 0)
- {
- string insql = string.Join(",", privateList.Select(x => $"'{x}'"));
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql})",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- var schoolList = schedule.Where(x => x.scope.Equals("school")).Select(x => x.schedule.stulist).Distinct();
- if (schoolList.Count() > 0)
- {
- List<GroupListDto> groups = new List<GroupListDto>();
- string insql = string.Join(",", schoolList.Select(x => $"'{x}'"));
- //我教的学校教学班,如果有过期的教学班则不返回
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: $"select distinct {SummarySql} from c where c.id in ({insql}) and ( c.expire = 0 or IS_DEFINED(c.expire) = false or c.expire >={nowtime} ) ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{schoolId}") }))
- {
- HashSet<string> groupName = item.members.Where(x => !string.IsNullOrEmpty(x.groupName)).Select(y => y.groupName).ToHashSet();
- groupLists.Add(new GroupListGrp(item, groupName));
- }
- }
- }
- List<CourseGroupList> courseGroups = new List<CourseGroupList>();
- teachCourses.GroupBy(y => (y.id, y.name, y.scope, y.period.name, y.period.id, y.subject.name, y.subject.id)).ToList().ForEach(x =>
- {
- List<GroupListGrp> classIds = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.classId)).Select(b => b.schedule.classId).Contains(n.id)).ToList();
- List<GroupListGrp> stulists = groupLists.Where(n => x.Where(m => !string.IsNullOrEmpty(m.schedule.stulist)).Select(b => b.schedule.stulist).Contains(n.id)).ToList();
- if (classIds == null)
- {
- classIds = new List<GroupListGrp>();
- }
- if (stulists != null)
- {
- classIds.AddRange(stulists);
- }
- CourseGroupList groupList = new CourseGroupList()
- {
- scope = x.Key.Item3,
- subject = x.Key.Item6,
- subjectId = x.Key.Item7,
- period = x.Key.Item4,
- periodId = x.Key.Item5,
- id = x.Key.Item1,
- name = x.Key.Item2,
- groups = classIds
- };
- courseGroups.Add(groupList);
- });
- return Ok(new { groupLists = courseGroups });
- case bool when $"{opt}".Equals("private", StringComparison.OrdinalIgnoreCase):
- //我个人的
- break;
- default:
- break;
- }
- return Ok(new { error = 1, msg = "参数异常" });
- }
- /// <summary>
- /// 根据任意名单id获取成员信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-members-listids")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetMembersListids(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- json.TryGetProperty("groupNames", out JsonElement groupNames);
- List<Dictionary<string, List<string>>> groupLists = new List<Dictionary<string, List<string>>>();
- if (groupNames.ValueKind.Equals(JsonValueKind.Array))
- {
- groupLists = groupNames.ToObject<List<Dictionary<string, List<string>>>>();
- }
- List<(string pId, List<string> gid)> ps = new List<(string pId, List<string> gid)>();
- if (groupLists.Count > 0)
- {
- foreach (var gp in groupLists)
- {
- foreach (KeyValuePair<string, List<string>> pp in gp)
- {
- ps.Add((pp.Key, pp.Value));
- }
- }
- }
- List<string> listids = ids.ToObject<List<string>>();
- (List<RMember> members, List<RGroupList> groups) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, listids, $"{schoolId}", ps);
- return Ok(new { groups, members });
- }
- /// <summary>
- /// 根据任意名单id获取名单摘要信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-grouplist-listids")]
- #if !DEBUG
- [AuthToken(Roles = "teacher,admin,student")]
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetGroupListListids(JsonElement json)
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!json.TryGetProperty("ids", out JsonElement ids)) return BadRequest();
- json.TryGetProperty("schoolId", out JsonElement schoolId);
- List<string> listids = ids.ToObject<List<string>>();
- List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, listids, $"{schoolId}", SummarySql);
- return Ok(new { groups });
- }
- /// <summary>
- /// 获取名单和成员信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplists-members")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistsMembers(JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement _tmdid);
- json.TryGetProperty("schoolId", out JsonElement _schoolId);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
- json.TryGetProperty("periodId", out JsonElement periodId);
- json.TryGetProperty("no", out JsonElement no);
- StringBuilder sql = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='{type}'");
- List<RGroupList> groups = new List<RGroupList>();
- string tbname = "Teacher";
- string code = $"GroupList";
- if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- code = $"GroupList-{_schoolId}";
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- sql.Append($" and c.periodId='{periodId}'");
- }
- if (!string.IsNullOrEmpty($"{no}"))
- {
- sql.Append($" and c.no='{no}'");
- }
- }
- else
- {
- sql.Append($" and c.creatorId='{_tmdid}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<RGroupList>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- groups.Add(item);
- }
- (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{type}", groups, tbname, _dingDing, $"{_schoolId}");
- return Ok(new { groups = groupsData, members });
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists-members()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- return Ok();
- }
- /// <summary>
- /// 获取名单列表
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplists")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplists(JsonElement json)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("tmdid", out JsonElement _tmdid);
- json.TryGetProperty("schoolId", out JsonElement _schoolId);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("type", out JsonElement type)) return BadRequest();
- json.TryGetProperty("periodId", out JsonElement periodId);
- json.TryGetProperty("no", out JsonElement no);
- StringBuilder sql = new StringBuilder($"SELECT distinct {SummarySql} FROM c where c.type='{type}'");
- List<GroupListDto> groups = new List<GroupListDto>();
- string tbname = "Teacher";
- string code = $"GroupList";
- if ($"{scope}".Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- code = $"GroupList-{_schoolId}";
- if (!string.IsNullOrEmpty($"{periodId}"))
- {
- sql.Append($" and c.periodId='{periodId}'");
- }
- if (!string.IsNullOrEmpty($"{no}"))
- {
- sql.Append($" and c.no='{no}'");
- }
- }
- else
- {
- sql.Append($" and c.creatorId='{_tmdid}'");
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tbname).GetItemQueryIterator<GroupListDto>(queryText: sql.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(code) }))
- {
- groups.Add(item);
- }
- return Ok(new { groups });
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplists()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- return Ok();
- }
- /// <summary>
- /// 根据id,code获取学校行政班信息和学生信息。用于维护学生基本信息。
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("get-classstudents-idcode")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetClassStudentsIdcode(JsonElement json)
- {
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest();
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"Class-{_code}"));
- List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
- {
- item.salt = null;
- item.pw = null;
- students.Add(item);
- }
- return Ok(new { classInfo = clazz, students = students });
- }
- catch (Exception ex)
- {
- return Ok(new { error = 404, msg = "班级不存在!" });
- }
- }
- //处理通用名单
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("get-grouplist-idcode")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetGrouplistIdcode(JsonElement json)
- {
- RGroupList groupList = null;
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- json.TryGetProperty("type", out JsonElement _type);
- json.TryGetProperty("code", out JsonElement _code);
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
- string tbname = $"{scope}".Equals("private") ? "Teacher" : "School";
- string code = "";
- if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
- {
- if ($"{scope}".Equals("private"))
- {
- //私人名单
- code = "GroupList";
- }
- else
- {
- //学校自定义名单
- code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
- }
- groupList = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<RGroupList>($"{id}", new PartitionKey($"{code}"));
- }
- else if ($"{_type}".Equals("class"))
- {
- try
- {
- code = $"Class-{_code}";
- Class clazz = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<Class>($"{id}", new PartitionKey($"{code}"));
- if (clazz != null)
- {
- List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"select value(c) from c where c.classId = '{clazz.id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"Base-{_code}") }))
- {
- students.Add(item);
- }
- ///行政班(学生搜寻classId动态返回)class
- List<RMember> smembers = students.Where(x => x.classId.Equals(clazz.id)).Select(y => new RMember { id = y.id, code = $"{_code}", name = y.name, type = 2, picture = y.picture, no = y.no, classId = y.classId, groupId = y.groupId, groupName = y.groupName }).ToList();
- groupList = new RGroupList
- {
- id = clazz.id,
- code = $"GroupList-{clazz.school}",
- name = clazz.name,
- periodId = clazz.periodId,
- pk = "GroupList",
- year = clazz.year,
- expire = 0,
- school = clazz.school,
- scope = "school",
- type = "class",
- scount = smembers.Count,
- no = clazz.no,
- leader = clazz.teacher?.id,
- members = smembers,
- };
- }
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { groupList });
- }
- }
- (List<RGroupList> groupsData, List<RMember> members) = await GroupListService.GetGroupListMemberInfo(_coreAPIHttpService, client, $"{groupList.type}", new List<RGroupList> { groupList }, tbname, _dingDing, $"{_code}");
- groupList = groupsData.FirstOrDefault();
- }
- catch (CosmosException ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n {json}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { groupList });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/get-grouplist-idcode()\n{ex.Message}\n{ex.StackTrace}\n{json}", GroupNames.醍摩豆服務運維群組);
- }
- return Ok(new { groupList });
- }
- /// <summary>
- /// 保存或更新通用名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("upsert-grouplist")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> UpsertGroupList(JsonElement json)
- {
- GroupList list = json.ToObject<GroupList>();
- try
- {
- var (userid, _, _, school) = HttpContext.GetAuthTokenInfo();
- if (string.IsNullOrEmpty(list.type))
- {
- return BadRequest();
- }
- list.year = list.year > 0 ? list.year : DateTimeOffset.UtcNow.Year;
- list.ttl = -1;
- list.creatorId = userid;
- list.school = string.IsNullOrEmpty(list.school) ? school : list.school;
- list.pk = "GroupList";
- if (list.scope.Equals("private"))
- {
- //私人名单
- list.code = "GroupList";
- list.school = null;
- //只有开启审核,且设置天数大于零,且之前没有设置过期时间的时候才会重新设置过期时间。
- GroupList dblist = null;
- if (!string.IsNullOrWhiteSpace(list.id))
- {
- var response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(list.id, new PartitionKey(list.code));
- if (response.Status==200)
- {
- dblist = JsonDocument.Parse(response.Content).RootElement.ToObject<GroupList>();
- }
- }
- if (list.review==1)
- {
- if (list.qrcodeDays>0)
- {
-
- if (dblist!=null)
- {
- //更新过期时间
- if (dblist.qrcodeDays!=list.qrcodeDays)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
- }
- else
- {
- //相同
- if (dblist.review==0 && list.review==1)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, expiry: DateTimeOffset.FromUnixTimeMilliseconds(list.qrcodeExpire).UtcDateTime);
- }
- else
- {
- list.qrcodeExpire=dblist.qrcodeExpire;
- }
- }
- }
- else
- {
- if (list.qrcodeExpire<=0)
- {
- list.qrcodeExpire= DateTimeOffset.UtcNow.AddDays(list.qrcodeDays).ToUnixTimeMilliseconds();
- }
- }
- }
- else
- {
- return Ok(new { error = 400, msg = "必须设置二维码过期天数!" });
- }
- }
- else
- {
- if (dblist!=null && dblist.review==1) {
- list.qrcodeDays = 1;
- list.qrcodeExpire = 0;
- string key = $"GroupList:GroupWaitingList:{list.scope}:{list.id}";
- var datas = await _azureRedis.GetRedisClient(8).HashGetAllAsync(key);
- List<GroupWaitingList> groupWaitingLists = new List<GroupWaitingList>();
- foreach (var rcd in datas)
- {
- var value = rcd.Value.ToString().ToObject<GroupWaitingList>();
- if (value!=null) { groupWaitingLists.Add(value); }
- }
- if (groupWaitingLists.IsNotEmpty()) {
- var takeCount = list.limitCount-dblist.members.Count;
- if (takeCount>0)
- {
- var takes = groupWaitingLists.OrderBy(x => x.applyTime).Take(takeCount);
- if (takes!=null && takes.Count()>0)
- {
- foreach (var t in takes)
- {
- GroupListService.JoinList(list, t.userid, t.type, t.school, t.year);
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string sutFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=0;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
- }
- }
- //未自动加入的,直接拒绝
- var untakes = groupWaitingLists.Except(takes);
- if (untakes!=null && untakes.Count()>0)
- {
- foreach (var t in takes)
- {
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string sutFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=1;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
- }
- }
- }
- }
- }
- else
- {
- //已经加满,删除候选
- foreach (var t in groupWaitingLists)
- {
- string stuKey = !string.IsNullOrWhiteSpace(school) ? $"GroupList:StudentWaitinglist:{school}_{t.userid}" : $"GroupList:StudentWaitinglist:{t.userid}";
- string sutFiled = $"{list.scope}:{list.id}";
- var data = await _azureRedis.GetRedisClient(8).HashGetAsync(stuKey, sutFiled);
- if (data != default && !data.IsNullOrEmpty)
- {
- var value = data.ToString().ToObject<GroupWaitingList>();
- value.status=1;
- await _azureRedis.GetRedisClient(8).HashSetAsync(stuKey, sutFiled, value.ToJsonString());
- }
- }
- }
- }
- await _azureRedis.GetRedisClient(8).KeyDeleteAsync(key);
- }
- }
- }
- else
- {
- //学校自定义名单
- list.code = !list.code.StartsWith("GroupList-") ? $"GroupList-{list.code}" : list.code;
- }
- switch (true)
- {
- //普通学生名单(包含学校教学班名单,个人课程名单),其中学生成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("teach", StringComparison.OrdinalIgnoreCase):
- list.type = "teach";
- list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //教研组名单,只有加入学校的老师名单 成员账号类型是醍摩豆ID,保存在学校表,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("research", StringComparison.OrdinalIgnoreCase):
- list.type = "research";
- list.scope = "school";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //个人好友名单,成员账号类型可以是学校学生账号和醍摩豆ID,分区键为GroupList
- case bool when $"{list.type}".Equals("friend", StringComparison.OrdinalIgnoreCase):
- list.type = "friend";
- list.scope = "private";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //社交群组类型(包含学校交流群组,个人交流群组),成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("group", StringComparison.OrdinalIgnoreCase):
- list.type = "group";
- list = await GroupListService.CheckListNo(list, _azureCosmos, _dingDing, _option);
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- //研修类型成员账号类型可以是学校学生账号和醍摩豆ID,,分区键为GroupList-hbcn
- case bool when $"{list.type}".Equals("yxtrain", StringComparison.OrdinalIgnoreCase):
- list.type = "yxtrain";
- list.scope = "school";
- list = await GroupListService.UpsertList(list, _azureCosmos, _configuration, _serviceBus);
- break;
- default:
- return Ok(new { error = 400, msg = "参数错误!" });
- }
- return Ok(new { list });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/upsert-grouplist()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest();
- }
- }
- //删除名单
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("delete-grouplist")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> DeleteGroupList(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("code", out JsonElement code)) return BadRequest();
- if (!json.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
- if (!json.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- string tbname = "";
- string datacode = "";
- if (scope.ToString().Equals("school", StringComparison.OrdinalIgnoreCase))
- {
- tbname = "School";
- datacode = $"GroupList-{code}";
- }
- else
- {
- tbname = "Teacher";
- datacode = $"GroupList";
- }
- try
- {
- await GroupListService.DeleteGrouplistEvent($"{id}", datacode, tbname, client, _configuration, _serviceBus);
- }
- catch (Exception ex) { }
- return Ok(new { id });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},grouplist/delete-grouplist()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return Ok(new { error = 400 });
- }
- }
- /// <summary>
- /// 保存或更新通用名单
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin,student")]
- [HttpPost("upsert-group-member")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> UpsertGroupMember(JsonElement json)
- {
- if (!json.TryGetProperty("opt", out JsonElement _opt)) { return BadRequest(); }
- if (!json.TryGetProperty("scope", out JsonElement _scope)) { return BadRequest(); }
- if (!json.TryGetProperty("id", out JsonElement _id)) { return BadRequest(); }
- if (!json.TryGetProperty("code", out JsonElement _code)) { return BadRequest(); }
- if (!json.TryGetProperty("type", out JsonElement _type)) { return BadRequest(); }
- try
- {
- GroupList groupList = null;
- string tbname = $"{_scope}".Equals("private") ? "Teacher" : "School";
- string code = "";
- if (string.IsNullOrEmpty($"{_type}") || !$"{_type}".Equals("class"))
- {
- if ($"{_scope}".Equals("private"))
- {
- //私人名单
- code = "GroupList";
- }
- else
- {
- //学校自定义名单
- code = !code.StartsWith("GroupList-") ? $"GroupList-{_code}" : code;
- }
- groupList = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReadItemAsync<GroupList>($"{_id}", new PartitionKey($"{code}"));
- }
- switch (true)
- {
- case bool when $"{_opt}".Equals("up-nickname", StringComparison.OrdinalIgnoreCase) && json.TryGetProperty("members", out JsonElement _members):
- var members = _members.ToObject<List<Member>>();
- List<Member> updateSuccess = new List<Member>();
- List<Member> updateFailed = new List<Member>();
- members.ForEach(x =>
- {
- var member = groupList.members.Find(z => z.type == x.type && z.id.Equals(x.id));
- if (member != null)
- {
- member.nickname = x.nickname;
- updateSuccess.Add(member);
- }
- else
- {
- updateFailed.Add(x);
- }
- });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, tbname).ReplaceItemAsync<GroupList>(groupList, $"{_id}", new PartitionKey(code));
- return Ok(new { updateSuccess, updateFailed });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location},更新名单成员信息异常{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- return Ok();
- }
- /// <
- /// summary>
- /// 处理名单审核
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "teacher,admin")]
- [HttpPost("review")]
- #if DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> review(JsonElement request)
- {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
-
- var client = _azureCosmos.GetCosmosClient();
- switch (true)
- {
- //待加入列表
- case bool when $"{grant_type}".Equals("waitlist", StringComparison.OrdinalIgnoreCase):
- break;
- //处理审核
- case bool when $"{grant_type}".Equals("process", StringComparison.OrdinalIgnoreCase):
- await _azureRedis.GetRedisClient(8).KeyExpireTimeAsync("");
- break;
- //审核结果,学生端获取到被拒绝的,或者过期的自动删除,未被审核的保存
- case bool when $"{grant_type}".Equals("result", StringComparison.OrdinalIgnoreCase):
- break;
- }
- return Ok();
- }
- }
- }
|