123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092 |
- using Microsoft.AspNetCore.Mvc;
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.DI;
- using System.Text.Json;
- using TEAMModelOS.SDK.Models;
- using Microsoft.AspNetCore.Http;
- using Azure.Cosmos;
- using TEAMModelOS.SDK.Extension;
- using System.IdentityModel.Tokens.Jwt;
- using System.IO;
- using System.Linq;
- using Microsoft.Extensions.Options;
- using System.Net.Http;
- using System.Net;
- using Microsoft.Extensions.Configuration;
- using TEAMModelOS.Filter;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Authorization;
- using TEAMModelOS.SDK.DI.CoreAPI;
- using DocumentFormat.OpenXml.Wordprocessing;
- using static TEAMModelOS.Controllers.FixDataController;
- using Microsoft.Extensions.Hosting;
- using Microsoft.AspNetCore.Hosting;
- using DocumentFormat.OpenXml.Office2010.Excel;
- namespace TEAMModelOS.Controllers
- {
- [ProducesResponseType(StatusCodes.Status200OK)]
- [ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("school/teacher")]
- [ApiController]
- public class SchoolTeacherController : Controller
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureStorageFactory _azureStorage;
- private readonly Option _option;
- private readonly IConfiguration _configuration;
- private readonly NotificationService _notificationService;
- private readonly AzureServiceBusFactory _azureServiceBus;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly IWebHostEnvironment _environment;
- private readonly DingDing _dingDing;
- public SchoolTeacherController(IWebHostEnvironment environment,DingDing dingDing, CoreAPIHttpService coreAPIHttpService, AzureServiceBusFactory azureServiceBus, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, NotificationService notificationService)
- {
- _dingDing = dingDing;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _option = option?.Value;
- _configuration = configuration;
- _notificationService = notificationService;
- _azureServiceBus = azureServiceBus;
- _coreAPIHttpService = coreAPIHttpService;
- _environment = environment;
- }
- /// <summary>
- /// 取得學校所有老師(不論加入狀態)
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacher-all")]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- public async Task<IActionResult> GetSchoolTeacherAll(JsonElement request)
- {
- var client = _azureCosmos.GetCosmosClient();
- //參數取得
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- //string status_str = (request.TryGetProperty("join_status", out JsonElement status_json)) ? status_json.ToString() : "join";
- //資料取得
- List<ScTeacher> teachers = new List<ScTeacher>();
- try
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ScTeacher>
- (queryText: $"SELECT c.subjectIds, c.id, c.name, c.picture ,c.status, c.job, c.createTime, ARRAY_LENGTH(c.permissions) as permissionCount,c.permissions,c.roles , c.size FROM c",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
- {
- if ($"{item.createTime}".Length > 10)
- {
- item.createTime = item.createTime / 1000;
- }
- teachers.Add(item);
- }
- if (teachers.IsNotEmpty())
- {
- List<IdNameCode> groupLists = new List<IdNameCode>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<IdNameCode>
- (queryText: $"SELECT c.id, c.name, m.id as code FROM c join m in c.members where c.type='research' and m.id in ({string.Join(",", teachers.Select(x => $"'{x.id}'"))}) ",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"GroupList-{school_code}") }))
- {
- groupLists.Add(item);
- }
- if (groupLists.IsNotEmpty())
- {
- teachers.ForEach(x => {
- List<IdNameCode> codes = groupLists.FindAll(g => g.code.Equals(x.id));
- if (codes.IsNotEmpty())
- {
- x.groups = codes;
- }
- });
- }
- }
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
- IEnumerable<string> ids = null;
- List<CoreUser> coreUsers = new List<CoreUser>();
- if (response.Status == 200)
- {
- TeacherImport teacherImport = JsonDocument.Parse(response.Content).RootElement.ToObject<TeacherImport>();
- var idsIn = teacherImport.teachers.Where(x => !string.IsNullOrWhiteSpace(x.id));
- //id是空 其他不是空的
- var tmdidsi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.tmdid)).Select(z => z.tmdid);
- var phonesi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.phone)).Select(z => z.phone);
- var emailsi = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.email)).Select(z => z.email);
- List<string> skeys = new List<string>();
- if (idsIn.Any())
- {
- skeys.AddRange(idsIn.Select(x => x.id));
- }
- if (tmdidsi.Any())
- {
- skeys.AddRange(tmdidsi);
- }
- if (phonesi.Any())
- {
- skeys.AddRange(phonesi);
- }
- if (emailsi.Any())
- {
- skeys.AddRange(emailsi);
- }
- if (skeys.Any())
- {
- try
- {
- var content = new StringContent(skeys.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- coreUsers = json.ToObject<List<CoreUser>>();
- ids = coreUsers.Select(x => x.id);
- }
- }
- catch (Exception ex)
- {
- //await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n\n{skeys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- if (coreUsers.Any())
- {
- teacherImport.teachers.ForEach(t =>
- {
- if (!string.IsNullOrWhiteSpace(t.id))
- {
- CoreUser coreUser = coreUsers.Find(x => x.searchKey.Equals(t.id) || x.id.Equals(t.id));
- if (coreUser != null)
- {
- t.id = coreUser.id;
- t.name = coreUser.name;
- t.picture = coreUser.picture;
- t.tmdid = coreUser.id;
- if (!string.IsNullOrWhiteSpace(coreUser.mobile))
- {
- t.phone = coreUser.mobile;
- }
- if (!string.IsNullOrWhiteSpace(coreUser.mail))
- {
- t.email = coreUser.mail;
- }
- }
- else
- {
- t.id = null;
- }
- }
- if (string.IsNullOrWhiteSpace(t.id))
- {
- if (!string.IsNullOrWhiteSpace(t.tmdid))
- {
- CoreUser coreUser = coreUsers.Find(x => x.id.Equals(t.tmdid));
- if (coreUser != null)
- {
- t.id = coreUser.id;
- t.name = coreUser.name;
- t.picture = coreUser.picture;
- t.tmdid = coreUser.id;
- if (!string.IsNullOrWhiteSpace(coreUser.mobile))
- {
- t.phone = coreUser.mobile;
- }
- if (!string.IsNullOrWhiteSpace(coreUser.mail))
- {
- t.email = coreUser.mail;
- }
- }
- }
- if (string.IsNullOrWhiteSpace(t.id))
- {
- if (!string.IsNullOrWhiteSpace(t.phone))
- {
- CoreUser coreUser = coreUsers.Find(x => !string.IsNullOrWhiteSpace(x.mobile) && x.mobile.Equals(t.phone));
- if (coreUser != null)
- {
- t.id = coreUser.id;
- t.name = coreUser.name;
- t.picture = coreUser.picture;
- t.tmdid = coreUser.id;
- if (!string.IsNullOrWhiteSpace(coreUser.mobile))
- {
- t.phone = coreUser.mobile;
- }
- if (!string.IsNullOrWhiteSpace(coreUser.mail))
- {
- t.email = coreUser.mail;
- }
- }
- }
- }
- if (string.IsNullOrWhiteSpace(t.id))
- {
- if (!string.IsNullOrWhiteSpace(t.email))
- {
- CoreUser coreUser = coreUsers.Find(x => !string.IsNullOrWhiteSpace(x.mail) && x.mail.Equals(t.email));
- if (coreUser != null)
- {
- t.id = coreUser.id;
- t.name = coreUser.name;
- t.picture = coreUser.picture;
- t.tmdid = coreUser.id;
- if (!string.IsNullOrWhiteSpace(coreUser.mobile))
- {
- t.phone = coreUser.mobile;
- }
- if (!string.IsNullOrWhiteSpace(coreUser.mail))
- {
- t.email = coreUser.mail;
- }
- }
- }
- }
- }
- if (!string.IsNullOrWhiteSpace(t.id))
- {
- var tch = teachers.Find(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals(t.id));
- if (tch == null)
- {
- tch = new ScTeacher
- {
- id = t.id,
- iname = t.iname,
- name = t.name,
- picture = t.picture,
- status = "import",
- createTime = t.time,
- permissionCount = 0,
- size = 0,
- permissions = new List<string>(),
- roles = new List<string>(),
- subjectIds = new List<string>(),
- groups = new List<IdNameCode>(),
- note = t.note,
- phone = t.phone,
- email = t.email,
- };
- teachers.Add(tch);
- }
- else
- {
- tch.iname = t.iname;
- tch.note = t.note;
- tch.phone = t.phone;
- tch.email = t.email;
- }
- }
- else
- {
- //teachers.Add();
- var tch = new ScTeacher
- {
- id = t.id,
- picture = t.picture,
- iname = t.iname,
- name = t.name,
- status = "import",
- createTime = t.time,
- permissionCount = 0,
- size = 0,
- permissions = new List<string>(),
- roles = new List<string>(),
- subjectIds = new List<string>(),
- groups = new List<IdNameCode>(),
- note = t.note,
- phone = t.phone,
- email = t.email,
- };
- teachers.Add(tch);
- }
- });
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
- }
- else
- {
- var noids = teacherImport.teachers.Where(x => string.IsNullOrWhiteSpace(x.id));
- foreach (var t in noids)
- {
- teachers.Add(new ScTeacher
- {
- id = t.id,
- picture = t.picture,
- iname = t.iname,
- name = t.name,
- status = "import",
- createTime = t.time,
- permissionCount = 0,
- size = 0,
- permissions = new List<string>(),
- roles = new List<string>(),
- subjectIds = new List<string>(),
- groups = new List<IdNameCode>(),
- note = t.note,
- phone = t.phone,
- email = t.email,
- });
- }
- }
- }
- IEnumerable<string> coreids = null;
- coreids = teachers.Where(z => !string.IsNullOrWhiteSpace(z.id)).Select(x => x.id);
- List<CoreUser> users = new List<CoreUser>();
- if (coreids != null && coreids.Any())
- {
- try
- {
- var content = new StringContent(coreids.ToJsonString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- if (!string.IsNullOrWhiteSpace(json))
- {
- users = json.ToObject<List<CoreUser>>();
- }
- }
- catch (Exception ex)
- {
- //await _dingDing.SendBotMsg($"{_option.Location},导入名单时,查验key信息错误{ex.Message}\n{ex.StackTrace}\n\n{skeys.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- if (users.Any())
- {
- teachers.ForEach(x => {
- if (!string.IsNullOrWhiteSpace(x.id))
- {
- CoreUser coreUser = users.Find(u => u.id.Equals(x.id));
- if (coreUser != null)
- {
- x.phone = coreUser.mobile;
- x.email = coreUser.mail;
- }
- else
- {
- x.status = "delete";
- }
- }
- });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{_option.Location},{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
- }
- //Azure.Response responseSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("Base"));
- //if (responseSchool.Status == 200) {
- // School school = JsonDocument.Parse(responseSchool.Content).RootElement.Deserialize<School>();
- //}
- //处理区级权限数据
- HashSet<string> teacherIds = teachers.Where(x => !string.IsNullOrWhiteSpace(x.id)).Select(z => z.id).ToHashSet();
-
- if (teacherIds.Any()) {
- string sql = $"select distinct value c from c where array_length(c.areas)>0 and c.id in ({string.Join(",",teacherIds.Select(c=>$"'{c}'"))})";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
- .GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") })) {
- var teach= teachers.Find(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals(item.id));
- if (teach != null) { teach.areas = item.areas; }
- }
- }
- return Ok(new { teachers });
- }
- public class ScTeacher
- {
- public string id { get; set; }
- public string name { get; set; }
- public string iname { get; set; }
- public string picture { get; set; }
- public string status { get; set; }
- public string job { get; set; }
- public long createTime { get; set; }
- public int permissionCount { get; set; }
- public int size { get; set; }
- public List<string> permissions { get; set; }
- public List<string> roles { get; set; }
- public List<string> subjectIds { get; set; }
- public List<IdNameCode> groups { get; set; } = new List<IdNameCode>();
- public string note { get; set; }
- public string phone { get; set; }
- public string email { get; set; }
- public List<TEAMModelOS.SDK.Models.Teacher.TeacherArea> areas { get; set; } = new List<TEAMModelOS.SDK.Models.Teacher.TeacherArea>();
- }
- /// <summary>
- /// 取得某位老師的權限
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacher-permission")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetPermissionById(JsonElement request)
- {
- var client = _azureCosmos.GetCosmosClient();
- //參數取得
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- //老師權限資料取得
- object permissions = null;
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("permissions", out JsonElement value))
- {
- permissions = value.ToObject<object>();
- }
- }
- return Ok(new { permissions });
- }
- /// <summary>
- /// 取得權限總列表
- /// </summary>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacher-authoritylist")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetSchoolAuthorityList()
- {
- Dictionary<string, object> dict = new Dictionary<string, object>
- {
- { "PartitionKey", "authority"}
- };
- var table = _azureStorage.GetCloudTableClient().GetTableReference("SchoolSetting");
- List<Authority> authoritylist = await table.FindListByDict<Authority>(dict);
- return Ok(new { authoritylist });
- }
- /// <summary>
- /// 更新老師的權限(可複數)
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("upd-teacher-permission")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> UpdSchoolTeacherPermission(JsonElement request)
- {
- try
- {
- var client = _azureCosmos.GetCosmosClient();
- //參數取得
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- request.TryGetProperty("ids", out JsonElement _ids);
- request.TryGetProperty("job", out JsonElement _job);
- request.TryGetProperty("permission", out JsonElement _permission);
- request.TryGetProperty("pmClean", out JsonElement _pmClean);
- request.TryGetProperty("pmAdd", out JsonElement _pmAdd);
- request.TryGetProperty("pmRmv", out JsonElement _pmRmv);
- List<string> rmvPm = null;
- if (_pmRmv.ValueKind.Equals(JsonValueKind.Array))
- {
- rmvPm = _pmRmv.ToObject<List<string>>();
- }
- List<string> addPm = null;
- if (_pmAdd.ValueKind.Equals(JsonValueKind.Array))
- {
- addPm = _pmAdd.ToObject<List<string>>();
- }
- List<string> permission = null;
- if (_permission.ValueKind.Equals(JsonValueKind.Array))
- {
- permission = _permission.ToObject<List<string>>();
- }
- if (!_ids.ValueKind.Equals(JsonValueKind.Array))
- {
- return BadRequest();
- }
- List<string> ids = _ids.ToObject<List<string>>();
- //更新權限
- List<SchoolTeacher> schoolTeachers = new List<SchoolTeacher>();
- bool hasjob = false;
- if (ids.Count > 1 && !string.IsNullOrWhiteSpace($"{_job}"))
- {
- hasjob = true;
- }
- else if (ids.Count == 1 && permission.IsNotEmpty())
- {
- hasjob = true;
- }
- foreach (var id in ids)
- {
- SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(id, new PartitionKey($"Teacher-{school_code}"));
- if (permission.IsNotEmpty())
- {
- st.permissions = permission;
- }
- if (addPm.IsNotEmpty())
- {
- st.permissions.AddRange(addPm);
- }
- if (rmvPm.IsNotEmpty())
- {
- st.permissions.RemoveAll(x => rmvPm.Contains(x));
- }
- if (hasjob)
- {
- st.job = $"{_job}";
- }
- //清除权限标记。
- if (_pmClean.ValueKind.Equals(JsonValueKind.True)) {
- st.permissions = new List<string>();
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(st, id, new PartitionKey($"Teacher-{school_code}"));
- schoolTeachers.Add(st);
- }
- return Ok(new { teachers = schoolTeachers });
- }
- catch (Exception)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 追加老師及學校加入狀態
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("add-teacher-status")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "teacher,admin")]
- public async Task<IActionResult> AddSchoolTeacher(JsonElement request)
- {
- var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
- var client = _azureCosmos.GetCosmosClient();
- //參數取得
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("user_list", out JsonElement user_list)) return BadRequest();
- if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
- //取得學校資訊
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- string schareaId = string.Empty;
- string schpic = string.Empty;
- if (schresponse.Status == 200)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
- schareaId = $"{areaId}";
- schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
- schpic = $"{picture}";
- }
- else
- {
- return BadRequest();
- }
- try
- {
- List<KeyValuePair<string, int>> keys = new List<KeyValuePair<string, int>>();
- List<IdNameCode> ids = new List<IdNameCode>();
- foreach (var obj in user_list.EnumerateArray())
- {
- obj.TryGetProperty("id", out JsonElement id);
- obj.TryGetProperty("name", out JsonElement name);
- obj.TryGetProperty("picture", out JsonElement picture);
- IdNameCode tmd = new IdNameCode { id = $"{id}", name = $"{name}" };
- ids.Add(tmd);
- //老師個人資料
- var tresponse = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id.ToString(), new PartitionKey("Base"));
- if (tresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(tresponse.ContentStream);
- Teacher teacher = json.ToObject<Teacher>();
- tmd.code = teacher.lang;
- var school = teacher.schools.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
- if (school != null)
- {
- school.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- if (school.status.Equals("invite") && grant_type.ToString().Equals("invite"))
- {
- keys.Add(new KeyValuePair<string, int>($"{id}", 1));
- //移除不能发送通知的部分
- ids.Remove(tmd);
- continue;
- }
- if (school.status.Equals("join") && grant_type.ToString().Equals("invite"))
- {
- keys.Add(new KeyValuePair<string, int>($"{id}", 2));
- //移除不能发送通知的部分
- ids.Remove(tmd);
- continue;
- }
- school.status = grant_type.GetString();
- }
- else
- teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), status = grant_type.GetString() });
- if (teacher.schools.Count > 0 && teacher.size <= 1)
- {
- teacher.size = 2;
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
- }
- else
- {
- using var stream = new MemoryStream();
- using var writer = new Utf8JsonWriter(stream);
- writer.WriteStartObject();
- writer.WriteString("pk", "Base");
- writer.WriteString("code", "Base");
- writer.WriteString("id", id.ToString());
- writer.WriteString("name", name.ToString());
- writer.WriteString("picture", picture.ToString());
- writer.WriteNumber("size", 1);
- writer.WriteString("groupId", "default");
- writer.WriteString("groupName", "默认组别");
- writer.WriteNull("defaultSchool");
- writer.WriteStartArray("schools");
- writer.WriteStartObject();
- writer.WriteString("schoolId", school_code.ToString());
- writer.WriteString("name", schname);
- writer.WriteString("status", grant_type.ToString());
- writer.WriteEndObject();
- writer.WriteEndArray();
- writer.WriteEndObject();
- writer.Flush();
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemStreamAsync(stream, new PartitionKey("Base"));
- }
- //學校老師資料
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
- //SchoolTeacher schteacher = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(id.ToString(), new PartitionKey($"Teacher-{school_code}"));
- if (sresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- SchoolTeacher schteacher = json.ToObject<SchoolTeacher>();
- if (schteacher.status.Equals("invite") && grant_type.ToString().Equals("invite"))
- {
- keys.Add(new KeyValuePair<string, int>($"{id}", 1));
- continue;
- }
- if (schteacher.status.Equals("join") && grant_type.ToString().Equals("invite"))
- {
- keys.Add(new KeyValuePair<string, int>($"{id}", 2));
- continue;
- }
- schteacher.status = grant_type.ToString();
- schteacher.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<SchoolTeacher>(schteacher, id.ToString(), new PartitionKey($"Teacher-{school_code}"));
- }
- else
- {
- using var stream = new MemoryStream();
- using var writer = new Utf8JsonWriter(stream);
- writer.WriteStartObject();
- writer.WriteString("pk", "Teacher");
- writer.WriteString("code", $"Teacher-{school_code}");
- writer.WriteString("id", id.ToString());
- writer.WriteString("name", name.ToString());
- writer.WriteString("groupId", "default");
- writer.WriteString("groupName", "默认组别");
- writer.WriteString("picture", picture.ToString());
- writer.WriteNull("job");
- writer.WriteNumber("size", 0);
- writer.WriteStartArray("roles");
- writer.WriteStringValue("teacher");
- writer.WriteEndArray();
- writer.WriteStartArray("permissions");
- if (grant_type.ToString().Equals("join"))
- {
- writer.WriteStringValue("content-read");
- writer.WriteStringValue("exercise-read");
- writer.WriteStringValue("knowledge-read");
- writer.WriteStringValue("syllabus-read");
- }
- writer.WriteEndArray();
- writer.WriteString("status", grant_type.ToString());
- writer.WriteNumber("createTime", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
- writer.WriteEndObject();
- writer.Flush();
- await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemStreamAsync(stream, new PartitionKey($"Teacher-{school_code}"));
- }
- if (grant_type.ToString().Equals("join"))
- {
- await TmdUserService.JoinSchool(client, $"{id}", $"{picture}", $"{name}", $"{school_code}", $"{schname}");
- }
- }
- string bizcode = grant_type.GetString();
- if (grant_type.GetString().Equals("join"))
- {
- bizcode = "request-join";
- }
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"ies5:{_option.Location}:private",
- to = ids.Select(x => x.id).ToList(),
- label = $"{bizcode}_school",
- body = new {
- location = _option.Location,
- biz = bizcode,
- tmdid = tid,
- tmdname = tname.ToString(),
- schoolcode = $"{school_code}",
- schoolname = $"{schname}",
- status = 1,
- time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
- }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
- _coreAPIHttpService.PushNotify(ids, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
- new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" } , { "tmdid",tid} }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- return Ok(new { exist = keys });
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 學校變更老師加入狀態
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "admin", Permissions = "schoolSetting-upd,auth-upd,schoolAc-upd,teacher-upd")]
- [HttpPost("upd-teacher-status")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> UpdSchoolTeacherStatus(JsonElement request)
- {
- try
- {
- var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
- if (!request.TryGetProperty("grant_type", out JsonElement grant_type)) return BadRequest();
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
- request.TryGetProperty("importName", out JsonElement _importName);
- var client = _azureCosmos.GetCosmosClient();
- //取得學校資訊
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- string schareaId = string.Empty;
- string schpic = string.Empty;
- if (schresponse.Status == 200)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- schjson.RootElement.TryGetProperty("areaId", out JsonElement areaId);
- schareaId = $"{areaId}";
- schjson.RootElement.TryGetProperty("picture", out JsonElement picture);
- schpic = $"{picture}";
- }
- else
- {
- return BadRequest();
- }
- //在老師表找出老師,處理該學校狀態 (老師基本資料應該要存在)
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
- if (teacher.schools == null)
- teacher.schools = new List<Teacher.TeacherSchool>();
- var school = teacher.schools?.FirstOrDefault(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
- if (school != null)
- {
- school.status = grant_type.GetString();
- school.time = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
- }
- else
- teacher.schools.Add(new Teacher.TeacherSchool() { areaId = schareaId, picture = schpic, schoolId = school_code.GetString(), name = schname, time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), status = grant_type.GetString() });
- var dft = new List<string>() { "content-read", "exercise-read", "knowledge-read", "syllabus-read" };
- if (teacher.schools.Count > 0 && teacher.size <= 1)
- {
- teacher.size = 2;
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
- //在學校表處理該學校教師帳號的狀態
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
- if (sresponse.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
- SchoolTeacher steacher = json.ToObject<SchoolTeacher>();
- steacher.status = grant_type.GetString();
- if (grant_type.ToString().Equals("join"))
- {
- if (steacher.permissions.IsNotEmpty())
- {
- foreach (var d in dft)
- {
- if (!steacher.permissions.Contains(d))
- {
- steacher.permissions.Add(d);
- }
- }
- }
- else
- {
- steacher.permissions = dft;
- }
- }
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(steacher, id.GetString(), new PartitionKey($"Teacher-{school_code}"));
- }
- else
- {
- SchoolTeacher st = new SchoolTeacher()
- {
- pk = "Teacher",
- code = $"Teacher-{school_code}",
- createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- id = teacher.id,
- name = teacher.name,
- picture = teacher.picture,
- roles = new List<string>(new string[] { "teacher" }),
- /// 只是申请加入就需要开放 这几个权限吗
- permissions = grant_type.GetString().Equals("join") ? dft : null,
- size = 0,
- status = grant_type.GetString()
- };
- var response = await client.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync(st, new PartitionKey($"Teacher-{school_code}"));
- }
- if (grant_type.ToString().Equals("join"))
- {
- await TmdUserService.JoinSchool(client, $"{teacher.id}", $"{teacher.picture}", $"{teacher.name}", $"{school_code}", $"{schname}");
- }
- string bizcode = grant_type.GetString();
- if (grant_type.GetString().Equals("join"))
- {
- bizcode = "request-join";
- if (!string.IsNullOrWhiteSpace($"{_importName}"))
- {
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
- TeacherImport teacherImport = null;
- if (response.Status == 200)
- {
- teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
- var tchs = teacherImport.teachers.FindAll(x => x.iname.Equals($"{_importName}") && string.IsNullOrWhiteSpace(x.id));
- if (tchs.IsNotEmpty())
- {
- var tch = tchs[0];
- string ujson = null;
- var content = new StringContent(new List<string> { $"{id}" }.ToJsonString(), Encoding.UTF8, "application/json");
- ujson = await _coreAPIHttpService.GetUserInfos(content);
- List<CoreUser> coreUsers = new List<CoreUser>();
- if (!string.IsNullOrWhiteSpace(ujson))
- {
- coreUsers = ujson.ToObject<List<CoreUser>>();
- }
- if (coreUsers.IsNotEmpty())
- {
- tch.phone = coreUsers[0].mobile;
- tch.email = coreUsers[0].mail;
- }
- tch.id = $"{teacher.id}";
- tch.picture = $"{teacher.picture}";
- tch.status = $"{grant_type}";
- tch.time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- tch.tmdid = teacher.id;
- tch.name = teacher.name;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
- }
- }
- }
- }
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"ies5:{_option.Location}:private",
- to = new List<string> { teacher.id },
- label = $"{bizcode}_school",
- body = new { location = _option.Location, biz = bizcode, tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name=teacher.name, code= teacher.lang} }, $"{bizcode}_school", Constant.NotifyType_IES5_Management,
- new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- return Ok(new { });
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- }
- /// <summary>
- /// 學校移除老師跟學校關聯
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "admin")]
- [HttpPost("rmv-teacher")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> RmvSchoolTeacher(JsonElement request)
- {
- if (!request.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
- try
- {
- var (tid, tname, _, tschool) = HttpContext.GetAuthTokenInfo();
-
- request.TryGetProperty("id", out JsonElement id);
- request.TryGetProperty("name", out JsonElement name);
- var client = _azureCosmos.GetCosmosClient();
- //在老師表找出老師,刪除該學校 (老師基本資料應該要存在)
- Azure.Response response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync($"{school_code}", new PartitionKey("TeacherImport"));
- TeacherImport teacherImport = null;
- if (response.Status == 200)
- {
- teacherImport = JsonDocument.Parse(response.Content).RootElement.Deserialize<TeacherImport>();
- }
- if (!string.IsNullOrWhiteSpace($"{name}") && teacherImport != null)
- {
- //移除同名的、其中一个
- var ts = teacherImport.teachers.FindAll(x => string.IsNullOrWhiteSpace(x.id) && !string.IsNullOrWhiteSpace(x.iname) && x.iname.Equals($"{name}"));
- if (ts.IsNotEmpty())
- {
- teacherImport.teachers.Remove(ts.First());
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
- }
- }
- if (!string.IsNullOrWhiteSpace($"{id}"))
- {
- if (teacherImport != null)
- {
- int count = teacherImport.teachers.RemoveAll(x => !string.IsNullOrWhiteSpace(x.id) && x.id.Equals($"{id}"));
- if (count > 0)
- {
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReplaceItemAsync(teacherImport, $"{school_code}", new PartitionKey("TeacherImport"));
- }
- }
- Teacher teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id.ToString(), new PartitionKey("Base"));
- //教师还未加入,就被移除,则不通知。
- bool needNotify = false;
- var sc= teacher.schools.FindAll(x => x.schoolId.Equals($"{school_code}"));
- if (sc.IsNotEmpty()) {
- sc.ForEach(z => {
- if (z.status.Equals("join")) {
- needNotify = true;
- }
- });
- }
- var school = teacher.schools.RemoveAll(x => x.schoolId.Equals(school_code.GetString(), StringComparison.OrdinalIgnoreCase));
- if (!string.IsNullOrEmpty(teacher.defaultSchool) && teacher.defaultSchool.Equals($"{school_code}"))
- {
- if (teacher.schools.IsNotEmpty())
- {
- teacher.defaultSchool = teacher.schools[0].schoolId;
- }
- else
- {
- teacher.defaultSchool = null;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, id.ToString(), new PartitionKey("Base"));
- //移除學校表中的老師document
- var sresponse = await client.GetContainer(Constant.TEAMModelOS, "School").DeleteItemStreamAsync(id.GetString(), new PartitionKey($"Teacher-{school_code}"));
- //将教师移除学校,同时也移除研修名单,教研组。
- StringBuilder queryText = new StringBuilder($"SELECT distinct value(c) FROM c where c.type='yxtrain' or c.type='research' ");
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<GroupList>(queryText: queryText.ToString(),
- requestOptions: new QueryRequestOptions() { PartitionKey = new Azure.Cosmos.PartitionKey($"GroupList-{school_code.GetString()}") }))
- {
- bool exists = item.members.Exists(x => x.id.Equals(id.ToString()));
- if (exists)
- {
- item.members.RemoveAll(x => x.id.Equals(id.ToString()));
- await GroupListService.UpsertList(item, _azureCosmos, _configuration, _azureServiceBus);
- //await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync(item,item.id,new PartitionKey(item.code));
- }
- }
- //await TmdUserService.LeaveSchool(client, $"{teacher.id}", $"{school_code}" );
- //取得學校資訊
- var schresponse = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(school_code.ToString(), new PartitionKey("Base"));
- string schname = string.Empty;
- if (schresponse.Status == 200)
- {
- using var schjson = await JsonDocument.ParseAsync(schresponse.ContentStream);
- schjson.RootElement.TryGetProperty("name", out JsonElement jsonschname);
- schname = jsonschname.ToString();
- }
- else
- {
- return BadRequest();
- }
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"ies5:{_option.Location}:private",
- to = new List<string> { teacher.id },
- label = $"remove_school",
- body = new { location = _option.Location, biz = "remove", tmdid = tid, tmdname = tname, schoolcode = $"{school_code}", schoolname = $"{schname}", status = 1, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- var code = await _notificationService.SendNotification(clientID, clientSecret, location, url, notification);
- if (needNotify) {
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, $"remove_school", Constant.NotifyType_IES5_Management,
- new Dictionary<string, object> { { "tmdname", tname }, { "schoolName", schname }, { "schoolId", $"{school_code}" }, { "tmdid", tid } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- }
- }
- return Ok(new { });
- }
- catch (Exception ex)
- {
- return BadRequest();
- }
- finally {
- Azure.Response schoolRes = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync($"{school_code}", new PartitionKey("Base"));
- if (schoolRes.Status==200)
- {
- School school = JsonDocument.Parse(schoolRes.Content).RootElement.Deserialize<School>();
- string sql = "select value sum(c.size ) from c ";
- int teachSize = 0;
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<int>(queryText: sql,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{school_code}") }))
- {
- teachSize += item;
- }
- school.tsize = teachSize;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(school, school.id, new PartitionKey("Base"));
- }
- }
- }
- /// <summary>
- /// 取得CoreID資訊
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- //[AuthToken(Roles = "admin")]
- [HttpPost("get-coreuser")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> GetUserFromCoreID(JsonElement request)
- {
- var content = new StringContent(request.ToString(), Encoding.UTF8, "application/json");
- string json = await _coreAPIHttpService.GetUserInfos(content);
- return Ok(json.ToObject<JsonElement>());
- }
- }
- }
|