12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451 |
- using Microsoft.Azure.Cosmos;
- using Azure.Storage.Blobs.Models;
- using Azure.Storage.Sas;
-
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using StackExchange.Redis;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Configuration;
- using System.Dynamic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Reflection;
- using System.Security.Policy;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Controllers.Analysis;
- using TEAMModelOS.Controllers.Both;
- 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.Cosmos;
- using TEAMModelOS.SDK.Models.Cosmos.Student;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Services;
- using TEAMModelOS.Services;
- using static TEAMModelOS.SDK.Services.BlobService;
- using Period = TEAMModelOS.SDK.Models.Period;
- namespace TEAMModelOS.Controllers
- {
- /// <summary>
- ///
- ///
- /*
- AClassONE
- ee6a461a-3b40-4f70-8842-cf275d1e15ee
- px-njcS.jL1P7g0-kW:EAkO2Ve7[9k1x
- 8124850f-03d8-4949-9355-ed0d0709189e
- l2aR-bk2LfCGt7OjSwRi:qZqfXXhL4:=
- */
- /// </summary>
- [Route("aclassone")]
- [ApiController]
- public class AClassONEController : ControllerBase
- {
- private readonly IHttpClientFactory _httpClient;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly SnowflakeId _snowflakeId;
- private readonly IConfiguration _configuration;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly HttpTrigger _httpTrigger;
- private readonly IPSearcher _searcher;
- public AClassONEController(
- AzureStorageFactory azureStorage,
- AzureRedisFactory azureRedis,
- AzureCosmosFactory azureCosmos,
- DingDing dingDing,
- SnowflakeId snowflakeId,
- IOptionsSnapshot<Option> option, IHttpClientFactory httpClient, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, IPSearcher searcher, HttpTrigger httpTrigger)
- {
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _azureCosmos = azureCosmos;
- _dingDing = dingDing;
- _snowflakeId = snowflakeId;
- _option = option?.Value;
- _httpClient = httpClient;
- _configuration = configuration;
- _coreAPIHttpService=coreAPIHttpService;
- _searcher=searcher;
- _httpTrigger=httpTrigger;
- }
- /// <summary>
- /// js_code获取小程序用户信息
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-miniapp-userinfo")]
- //[Authorize(Roles = "AClassONE")]
- public async Task<IActionResult> GetMiniAPPOpenid(JsonElement json)
- {
- // string Content = await responseMessage.Content.ReadAsStringAsync();
- try {
- var location = _option.Location;
- var clientID = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:AClassONE:clientSecret");
- var wxappid = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:appid");
- var wxsecret = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:secret");
- if (location.Contains("China"))
- {
- location = "China";
- }
- else if (location.Contains("Global"))
- {
- location = "Global";
- }
- var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
- //return Ok(new { token = new { token.TokenType,token.AccessToken } });
- if (!json.TryGetProperty("js_code", out JsonElement js_code)) return BadRequest("js_code is null");
- string url = $"https://api.weixin.qq.com/sns/jscode2session?appid={wxappid}&secret={wxsecret}&js_code={js_code}&grant_type=authorization_code";
- HttpResponseMessage responseMessage = await _httpClient.CreateClient().GetAsync(url);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- JsonDocument document = JsonDocument.Parse(responseMessage.Content.ReadAsStream());
- return Ok(new { miniappData = document, token = new { token.TokenType, token.AccessToken } });
- }
- else
- {
- string Content = await responseMessage.Content?.ReadAsStringAsync();
- await _dingDing.SendBotMsg($"get-miniapp-userinfo:{Content}", GroupNames.成都开发測試群組);
- return BadRequest(Content);
- }
- }
- catch(Exception ex) {
- await _dingDing.SendBotMsg($"get-miniapp-userinfo:{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 获取教师信息
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacher-info")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> GetTeacherInfo(JsonElement json)
- {
- try {
- string head_lang = "";
- if (HttpContext.Request.Headers.TryGetValue("lang", out var _lang))
- {
- head_lang = $"{_lang}";
- }
- int timezone = 8;
- if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone,out int tz))
- {
- timezone=tz;
- }
- if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest("code is null");
- var phoneInfo = await GetWeChatPhoneNumber(_code.ToString());
- //phoneInfo.code=200;
- if (phoneInfo.code==200)
- {
- string _mobile = phoneInfo.phone.phoneNumber;
- //string _mobile = "18281911681";
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{_mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- (string ip, string region) = await LoginService.LoginIp(HttpContext, _searcher);
- Teacher teacher = null;
- TeacherInfo teacherInfo = await TeacherService.TeacherInfo(_azureCosmos, teacher, $"{coreUser.name}", $"{coreUser.picture}", coreUser.id, _azureStorage, _option, _azureRedis, ip, _httpTrigger, $"{_lang}",timezone);
- return Ok(new
- {
- teacherInfo.auth_token,
- teacherInfo.blob_uri,
- teacherInfo.blob_sas,
- teacherInfo.schools,
- teacherInfo.defaultschool,
- });
- }
- else return Ok(new { state = 404, msg = "未找到关联账号" });
- }
- } catch (Exception ex) { }
- return Ok();
- }
- /// <summary>
- /// 获取学校信息
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-school-info")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE,IES")]
- #endif
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> GetSchoolInfo(JsonElement json) {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- if (!json.TryGetProperty("school_code", out JsonElement _school_code)) return BadRequest();
- string school_code = $"{_school_code}";
- List<string> roles = new List<string>();
- List<string> permissions = new List<string>();
- var client = _azureCosmos.GetCosmosClient();
- int size = 0;
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(tmdid, new PartitionKey("Base"));
- List<AreaDto> areas = new List<AreaDto>();
- HashSet<string> areaIds = new HashSet<string>();
- if (teacher.areas.IsNotEmpty())
- {
- teacher.areas.ForEach(x => {
- areaIds.Add(x.areaId);
- });
- }
- if (teacher.schools.IsNotEmpty())
- {
- teacher.schools.ForEach(x => {
- if (!string.IsNullOrEmpty(x.areaId))
- {
- areaIds.Add(x.areaId);
- }
- });
- }
- List<Area> areasDbs = new List<Area>();
- List<AreaSetting> areaSettings = new List<AreaSetting>();
- if (areaIds.Count > 0)
- {
- string queryText = $"select value(c) from c where c.id in ({string.Join(",", areaIds.Select(x => $"'{x}'"))})";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIteratorSql<Area>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
- {
- areasDbs.Add(item);
- }
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIteratorSql<AreaSetting>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("AreaSetting") }))
- {
- areaSettings.Add(item);
- }
- }
- if (teacher.areas.IsNotEmpty())
- {
- foreach (var areat in teacher.areas)
- {
- Area area = areasDbs.Find(x => x.id.Equals(areat.areaId));
- AreaSetting setting = null;
- if (area != null)
- {
- setting = areaSettings.Find(x => x.id.Equals(areat.areaId));
- }
- int access = 0;
- if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
- {
- access = 1;
- }
- //if (setting != null)
- //{
- // setting.accessConfig = null;
- //}
- if (!string.IsNullOrWhiteSpace(area?.id)) {
- var containerArea = _azureStorage.GetBlobContainerClient(area?.id);
- await containerArea.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建Teacher私有容器,如存在則不做任何事,保障容器一定存在
- var blobArea = _azureStorage.GetBlobContainerSAS(area?.id, blobContainerSasPermissions: BlobContainerSasPermissions.All);
- areas.Add(new AreaDto { sas= blobArea.sas, url= blobArea.uri, shortCode=area?.shortCode, areaId = area?.id, name = area?.name, standard = area?.standard, standardName = area?.standardName, setting = setting, access = access });
- }
- }
- }
- if (school_code.Equals(teacher.defaultSchool) && teacher.schools.IsNotEmpty() && !teacher.schools.Select(x => x.schoolId).Contains(school_code))
- {
- school_code = teacher.schools[0].schoolId;
- teacher.defaultSchool = school_code;
- teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, tmdid, new PartitionKey("Base"));
- }
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(tmdid, new PartitionKey($"Teacher-{school_code}"));
- string defaultPeriodId = "";
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var jsonData = await JsonDocument.ParseAsync(response.Content);
- if (jsonData.RootElement.TryGetProperty("size", out JsonElement _size) && _size.ValueKind == JsonValueKind.Number)
- {
- size = _size.GetInt32();
- }
- if (jsonData.RootElement.TryGetProperty("periodId", out JsonElement _periodId))
- {
- defaultPeriodId =$"{_periodId}";
- }
- if (jsonData.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _roles.EnumerateArray())
- {
- roles.Add(obj.GetString());
- }
- }
- if (jsonData.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _permissions.EnumerateArray())
- {
- permissions.Add(obj.GetString());
- }
- }
- var scteacher = jsonData.RootElement.ToObject<SchoolTeacher>();
- if (!$"{teacher.name}".Equals($"{scteacher?.name}") || !$"{teacher.picture}".Equals($"{scteacher?.picture}"))
- {
- scteacher.name=teacher.name;
- scteacher.picture=teacher.picture;
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(scteacher, scteacher.id, new PartitionKey(scteacher.code));
- }
- }
- if (roles.Count == 0)
- {
- //助理,管家
- //roles.Add("assist");
- roles.Add("teacher");
- }
- School school_base = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{school_code}", new PartitionKey("Base"));
- string currAreaId = "";
- dynamic currArea = new ExpandoObject();
- if (!string.IsNullOrEmpty(school_base.areaId))
- {
- try
- {
- Area area = areasDbs.Find(x => x.id.Equals(school_base.areaId));
- AreaSetting setting = null;
- if (area != null)
- {
- //setting =await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(school_base.areaId, new PartitionKey("AreaSetting"));
- setting = areaSettings.Find(x => x.id.Equals(school_base.areaId));
- }
- int access = 0;
- AccessConfig accessConfig = null;
- if (setting != null && !string.IsNullOrWhiteSpace(setting.accessConfig))
- {
- access = 1;
- accessConfig = setting.accessConfig.ToObject<AccessConfig>();
- }
- //if (setting!=null&& !string.IsNullOrEmpty(setting.accessConfig)) {
- // setting.accessConfig = null;
- //}
- currArea = new
- {
- shortCode = area?.shortCode,
- areaId = area?.id,
- name = area?.name,
- standard = area?.standard,
- standardName = area?.standardName,
- setting = setting,
- access = access,
- //submitType=accessConfig?.submitType,
- homeworkType = accessConfig != null && accessConfig.homeworkType.IsNotEmpty() ? accessConfig.homeworkType : new List<string> { "pdf" },
- };
- currAreaId = area?.id;
- }
- catch (CosmosException)
- {
- //数据库捞不到数据
- }
- }
- if (areas.Count > 0)
- {
- roles.Add("area");
- }
- areas.ForEach(x => { { if (x.setting != null) { x.setting.accessConfig = x.setting.accessConfig; } } });
- int timezone = 8;
- if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone, out int tz))
- {
- timezone=tz;
- }
- if (!string.IsNullOrWhiteSpace(school_base.timeZone?.value))
- {
- string timeZoneOffsetString = school_base.timeZone.value;
- bool plus = true;
- if (timeZoneOffsetString.Contains("-"))
- {
- plus=false;
- }
-
- // 去除时区偏移字符串中的正负号
- timeZoneOffsetString = timeZoneOffsetString.Replace("+", "").Replace("-", "");
- // 尝试解析格式化后的时区偏移字符串
- if (TimeSpan.TryParse(timeZoneOffsetString, out TimeSpan timeZoneOffset))
- {
- // 将时区偏移转换为小时数
- timezone = plus ? (int)timeZoneOffset.TotalHours : -(int)timeZoneOffset.TotalHours;
- }
- }
- var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName,teacher. id, teacher.name, teacher.picture, _option.JwtSecretKey, Website: "IES", timezone: timezone, scope: Constant.ScopeTeacher, schoolID: school_code.ToString(), areaId: currAreaId, standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), expire: 1);
- string school_code_blob = school_code.ToLower();
- var container = _azureStorage.GetBlobContainerClient(school_code_blob);
- await container.CreateIfNotExistsAsync(PublicAccessType.None); //嘗試創建School容器,如存在則不做任何事,保障容器一定存在
- var (blob_uri, blob_sas) = (roles.Contains("admin") || permissions.Contains("schoolAc-upd")) ? _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS(school_code_blob, BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Write);
- return Ok(new {
- auth_token,
- blob_uri,
- blob_sas,
- school_base,
- areas,
- currArea,
- });
- }
- /// <summary>
- /// 获取教师的教学信息
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teach-info")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE,IES")]
- #endif
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> GetTeachInfo(JsonElement json) {
- (string tmdid, _, _, string school) = HttpContext.GetAuthTokenInfo();
- List<KeyValuePair<string, CourseTask>> schoolTeacherTask = new List<KeyValuePair<string, CourseTask>>();
- List<KeyValuePair<string, CourseTask>> schoolAssistantTask = new List<KeyValuePair<string, CourseTask>>();
- List<KeyValuePair<string, CourseTask>> privateTeacherTask = new List<KeyValuePair<string, CourseTask>>();
- List<KeyValuePair<string, CourseTask>> privateAssistantTask = new List<KeyValuePair<string, CourseTask>>();
- List<CourseDto> schoolCourses = new List<CourseDto>();
- List<CourseDto> teahcerCourses = new List<CourseDto>();
- List<string> groupIds = new List<string>();
- HashSet<string> hashGroupIds = new HashSet<string>();
- List<Class> classes = new List<Class>();
- Period periodSchool = null;
- //所有行政版
- List<GroupListDto> allClasses = new List<GroupListDto>();
- if (!string.IsNullOrWhiteSpace(school))
- {
- JsonElement year = default, semesterId = default, _periodId = default;
- School schoolBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- if (!json.TryGetProperty("periodId", out _periodId)) return BadRequest();
- var period = schoolBase.period.Find(x => x.id.Equals($"{_periodId}"));
- allClasses= await GroupListService.GetGroupListByType(_azureCosmos.GetCosmosClient(), "class", schoolBase, period, 0);
- //班主任
- string sqlClassTeacher = $"select value c from c where c.teacher.id='{tmdid}' and c.periodId='{_periodId}'";
- var resultClass = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<Class>(sqlClassTeacher, $"Class-{school}");
- if (resultClass.list.IsNotEmpty())
- {
- classes.AddRange(resultClass.list);
- hashGroupIds = new HashSet<string>(resultClass.list.Select(z=>z.id));
- }
- //执教
- //协同
- //管理员
- string sql = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
-
-
-
- int _year = -1;
- string _semesterId=string.Empty;
-
- if (json.TryGetProperty("year", out year))
- {
- _year= int.Parse($"{_year}");
- }
- if (json.TryGetProperty("semesterId", out semesterId))
- {
- _semesterId=$"{semesterId}";
- }
-
-
- periodSchool=period;
- if (_year==-1 || string.IsNullOrWhiteSpace(_semesterId))
- {
- var semesterInfo = SchoolService.GetSemester(period, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
- if (_year==-1) {
- _year=semesterInfo.studyYear;
- }
- if (string.IsNullOrWhiteSpace(_semesterId)) {
- _semesterId=semesterInfo.currSemester.id;
- }
- }
-
- //string date = SchoolService.GetOpensByStudyYearAndSemester(period.semesters, int.Parse($"{_year}"), $"{_semesterId}");
- sql = $"{sql} and c.year={_year} and c.semesterId='{_semesterId}'";
- HashSet<string> courseIds = new HashSet<string>();
- var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseTask>(sql, $"CourseTask-{school}");
- if (resultSchool.list.IsNotEmpty())
- {
- resultSchool.list.ForEach(x => {
- var schedulesTeacher = x.schedules.Where(z => !string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
- if (schedulesTeacher.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesTeacher.ToList();
- schoolTeacherTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- //groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- var gpids= schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId);
- if (gpids!=null && gpids.Count()>0)
- {
- foreach (var gp in gpids) {
- hashGroupIds.Add(gp);
- }
- }
- }
- var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid));
- if (schedulesAssistant.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesAssistant.ToList();
- schoolAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- //groupIds.AddRange(schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- var gpids = schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId);
- if (gpids!=null && gpids.Count()>0)
- {
- foreach (var gp in gpids)
- {
- hashGroupIds.Add(gp);
- }
- }
- }
- });
- }
- if (courseIds.Any())
- {
- string sqlCourse = $"select value c from c where c.id in ({string.Join(",", courseIds.Select(b => $"'{b}'"))})";
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourse, $"CourseBase-{school}");
- if (result.list.IsNotEmpty())
- {
- foreach (var item in result.list)
- {
- List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
- var teacher = schoolTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
- if (teacher.Any())
- {
- courseTaskDtos.AddRange(teacher.ToList());
- }
- var assistant = schoolAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
- if (assistant.Any())
- {
- courseTaskDtos.AddRange(assistant.ToList());
- }
- schoolCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
- }
- }
- }
- }
- //个人
- {
- HashSet<string> courseIds = new HashSet<string>();
- string sqlCoursePrivate = $"select value c.id from c where c.creatorId='{tmdid}'";
- var resultCourseBasePrivate = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<string>(sqlCoursePrivate, $"CourseBase");
- if (resultCourseBasePrivate.list.IsNotEmpty())
- {
- courseIds=new HashSet<string>(resultCourseBasePrivate.list);
- }
- string sqlprivate = $"SELECT distinct value c FROM c join b in c.schedules where c.pk='CourseTask' and (ARRAY_CONTAINS(b.assistants,'{tmdid}')or b.teacherId ='{tmdid}' )";
- var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseTask>(sqlprivate, $"CourseTask");
- if (resultTeacher.list.IsNotEmpty())
- {
- resultTeacher.list.ForEach(x => {
- var schedulesTeacher = x.schedules.Where(z => !string.IsNullOrWhiteSpace(z.teacherId) && z.teacherId.Equals(tmdid));
- if (schedulesTeacher.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesTeacher.ToList();
- privateTeacherTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- groupIds.AddRange(schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- var gpids = schedulesTeacher.Where(z => !string.IsNullOrWhiteSpace(z.groupId));
- if (gpids!=null && gpids.Count()>0)
- {
- foreach (var gp in gpids)
- {
- if (!string.IsNullOrWhiteSpace(gp.school))
- {
- if (!string.IsNullOrWhiteSpace(school) && gp.school.Equals(school))
- {
- hashGroupIds.Add(gp.groupId);
- }
- }
- else {
- hashGroupIds.Add(gp.groupId);
- }
-
- }
- }
- }
- var schedulesAssistant = x.schedules.Where(z => z.assistants.Contains(tmdid));
- if (schedulesAssistant.Any())
- {
- courseIds.Add(x.courseId);
- CourseTask courseTask = x.ToJsonString().ToObject<CourseTask>();
- courseTask.schedules=schedulesAssistant.ToList();
- privateAssistantTask.Add(new KeyValuePair<string, CourseTask>(x.courseId, courseTask));
- groupIds.AddRange(schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId)).Select(x => x.groupId));
- var gpids = schedulesAssistant.Where(z => !string.IsNullOrWhiteSpace(z.groupId));
- if (gpids!=null && gpids.Count()>0)
- {
- foreach (var gp in gpids)
- {
- if (!string.IsNullOrWhiteSpace(gp.school))
- {
- if (!string.IsNullOrWhiteSpace(school) && gp.school.Equals(school)) {
- hashGroupIds.Add(gp.groupId);
- }
- }
- else
- {
- hashGroupIds.Add(gp.groupId);
- }
- }
- }
- }
- });
- }
- if (courseIds.Any())
- {
- string sqlCourse = $"select distinct value c from c where c.code='CourseBase' and ( c.creatorId='{tmdid}' or c.id in ({string.Join(",", courseIds.Select(b => $"'{b}'"))}))";
- var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetList<CourseBase>(sqlCourse, $"CourseBase");
- if (result.list.IsNotEmpty())
- {
- foreach (var item in result.list)
- {
- List<CourseTaskDto> courseTaskDtos = new List<CourseTaskDto>();
- var teacher = privateTeacherTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="teacher" });
- if (teacher.Any())
- {
- courseTaskDtos.AddRange(teacher.ToList());
- }
- var assistant = privateAssistantTask.Where(x => x.Key.Equals(item.id)).Select(z => new CourseTaskDto { courseTask=z.Value, type="assistant" });
- if (assistant.Any())
- {
- courseTaskDtos.AddRange(assistant.ToList());
- }
- teahcerCourses.Add(new CourseDto { courseBase=item, courseTasks=courseTaskDtos });
- }
- }
- }
- }
- var groupInfo = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, hashGroupIds.ToList(), school);
- var groupIdsRel = groupIds.GroupBy(z => z).Select(z => new { groupId = z.Key, count = z.ToList().Count() });
- List<TeacherRoleGrouplist> groupLists= new List<TeacherRoleGrouplist>();
- foreach (var item in teahcerCourses)
- {
-
- foreach (var z in item.courseTasks) {
- var groups = z.courseTask.schedules.Select(z => z.groupId);
- if (groups!=null) {
- var groupList = groupInfo.groups.Where(z => groups.Contains(z.id));
- if (groupList!=null)
- {
- foreach (var gp in groupList) {
- string subjectId = null;
- string subjectName = null;
- string subjectBindId = null;
- TeacherRoleGrouplist roleGrouplist = groupLists.Find(f => f.scope.Equals("private") && f.groupList.id.Equals(gp.id));
- if (roleGrouplist!=null)
- {
- if (roleGrouplist.roles.Contains(z.type)) {
- roleGrouplist.roles.Add(z.type);
- }
- }
- else {
- groupLists.Add(new TeacherRoleGrouplist { roles = new HashSet<string>() { z.type }, scope= "private", groupList= gp, subjectId= subjectId, subjectName=subjectName, subjectBindId= subjectBindId });
- }
- }
- }
- }
- }
- }
- foreach (var item in schoolCourses)
- {
- string subjectBindId = null;
- if (!string.IsNullOrWhiteSpace(school) && periodSchool!=null && item.courseBase.scope.Equals("school") && !string.IsNullOrWhiteSpace(item.courseBase?.subject?.id))
- {
- subjectBindId=periodSchool.subjects.Find(z => z.id.Equals(item.courseBase.subject.id))?.bindId;
- }
- foreach (var z in item.courseTasks)
- {
- var groups = z.courseTask.schedules.Select(z => z.groupId);
- if (groups!=null)
- {
- var groupList = groupInfo.groups.Where(z => groups.Contains(z.id));
- if (groupList!=null)
- {
- foreach (var gp in groupList)
- {
- TeacherRoleGrouplist roleGrouplist = groupLists.Find(f => f.scope.Equals("school") && f.groupList.id.Equals(gp.id));
- if (roleGrouplist!=null)
- {
- if (roleGrouplist.roles.Contains(z.type))
- {
- roleGrouplist.roles.Add(z.type);
- }
- }
- else
- {
- groupLists.Add(new TeacherRoleGrouplist { roles = new HashSet<string>() { z.type }, scope = "school", groupList = gp, subjectId = item.courseBase?.subject?.id, subjectName = item.courseBase?.subject?.name, subjectBindId= subjectBindId });
- }
- }
- }
- }
- }
- }
- foreach (var item in classes) {
- var groupList = groupInfo.groups.Where(z => item.id.Equals(z.id));
- if (groupList!=null)
- {
- foreach (var gp in groupList)
- {
- TeacherRoleGrouplist roleGrouplist = groupLists.Find(f => f.scope.Equals("school") && f.groupList.id.Equals(gp.id));
- if (roleGrouplist!=null)
- {
- if (!roleGrouplist.roles.Contains("charge"))
- {
- roleGrouplist.roles.Add("charge");
- }
- }
- else
- {
- groupLists.Add(new TeacherRoleGrouplist { roles = new HashSet<string>() { "charge" }, scope = "school", groupList = gp, });
- }
- }
- }
- }
- //暂时先注释不需要的
- return Ok(new {/* teahcerCourses, schoolCourses, groupIdsRel, */groupLists, allClasses });
- }
-
- /// <summary>
- /// 根据家长手机号获取监护学生的信息
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-children-by-mobile")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> GetChildrenByPhone(JsonElement json)
- {
- try
- {
- if (!json.TryGetProperty("code", out JsonElement _code)) return BadRequest("code is null");
- var phoneInfo= await GetWeChatPhoneNumber(_code.ToString());
- if (phoneInfo.code==200)
- {
- string _mobile = phoneInfo.phone.phoneNumber;
-
- string sql = $"select value c from c where c.mobile='{_mobile}'";
- List<Guardian> guardians = new List<Guardian>();
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<Guardian>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base-Guardian") }))
- {
- guardians.Add(item);
- }
- //没有找到监护人信息时,尝试跨分区搜索,但是不建议。
- if (!guardians.IsNotEmpty())
- {
- List<Student> students = new List<Student>();
- string stuSql = $"select distinct value c from c join g in c.guardians where g.mobile='{_mobile}'";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<Student>(queryText: stuSql, requestOptions: new QueryRequestOptions { }))
- {
- students.Add(item);
- }
- if (students.Any())
- {
- string guardianName = "";
- string mobile = $"{_mobile}";
- List<GuardianStudent> guardianStudents = new List<GuardianStudent>();
- students.ForEach(x =>
- {
- var studentGuardian = x.guardians.Find(x => !string.IsNullOrWhiteSpace(x.mobile) && x.mobile.Equals(mobile));
- if (studentGuardian != null)
- {
- guardianName = studentGuardian.name;
- guardianStudents.Add(new GuardianStudent {relation=studentGuardian.relation, type = 2, id = x.id, code = x.schoolId, name = x.name, picture = x.picture });
- }
- });
- if (guardians.Any())
- {
- guardians.First().students.AddRange(guardianStudents);
- }
- else
- {
- Guardian guardian = new Guardian() { id = Guid.NewGuid().ToString(), name = guardianName, mobile = mobile, students = guardianStudents, code = "Base-Guardian", pk = "Guardian" };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemAsync(guardian, new PartitionKey("Base-Guardian"));
- guardians.Add(guardian);
- }
- }
- }
- if (guardians.Any())
- {
- var students = guardians.SelectMany(x => x.students).DistinctBy(x => $"{x.type}-{x.id}{x.code}");
- var first = guardians.First();
- first.students = students.ToList();
- if (guardians.Count > 1)
- {
- //合并,并移除多余的绑定的手机号。
- guardians.Remove(first);
- if (guardians.Any() && !guardians.Select(x => x.id).Contains(first.id))
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).DeleteItemsStreamAsync(guardians.Select(x => x.id).ToList(), "Base-Guardian");
- }
- }
- first.nickname =first.name;
- first.picture = first.picture;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReplaceItemAsync(first, first.id, new PartitionKey(first.code));
- var schoolcodes = first.students.Where(s => !string.IsNullOrWhiteSpace(s.code)).Select(x => x.code);
- List<School> idSchools = new List<School>();
- if (schoolcodes.Any())
- {
- string sqlschool = $"select c.id,c.name,c.picture,c.period from c where c.id in ({string.Join(",", schoolcodes.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
- GetItemQueryIteratorSql<School>(queryText: sqlschool, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- idSchools.Add(item);
- }
- }
- var stus = first.students.GroupBy(x => x.code).Select(x => new { x.Key, list = x.ToList() });
- List<Student> studentes = new List<Student>();
- List<Class> classes = new List<Class>();
- foreach (var stu in stus)
- {
- HashSet<string> classIds = new HashSet<string>();
- string sqlStudent = $"select c.name ,c.periodId ,c.id ,c.schoolId, c.picture, c.classId, c.gender, c.year,c.guardians from c where c.id in ({string.Join(",", stu.list.Select(s => $"'{s.id}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<Student>(queryText: sqlStudent, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base-{stu.Key}") }))
- {
- studentes.Add(item);
- classIds.Add(item.classId);
- }
- string sqlClassIds = $" select c.name ,c.periodId ,c.id ,c.school, c.teacher,c.year from c where c.id in ({string.Join(",", classIds.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
- GetItemQueryIteratorSql<Class>(queryText: sqlClassIds, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Class-{stu.Key}") }))
- {
- classes.Add(item);
- }
- }
- List<dynamic> stuData = new List<dynamic>();
- List<GuardianStudent> guardianStudents= new List<GuardianStudent>();
- foreach (var x in first.students)
- {
- var stu = studentes.Find(s => s.id.Equals(x.id) && s.schoolId.Equals(x.code));
- if (stu== null) {
- guardianStudents.Add(x);
- continue;
- }
- var school = idSchools.Find(s => s.id.Equals(x.code));
- string periodName = "";
- if (school != null && stu != null && !string.IsNullOrWhiteSpace(stu.periodId))
- {
- var period = school.period.Find(p => p != null && p.id.Equals(stu.periodId));
- periodName = period?.name;
- }
- string className = "";
- string teacherTmdid = "";
- string teacherName = "";
- int? classYear = 0;
- if (stu != null && !string.IsNullOrWhiteSpace(stu.classId))
- {
- var clazz = classes.Find(p => p != null && p.id.Equals(stu.classId));
- className = clazz?.name;
- teacherTmdid = clazz?.teacher?.id;
- teacherName = clazz?.teacher?.name;
- classYear = clazz?.year;
- }
- if (string.IsNullOrWhiteSpace(x.relation)) {
- try {
- Student student = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemAsync<Student>(x.id, new PartitionKey($"Base-{x.code}"));
- var guardian = student.guardians.FindAll(x => x.mobile.Equals(_mobile));
- if (guardian.IsNotEmpty()) {
- x.relation= guardian.First().relation;
- if (!string.IsNullOrWhiteSpace(x.relation)) {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync<Guardian>(first, new PartitionKey(first.code));
- }
- }
- } catch { }
- }
- stuData.Add(new
- {
- x.id,
- schoolId = x.code,
- stu.name,
- stu.periodId,
- stu.picture,
- stu.classId,
- stu.gender,
- x.type,
- x.relation,
- stuYear = stu.year,
- schoolName = school.name,
- schoolPicture = school.picture,
- periodName,
- className,
- teacherTmdid,
- teacherName,
- classYear
- });
- }
- if (guardianStudents.IsNotEmpty()) {
- first.students.RemoveAll(z => guardianStudents.Contains(z));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync<Guardian>(first, new PartitionKey(first.code));
- }
- return Ok(new { code =200,guardian = new { first.id, first.name, first.picture, first.nickname, first.mobile, students = stuData } });
- }
- else
- {
- return Ok(new { code = 1, msg = "暂未找到学生信息", mobile = _mobile });
- }
- }
- else
- {
- return BadRequest("手机授权码过期!");
- }
- }
- catch (Exception ex)
- {
- return BadRequest("500错误");
- }
- }
- /// <summary>
- /// 获取当前学生参与的活动列表
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-children-activity")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> getActivity(JsonElement request) {
- try {
- if (!request.TryGetProperty("studentId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("classId", out JsonElement classId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();//学校编码
- var client = _azureCosmos.GetCosmosClient();
- StringBuilder stringBuilder = new($"select value(c) from c where (c.status<>404 or IS_DEFINED(c.status) = false )");
- string continuationToken = string.Empty;
- string token = default;
- if (!string.IsNullOrWhiteSpace($"{classId}"))
- {
- stringBuilder.Append($" and array_contains(c.classes,'{classId}')");
- }
- stringBuilder.Append("order by c.createTime desc");
- //是否需要进行分页查询,默认不分页
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- };
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- List<ArtEvaluation> arts = new();
- var result= await client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ArtEvaluation>(stringBuilder.ToString(), $"Art-{code}", token, 5);
- if (result.list.IsNotEmpty()) {
- arts = result.list;
- token = result.continuationToken;
- }
- List<string> artIds = new();
- artIds = arts.Select(c => c.id).ToList();
- List<ArtAttachment> artAttachments = new();
- List<StudentArtResult> studentArtResults = new();
- if (artIds.Count > 0) {
- string sqlTask = $"select value(c) from c where c.studentId = '{stuId}' and c.artId in ({string.Join(",", artIds.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<ArtAttachment>(queryText: sqlTask, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtAttachment-{code}") }))
- {
- artAttachments.Add(item);
- }
-
- foreach (var art in arts)
- {
- StudentArtResult artResult = new();
- string stu = string.Format("{0}{1}{2}", code.GetString(), "-", stuId.GetString());
- var res = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(stu.ToString(), new PartitionKey($"ArtResult-{art.id}"));
- if (res.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(res.Content);
- artResult = json.ToObject<StudentArtResult>();
- studentArtResults.Add(artResult);
- }
- }
- }
- var quotStus = studentArtResults.Select(c => new {
- c.artId,
- quotas = c.results.GroupBy(z => (z.quotaId, z.quotaName, z.subjectId)).Select(k => new {
- k.Key.quotaId,
- k.Key.quotaName,
- k.Key.subjectId,
- count = artAttachments.Where(p => p.studentId.Equals(stuId.GetString()) && p.artId.Equals(c.artId) && p.quotaId.Equals(k.Key.quotaId) && p.subjectId.Equals(k.Key.subjectId)).ToList().Count > 0 ?
- artAttachments.Where(p => p.studentId.Equals(stuId.GetString()) && p.artId.Equals(c.artId) && p.quotaId.Equals(k.Key.quotaId) && p.subjectId.Equals(k.Key.subjectId)).ToList().Count : 0
- })
- });
- var newArts = arts.Select(c => new {
-
- c.id,
- c.name,
- c.school,
- c.createTime,
- c.type,
- c.classes,
- c.progress,
- c.scope,
- c.areaId,
- c.pId,
- c.topic,
- c.startTime,
- c.endTime,
- c.uploadSTime,
- c.uploadETime,
- c.publish,c.subjects,
- c.period,
- c.periodType,
- c.zymusicstds,c.code,
- c.examDeadline,
- quotStus.Where(z => z.artId.Equals(c.id)).FirstOrDefault().quotas,
- count = artAttachments.Where(z => z.artId.Equals(c.id)).ToList().Count
- });
- return Ok(new { arts = newArts ,token});
- } catch (Exception e) {
- await _dingDing.SendBotMsg($"OS,{_option.Location},art/find-children-activity()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest("500错误");
- }
- }
- /// <summary>
- /// 获取当前老师所在范围的活动列表
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("find-teacher-activity")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> getTeacherActivity(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("studentId", out JsonElement teacId)) return BadRequest();
- if (!request.TryGetProperty("classIds", out JsonElement classIds)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();//学校编码
- List<string> cIds = classIds.ToObject<List<string>>();
- var client = _azureCosmos.GetCosmosClient();
- StringBuilder stringBuilder = new($"select value(c) from c where (c.status<>404 or IS_DEFINED(c.status) = false )");
- string continuationToken = string.Empty;
- string token = default;
- stringBuilder.Append("order by c.createTime desc");
- //是否需要进行分页查询,默认不分页
- if (request.TryGetProperty("token", out JsonElement token_1))
- {
- token = token_1.GetString();
- };
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- List<ArtEvaluation> arts = new();
- var result = await client.GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ArtEvaluation>(stringBuilder.ToString(), $"Art-{code}", token, 5);
- if (result.list.IsNotEmpty())
- {
- arts = result.list;
- token = result.continuationToken;
- }
- arts = arts.Where(c => c.classes.Intersect(cIds).Any()).Where((x, i) => arts.FindIndex(z => z.id == x.id) == i).ToList();
- List<string> artIds = new();
- artIds = arts.Select(c => c.id).ToList();
- List<ArtAttachment> artAttachments = new();
- string sqlTask = $"select value(c) from c where c.studentId = '{teacId}' and c.artId in ({string.Join(",", artIds.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<ArtAttachment>(queryText: sqlTask, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtAttachment-{code}") }))
- {
- artAttachments.Add(item);
- }
- var newArts = arts.Select(c => new {
- c.id,
- c.name,
- c.school,
- c.createTime,
- c.type,
- c.classes,
- c.progress,
- c.scope,
- c.areaId,
- c.pId,
- c.topic,
- c.startTime,
- c.endTime,
- c.uploadSTime,
- c.uploadETime,
- c.publish,
- c.subjects,
- c.period,
- c.periodType,
- c.zymusicstds,
- c.code,
- count = artAttachments.Where(z => z.artId.Equals(c.id)).ToList().Count
- });
- return Ok(new { arts = newArts, token });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},art/find-children-activity()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest("500错误");
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("find-summary-activity")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> findSummaryActivity(JsonElement request)
- {
- try
- {
- if (!request.TryGetProperty("studentId", out JsonElement stuId)) return BadRequest();
- if (!request.TryGetProperty("artId", out JsonElement artId)) return BadRequest();
- //if (!request.TryGetProperty("acId", out JsonElement taskId)) return BadRequest();
- if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();//学校编码
- var client = _azureCosmos.GetCosmosClient();
- StudentArtResult result = new();
- ArtEvaluation art = new();
- string stu = string.Format("{0}{1}{2}", code.GetString(), "-", stuId.GetString());
- var res = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(stu.ToString(), new PartitionKey($"ArtResult-{artId}"));
- if (res.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(res.Content);
- result = json.ToObject<StudentArtResult>();
-
- }
- List<string> taskIds = new();
- var qut = result.results.Where(c => c.quotaId.Equals("quota_22")).ToList();
- foreach (var quota in qut) {
- result.results.Remove(quota);
- }
- taskIds = result.results.Select(c => c.taskId).ToList();
- List<ArtAttachment> artAttachments = new();
- string sqlTask = $"select value(c) from c where c.studentId = '{stuId}' and c.taskId in ({string.Join(",", taskIds.Select(s => $"'{s}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
- GetItemQueryIteratorSql<ArtAttachment>(queryText: sqlTask, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ArtAttachment-{code}") }))
- {
- artAttachments.Add(item);
- }
- var resArt = await client.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync(artId.ToString(), new PartitionKey($"Art-{code}"));
- if (resArt.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(resArt.Content);
- art = json.ToObject<ArtEvaluation>();
- }
- /* var setting = art.settings.Where(c => c.id.Equals("quota_22")).FirstOrDefault();
- art.settings.Remove(setting);*/
- return Ok(new { result,art, artAttachments });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},art/find-summary-activity()\n{e.Message}\n{e.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return BadRequest("500错误");
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("upload-all")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> UploadAll(JsonElement element)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //if (!element.TryGetProperty("code", out JsonElement school)) return BadRequest();
- if (!element.TryGetProperty("attachments", out JsonElement stus)) return BadRequest();
- stuFiles files = stus.ToObject<stuFiles>();
- List<string> value = new List<string>();
- await foreach (var s in stuTask(files, client))
- {
- if (s.code == 1)
- {
- value.Add(s.value);
- }
- }
- if (value.Count > 0)
- {
- return Ok(new { code = 400, msg = "学生ID上传异常", value });
- }
- else
- {
- return Ok(files);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},aclassone/uploadAll()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { code = 500, msg = ex.Message });
- }
- }
- [ProducesDefaultResponseType]
- [HttpPost("delete")]
- #if !DEBUG
- [Authorize(Roles = "AClassONE")]
- #endif
- public async Task<IActionResult> deleteFiels(JsonElement element)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- if (!element.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!element.TryGetProperty("code", out JsonElement code)) return BadRequest();
- ArtAttachment attachment = new();
- var res = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync(id.ToString(), new PartitionKey($"ArtAttachment-{code}"));
- if (res.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(res.Content);
- attachment = json.ToObject<ArtAttachment>();
- }
- List<Attachment> atts = attachment.files;
- foreach (Attachment att in atts) {
- await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, code.GetString(), new List<string> { $"{att.blob}" });
- }
- await client.GetContainer("TEAMModelOS", "Student").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"ArtAttachment-{code}"));
- return Ok();
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},aclassone/delete()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- return Ok(new { code = 500, msg = ex.Message });
- }
- }
- private async IAsyncEnumerable<(int code, string value)> stuTask(stuFiles files, CosmosClient client)
- {
- string value = "";
- int code = 0;
- try {
- if (string.IsNullOrEmpty(files.id))
- {
- ArtAttachment attachment = new()
- {
- id = Guid.NewGuid().ToString(),
- artId = files.artId,
- achievement = files.achievement,
- address = files.address,
- studentId = files.studentId,
- taskId = files.taskId,
- subjectId = files.subjectId,
- quotaId = files.quotaId,
- quotaName = files.quotaName,
- uploadName = files.uploadName,
- uploadTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- duration = files.duration,
- name = files.name,
- des = files.des,
- artType = files.artType,
- level = files.level,
- files = files.files,
- ttl = -1,
- code = "ArtAttachment-" + files.school
- };
- await client.GetContainer("TEAMModelOS", "Student").CreateItemAsync(attachment, new PartitionKey($"{attachment.code}"));
- }
- else
- {
- ArtAttachment attachment = new()
- {
- artId = files.artId,
- achievement = files.achievement,
- address = files.address,
- studentId = files.studentId,
- taskId = files.taskId,
- subjectId = files.subjectId,
- quotaId = files.quotaId,
- quotaName = files.quotaName,
- updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- uploadName = files.uploadName,
- duration = files.duration,
- name = files.name,
- des = files.des,
- artType = files.artType,
- level = files.level,
- files = files.files,
- ttl = -1,
- code = "ArtAttachment-" + files.school
- };
- await client.GetContainer("TEAMModelOS", "Student").ReplaceItemAsync(attachment, attachment.id, new PartitionKey($"{attachment.code}"));
- }
- }
- catch (Exception e) {
- value = files.studentId;
- code = 1;
- }
- yield return (code, value);
- }
- private async Task<(int code, WeChatPhone phone)> GetWeChatPhoneNumber(string phoneCode)
- {
- var wxappid = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:appid");
- var wxsecret = _configuration.GetValue<string>("HaBookAuth:WXMiniAPP:secret");
- string urlAccessToken = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={wxappid}&secret={wxsecret}";
- HttpResponseMessage responseMessage = await _httpClient.CreateClient().GetAsync(urlAccessToken);
- string contentToken = responseMessage.StatusCode == HttpStatusCode.OK ? await responseMessage.Content.ReadAsStringAsync() : "{}";
- JsonElement WeChapToken = contentToken.ToObject<JsonElement>();
- string WeChataccess_token = $"{WeChapToken.GetProperty("access_token")}";
- Dictionary<string, object> dict = new() { { "code", phoneCode } };
- string url = $"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={WeChataccess_token}";
- // 将参数转化为HttpContent
- HttpContent contentPhone = new StringContent(dict.ToJsonString(), Encoding.UTF8, "application/json");
- var httpResponse = await _httpClient.CreateClient().PostAsync(url, contentPhone);
- WeChatPhone phone = null;
- int code = 200;
- if (httpResponse.StatusCode == HttpStatusCode.OK)
- {
- string responseContent = await httpResponse.Content.ReadAsStringAsync();
- WeChatPhoneStatus? t = responseContent.ToObject<WeChatPhoneStatus>();
- phone = t.phone_info;
- if (phone==null)
- {
- code = 404;
- }
- else { code = 200; }
- }
- else
- {
- //微信找到。
- code = 404;
- }
- return (code, phone);
- }
- /// <summary>
- /// 查询考试信息
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [Authorize(Roles = "AClassONE")]
- [HttpPost("find-activity")]
- public async Task<IActionResult> FindExam(JsonElement request)
- {
- try
- {
- //var client = _azureCosmos.GetCosmosClient();
- var (id, name, pic, school) = HttpContext.GetAuthTokenInfo();
- (List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(request, id, school, _azureCosmos, _azureRedis);
- return Ok(new { datas, continuationToken });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find-activity()\n{e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- return BadRequest("500错误");
- }
- }
- public class TeacherRoleGrouplist
- {
- public HashSet<string> roles { get; set; }
- public string scope { get; set; }
- public RGroupList groupList { get; set; }
- public string subjectId { get; set; }
- public string subjectName { get; set; }
- public string subjectBindId { get; set; }
- }
- public class WeChatPhone
- {
- public string? phoneNumber { get; set; }
- public string? purePhoneNumber { get; set; }
- public string? countryCode { get; set; }
- // public JsonElement watermark { get; set; }
- }
- public class WeChatPhoneStatus
- {
- public int? errcode { get; set; }
- public string? errmsg { get; set; }
- public WeChatPhone? phone_info { get; set; }
- }
- private class stuFiles
- {
- public string id { get; set; }
- public string school { get; set; }
- public string artId { get; set; }
- public string taskId { get; set; }
- public string studentId { get; set; }
- public string quotaId { get; set; }
- public string quotaName { get; set; }
- public string subjectId { get; set; }
- public string address { get; set; }
- public string time { get; set; }
- public string duration { get; set; }
- public string achievement { get; set; }
- public string name { get; set; }
- public string des { get; set; }
- //0 艺术特长 1 艺术体验
- public int artType { get; set; } = -1;
- // 0 校级 1 区级 2 市级 3 省级 4 国家级
- public int level { get; set; } = -1;
- public long uploadTime { get; set; }
- public string uploadName { get; set; }
- public List<Attachment> files { get; set; } = new List<Attachment>();
- }
- }
- }
|