BINoticeController.cs 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Options;
  6. using System.Net.Http;
  7. using TEAMModelOS.SDK.DI;
  8. using TEAMModelOS.SDK;
  9. using TEAMModelOS.Models;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using TEAMModelOS.SDK.Context.Constant;
  13. using System.Collections.Generic;
  14. using System.Text;
  15. using TEAMModelOS.SDK.Extension;
  16. using TEAMModelBI.Models;
  17. using System.Linq;
  18. using TEAMModelBI.Filter;
  19. using TEAMModelOS.SDK.Models.Cosmos.BI;
  20. using Microsoft.Azure.Cosmos;
  21. using System;
  22. using TEAMModelOS.SDK.Models.Service.BI;
  23. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  24. using TEAMModelBI.Tool.Extension;
  25. using TEAMModelOS.SDK.Models;
  26. using Pipelines.Sockets.Unofficial.Arenas;
  27. using TEAMModelBI.Tool;
  28. using Azure.Core;
  29. using Azure.Storage.Blobs.Models;
  30. using Microsoft.AspNetCore.Authorization;
  31. using static TEAMModelBI.Models.Extension.GeoRegion;
  32. using System.Diagnostics.Metrics;
  33. using Microsoft.Azure.Cosmos.Table;
  34. using System.Net.Http.Json;
  35. using NotifyData = TEAMModelOS.SDK.CoreAPIHttpService.NotifyData;
  36. using Microsoft.Azure.Cosmos.Linq;
  37. namespace TEAMModelBI.Controllers.BICommon
  38. {
  39. [Route("notice")]
  40. [ApiController]
  41. public class BINoticeController : ControllerBase
  42. {
  43. private readonly AzureCosmosFactory _azureCosmos;
  44. private readonly DingDing _dingDing;
  45. private readonly Option _option;
  46. private readonly AzureStorageFactory _azureStorage;
  47. private readonly IConfiguration _configuration;
  48. private readonly AzureServiceBusFactory _serviceBus;
  49. private readonly IHttpClientFactory _http;
  50. private readonly CoreAPIHttpService _coreAPIHttpService;
  51. private readonly IWebHostEnvironment _environment; //读取文件
  52. private readonly HttpClient _httpClient;
  53. private readonly SnowflakeId _snowflakeId;
  54. public BINoticeController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IConfiguration configuration, AzureServiceBusFactory serviceBus, IHttpClientFactory http, CoreAPIHttpService coreAPIHttpService, IWebHostEnvironment hostingEnvironment, HttpClient httpClient, SnowflakeId snowflakeId)
  55. {
  56. _azureCosmos = azureCosmos;
  57. _dingDing = dingDing;
  58. _azureStorage = azureStorage;
  59. _option = option?.Value;
  60. _configuration = configuration;
  61. _serviceBus = serviceBus;
  62. _http = http;
  63. _coreAPIHttpService = coreAPIHttpService;
  64. _environment = hostingEnvironment;
  65. _httpClient = httpClient;
  66. _snowflakeId = snowflakeId;
  67. }
  68. /// <summary>
  69. /// 查询账户信息
  70. /// </summary>
  71. /// <param name="jsonElement"></param>
  72. /// <returns></returns>
  73. [AuthToken(Roles = "admin,rdc,assist,sales")]
  74. [HttpPost("get-info")]
  75. public async Task<IActionResult> GetInfo(JsonElement jsonElement)
  76. {
  77. jsonElement.TryGetProperty("ids", out JsonElement _ids);
  78. var cosmosClient = _azureCosmos.GetCosmosClient();
  79. List<string> ids = new();
  80. ids = _ids.ToObject<List<string>>();
  81. List<TmdUserinfo> userinfos = new();
  82. List<string> noFound = new();
  83. if (ids.Count > 0)
  84. {
  85. var content = new StringContent(ids.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
  86. string idJson = await _coreAPIHttpService.GetUserInfos(content);
  87. userinfos = idJson.ToObject<List<TmdUserinfo>>();
  88. foreach (var item in ids)
  89. {
  90. var tempId = userinfos.Where(s => s.id.Equals(item)).ToList();
  91. var tempMail = userinfos.Where(s => !string.IsNullOrEmpty($"{s.mail}") && s.mail.Equals(item)).ToList();
  92. var tempmobile = userinfos.Where(s => !string.IsNullOrEmpty($"{s.mobile}") && s.mobile.Equals(item)).ToList();
  93. if (tempId.Count == 0 && tempMail.Count == 0 && tempmobile.Count == 0)
  94. noFound.Add(item);
  95. }
  96. }
  97. return Ok(new { state = RespondCode.Ok, userinfos, noFound });
  98. }
  99. /// <summary>
  100. /// 依据学校id查询学校教师信息
  101. /// </summary>
  102. /// <param name="jsonElement"></param>
  103. /// <returns></returns>
  104. //[AuthToken(Roles = "admin,rdc,assist,sales")]
  105. [HttpPost("get-tchinfos")]
  106. public async Task<IActionResult> GetSchoolTeacher(JsonElement jsonElement)
  107. {
  108. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  109. List<IdInfo> idInfos = new();
  110. var cosmosClient = _azureCosmos.GetCosmosClient();
  111. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<IdInfo>(queryText: "select c.id,c.name,c.picture from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Teacher-{scId}") }))
  112. {
  113. idInfos.Add(item);
  114. }
  115. return Ok(new { state = RespondCode.Ok, idInfos });
  116. }
  117. /// <summary>
  118. /// BI发布端外消息
  119. /// </summary>
  120. /// <param name="jsonElement"></param>
  121. /// <returns></returns>
  122. [AuthToken(Roles = "admin,rdc,assist,sales")]
  123. [HttpPost("push-info")]
  124. public async Task<IActionResult> PushNotion(JsonElement jsonElement)
  125. {
  126. try
  127. {
  128. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  129. jsonElement.TryGetProperty("type", out JsonElement type);
  130. jsonElement.TryGetProperty("jumpUrl", out JsonElement jumpUrl);
  131. jsonElement.TryGetProperty("callbackName", out JsonElement callbackName);
  132. jsonElement.TryGetProperty("refuseName", out JsonElement refuseName);
  133. if (!jsonElement.TryGetProperty("theme", out JsonElement theme)) return BadRequest();
  134. if (!jsonElement.TryGetProperty("content", out JsonElement content)) return BadRequest();
  135. jsonElement.TryGetProperty("tmdIds", out JsonElement _tmdIds);
  136. jsonElement.TryGetProperty("schoolIds", out JsonElement _schoolIds);
  137. jsonElement.TryGetProperty("areaIds", out JsonElement _areaIds);
  138. if (!jsonElement.TryGetProperty("crowdType", out JsonElement _crowdType)) return BadRequest();
  139. if (!jsonElement.TryGetProperty("sendTime", out JsonElement sendTime)) return BadRequest();
  140. jsonElement.TryGetProperty("source", out JsonElement source);
  141. jsonElement.TryGetProperty("isOnlySave", out JsonElement isOnlySave);
  142. var cosmosClient = _azureCosmos.GetCosmosClient();
  143. //DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  144. List<IdNameCode> idNameCodes = new();
  145. BINotice bINotice = new();
  146. List<CrowdInfo> tmdIds = new();
  147. List<CrowdInfo> schoolIds = new();
  148. List<CrowdInfo> areaIds = new();
  149. List<string> tempScIds = new();
  150. //if (!string.IsNullOrEmpty($"{sendTime}"))
  151. // dateTime = DateTimeOffset.Parse($"{sendTime}");
  152. if (string.IsNullOrEmpty($"{_tmdIds}") && string.IsNullOrEmpty($"{_schoolIds}") && string.IsNullOrEmpty($"{_areaIds}"))
  153. return Ok(new { state = RespondCode.ParamsError, msg = "发送人群不能为空" });
  154. if (!string.IsNullOrEmpty($"{_tmdIds}"))
  155. tmdIds = _tmdIds.ToObject<List<CrowdInfo>>();
  156. if (!string.IsNullOrEmpty($"{_schoolIds}"))
  157. schoolIds = _schoolIds.ToObject<List<CrowdInfo>>();
  158. if (!string.IsNullOrEmpty($"{_areaIds}"))
  159. areaIds = _areaIds.ToObject<List<CrowdInfo>>();
  160. Crowd crowd = new()
  161. {
  162. tmdIds = tmdIds.Count > 0 ? tmdIds : new List<CrowdInfo>(),
  163. schoolIds = schoolIds.Count > 0 ? schoolIds : new List<CrowdInfo>(),
  164. areaIds = areaIds.Count > 0 ? areaIds : new List<CrowdInfo>(),
  165. types = $"{_crowdType}"
  166. };
  167. if (tmdIds.Count > 0)
  168. {
  169. StringBuilder tchSql = new($"select c.id, c.name,c.code,c.picture,c.nickname from c ");
  170. if (tmdIds.Count > 0)
  171. {
  172. tchSql.Append(BICommonWay.ManyScSql(" where c.id ", tmdIds.Select(s => s.id).ToList()));
  173. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: tchSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  174. {
  175. var tempId = idNameCodes.FindAll(fa => fa.id.Equals(item.id)).ToList();
  176. if (tempId.Count == 0)
  177. idNameCodes.Add(item);
  178. }
  179. }
  180. }
  181. if (areaIds.Count > 0)
  182. {
  183. StringBuilder scAreaSql = new($"select value(c.id) from c");
  184. if (schoolIds.Count > 0)
  185. {
  186. scAreaSql.Append(BICommonWay.ManyScSql(" where c.areaId", areaIds.Select(s => s.id).ToList()));
  187. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<string>(queryText: scAreaSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  188. {
  189. var tempScId = schoolIds.FindAll(fa => fa.Equals(item)).ToList();
  190. if (tempScId.Count == 0)
  191. tempScIds.Add(item);
  192. }
  193. }
  194. }
  195. if (schoolIds.Count > 0)
  196. {
  197. StringBuilder scTchSql = new($"select c.id, c.name, c.picture,c.nickname from c where c.pk='Teacher'");
  198. if (schoolIds.Count > 0)
  199. {
  200. scTchSql.Append(BICommonWay.ManyScSql(" and c.code", schoolIds.Select(s => s.id).ToList(), $"Teacher-"));
  201. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<IdNameCode>(queryText: scTchSql.ToString(), requestOptions: new QueryRequestOptions() { }))
  202. {
  203. var tempId = idNameCodes.FindAll(fa => fa.id.Equals(item.id)).ToList();
  204. if (tempId.Count == 0)
  205. idNameCodes.Add(item);
  206. }
  207. }
  208. }
  209. string tagServiceName = ($"{_crowdType}".ToLower().Contains("hita")) ? "HiTA" : $"{_crowdType}";
  210. bINotice = new()
  211. {
  212. id = Guid.NewGuid().ToString(),
  213. code = "BINotice",
  214. type = !string.IsNullOrEmpty($"{type}") ? type.GetInt32() : 0,
  215. jumpUrl = !string.IsNullOrEmpty($"{jumpUrl}") ? $"{jumpUrl}" : "",
  216. callbackName = !string.IsNullOrEmpty($"{callbackName}") ? $"{callbackName}" : "",
  217. refuseName = !string.IsNullOrEmpty($"{refuseName}") ? $"{refuseName}" : "",
  218. theme = $"{theme}",
  219. content = $"{content}",
  220. crowd = crowd,
  221. crowdIds = idNameCodes.Select(s => $"{s.id}_{tagServiceName}").ToList(),
  222. createId = _tmdId,
  223. sendTime = sendTime.GetInt64(),//发布时间待解决
  224. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  225. source = !string.IsNullOrEmpty($"{source}") ? $"{source}" : "BI"
  226. };
  227. bINotice = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<BINotice>(bINotice, new PartitionKey("BINotice"));
  228. if (isOnlySave.GetBoolean())
  229. {
  230. //BI发送端外通知
  231. _coreAPIHttpService.BIPushNotify(bINotice, new Dictionary<string, object> { { "tmdid", _tmdIds }, { "sendId", bINotice.crowdIds } }, _option.Location, _configuration, _dingDing);
  232. }
  233. return Ok(new { state = RespondCode.Ok, bINotice });
  234. }
  235. catch (Exception ex)
  236. {
  237. _ = _dingDing.SendBotMsg($"BI,{_option.Location},notion/PushNotion() \n{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  238. return BadRequest();
  239. }
  240. }
  241. /// <summary>
  242. /// 查询发布的消息信息
  243. /// </summary>
  244. /// <param name="jsonElement"></param>
  245. /// <returns></returns>
  246. [HttpPost("get-infos")]
  247. [AuthToken(Roles = "admin,rdc,assist,sales")]
  248. public async Task<IActionResult> GetInfos(JsonElement jsonElement)
  249. {
  250. jsonElement.TryGetProperty("id", out JsonElement id);
  251. var cosmosClient = _azureCosmos.GetCosmosClient();
  252. List<BINotice> bINotices = new();
  253. StringBuilder sql = new("select value(c) from c");
  254. if (!string.IsNullOrEmpty($"{id}"))
  255. sql.Append($" where c.id='{id}'");
  256. sql.Append($" order by c.sendTime desc ");
  257. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<BINotice>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BINotice") }))
  258. {
  259. bINotices.Add(item);
  260. }
  261. return Ok(new { state = RespondCode.Ok, bINotices });
  262. }
  263. /// <summary>
  264. /// 取得學區及所屬學校、教師數
  265. /// </summary>
  266. /// <param name="jsonElement"></param>
  267. /// <returns></returns>
  268. [HttpPost("get-areas")]
  269. #if !DEBUG
  270. [Authorize(Roles = "IES")]
  271. [AuthToken(Roles = "admin")]
  272. #endif
  273. public async Task<IActionResult> GetAreas(JsonElement jsonElement)
  274. {
  275. try
  276. {
  277. string reqAreaId = (jsonElement.TryGetProperty("areaId", out JsonElement _areaId)) ? _areaId.GetString() : string.Empty;
  278. bool showSchool = (jsonElement.TryGetProperty("showSchool", out JsonElement _showSchool)) ? _showSchool.GetBoolean() : false; //是否列出學校
  279. var cosmosClient = _azureCosmos.GetCosmosClient();
  280. List<AreaInfo> areaInfos = new();
  281. //取得學區
  282. string sqlArea = $"SELECT c.id, c.name FROM c ";
  283. string whereArea = string.Empty;
  284. if (!string.IsNullOrWhiteSpace(reqAreaId))
  285. {
  286. string wherePre = (!string.IsNullOrWhiteSpace(whereArea)) ? " AND " : string.Empty;
  287. whereArea += $"{wherePre} c.id = '{reqAreaId}' ";
  288. }
  289. if (!string.IsNullOrWhiteSpace(whereArea))
  290. {
  291. whereArea = $" WHERE {whereArea}";
  292. sqlArea = sqlArea + whereArea;
  293. }
  294. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", Constant.Normal).GetItemQueryIteratorSql<AreaInfo>(queryText: sqlArea, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  295. {
  296. areaInfos.Add(item);
  297. }
  298. //取得學校ID列表
  299. Dictionary<string, string> schAreaDic = new Dictionary<string, string>();
  300. Dictionary<string, string> schNameDic = new Dictionary<string, string>();
  301. List<string> teacherCodes = new List<string>();
  302. List<string> areaIds = areaInfos.Select(a => a.id).ToList();
  303. string sqlSch = $"SELECT c.id, c.name, c.areaId FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(areaIds)}, c.areaId)";
  304. ///實體校
  305. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  306. {
  307. string schId = item.GetProperty("id").ToString();
  308. string schName = item.GetProperty("name").ToString();
  309. string areaId = item.GetProperty("areaId").ToString();
  310. if (!schAreaDic.ContainsKey(schId))
  311. {
  312. schAreaDic.Add(schId, areaId);
  313. schNameDic.Add(schId, schName);
  314. }
  315. if (!teacherCodes.Contains($"Teacher-{schId}"))
  316. {
  317. teacherCodes.Add($"Teacher-{schId}");
  318. }
  319. }
  320. ///虛擬校
  321. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"VirtualBase") }))
  322. {
  323. string schId = item.GetProperty("id").ToString();
  324. string schName = item.GetProperty("name").ToString();
  325. string areaId = item.GetProperty("areaId").ToString();
  326. if (!schAreaDic.ContainsKey(schId))
  327. {
  328. schAreaDic.Add(schId, areaId);
  329. if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
  330. }
  331. }
  332. //取得學校教師數
  333. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>();
  334. string sqlTch = $"SELECT REPLACE(c.code, 'Teacher-', '') as schoolId, COUNT(c.id) AS tchCnt FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code) GROUP BY c.code";
  335. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  336. {
  337. string schId = item.GetProperty("schoolId").ToString();
  338. int tchCnt = item.GetProperty("tchCnt").GetInt32();
  339. schTeacherCntDic.Add(schId, tchCnt);
  340. }
  341. //資料整理1 有教師則記入
  342. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  343. {
  344. string schId = item.Key;
  345. int tchCnt = item.Value;
  346. string areaId = schAreaDic[schId];
  347. AreaInfo areaInfo = areaInfos.Where(a => a.id.Equals(areaId)).FirstOrDefault();
  348. if (areaInfo != null)
  349. {
  350. areaInfo.scCnt++;
  351. areaInfo.tchCnt += tchCnt;
  352. if (showSchool)
  353. {
  354. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  355. areaInfo.schools.Add(sch);
  356. }
  357. }
  358. }
  359. //資料整理2 移除無學校學區
  360. var result = areaInfos.Where(a => a.scCnt > 0).ToList();
  361. return Ok(new { state = RespondCode.Ok, result });
  362. }
  363. catch (Exception ex)
  364. {
  365. return BadRequest(new { ex });
  366. }
  367. }
  368. /// <summary>
  369. /// 取得地理位置所屬的學校或TMID
  370. /// </summary>
  371. /// <param name="jsonElement"></param>
  372. /// <returns></returns>
  373. [HttpPost("get-geos")]
  374. #if !DEBUG
  375. [Authorize(Roles = "IES")]
  376. [AuthToken(Roles = "admin")]
  377. #endif
  378. public async Task<IActionResult> GetGeos(JsonElement jsonElement)
  379. {
  380. regiondata regionData = GetRegionData(); //取得國省市區地理資訊架構
  381. Dictionary<string, string> geoIdNameDic = new Dictionary<string, string>(); //key: geoId val:geoName
  382. var cosmosClient = _azureCosmos.GetCosmosClient();
  383. bool showSchool = (jsonElement.TryGetProperty("showSchool", out JsonElement _showSchool)) ? _showSchool.GetBoolean() : false; //是否列出學校
  384. string countryId = (jsonElement.TryGetProperty("countryId", out JsonElement _countryId)) ? _countryId.GetString() : string.Empty; //地區ID(國ID)
  385. string provinceId = (jsonElement.TryGetProperty("provinceId", out JsonElement _provinceId)) ? _provinceId.GetString() : string.Empty; //省ID
  386. string cityId = (jsonElement.TryGetProperty("cityId", out JsonElement _cityId)) ? _cityId.GetString() : string.Empty; //市ID
  387. string distId = (jsonElement.TryGetProperty("dist", out JsonElement _distJobj)) ? _distJobj.GetString() : string.Empty; //區ID
  388. string countryName = string.Empty;
  389. string provinceName = string.Empty;
  390. string cityName = string.Empty;
  391. string distName = string.Empty;
  392. //bool hasVirtual = (jsonElement.TryGetProperty("virtual", out JsonElement virtualJobj)) ? virtualJobj.GetBoolean() : true; //是否取得虛擬學校
  393. bool isGlobal = (_option.Location.Contains("Global")) ? true : false;
  394. List<AreaInfo> geoInfos = new();
  395. //取得搜尋的國省市名稱
  396. if (string.IsNullOrWhiteSpace(countryId)) return BadRequest();
  397. countryName = (regionData.country.ContainsKey(countryId)) ? regionData.country[countryId].name : string.Empty;
  398. if (string.IsNullOrWhiteSpace(countryName))
  399. {
  400. return BadRequest();
  401. }
  402. else
  403. {
  404. if (isGlobal)
  405. {
  406. provinceId = string.Empty;
  407. if (countryId.Equals("TW"))
  408. {
  409. geoIdNameDic = new Dictionary<string, string>();
  410. foreach (KeyValuePair<string, regionbase> item in regionData.city[countryId][countryId.ToLower()])
  411. {
  412. geoIdNameDic.Add(item.Value.code, item.Value.name);
  413. }
  414. }
  415. }
  416. else
  417. {
  418. geoIdNameDic = new Dictionary<string, string>();
  419. foreach (KeyValuePair<string, regionbase> item in regionData.province[countryId])
  420. {
  421. geoIdNameDic.Add(item.Value.code, item.Value.name);
  422. }
  423. }
  424. }
  425. if (regionData.province.ContainsKey(countryId) && !string.IsNullOrWhiteSpace(provinceId))
  426. {
  427. provinceName = (regionData.province[countryId].ContainsKey(provinceId)) ? regionData.province[countryId][provinceId].name : string.Empty;
  428. geoIdNameDic = new Dictionary<string, string>();
  429. foreach (KeyValuePair<string, regionbase> item in regionData.city[countryId][provinceId])
  430. {
  431. geoIdNameDic.Add(item.Value.code, item.Value.name);
  432. }
  433. }
  434. if (isGlobal)
  435. {
  436. if (regionData.city.ContainsKey(countryId))
  437. {
  438. if (countryId.ToLower().Equals("tw"))
  439. {
  440. if (!string.IsNullOrWhiteSpace(cityId) && regionData.city[countryId][countryId.ToLower()].ContainsKey(cityId))
  441. {
  442. cityName = regionData.city[countryId][countryId.ToLower()][cityId].name;
  443. }
  444. }
  445. }
  446. } else
  447. {
  448. if (regionData.city.ContainsKey(countryId) &&
  449. !string.IsNullOrWhiteSpace(provinceId) && regionData.city[countryId].ContainsKey(provinceId) &&
  450. !string.IsNullOrWhiteSpace(cityId) && regionData.city[countryId][provinceId].ContainsKey(cityId)
  451. )
  452. {
  453. cityName = regionData.city[countryId][provinceId][cityId].name;
  454. }
  455. }
  456. //SQL文製作
  457. string groupKey = string.Empty;
  458. string sqlWhere = string.Empty;
  459. if (!string.IsNullOrWhiteSpace(countryName))
  460. {
  461. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  462. comeRemoveStr.ForEach(c => { countryName = countryName.Replace(c, ""); });
  463. sqlWhere += $" CONTAINS(c.region, '{countryName}') ";
  464. groupKey = (isGlobal) ? "city" : "province";
  465. }
  466. if (!string.IsNullOrWhiteSpace(provinceName))
  467. {
  468. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  469. comeRemoveStr.ForEach(c => { provinceName = provinceName.Replace(c, ""); });
  470. sqlWhere += $" CONTAINS(c.province, '{provinceName}') ";
  471. groupKey = "city";
  472. }
  473. if (!string.IsNullOrWhiteSpace(cityName))
  474. {
  475. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  476. comeRemoveStr.ForEach(c => { cityName = cityName.Replace(c, ""); });
  477. sqlWhere += $" CONTAINS(c.city, '{cityName}') ";
  478. groupKey = "name";
  479. }
  480. Dictionary<string, string> schGeoDic = new Dictionary<string, string>(); //key: schoolId val:統計的geoId
  481. Dictionary<string, string> schNameDic = new Dictionary<string, string>(); //key: schoolId val:學校名稱
  482. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>(); //key: schoolId val:學校教師數
  483. if (!string.IsNullOrWhiteSpace(sqlWhere))
  484. {
  485. //取得學校ID列表
  486. List<string> teacherCodes = new List<string>();
  487. sqlWhere = $" WHERE {sqlWhere}";
  488. string sqlSch = $"SELECT c.id, c.name, c.region, c.province, c.city, c.dist FROM c {sqlWhere} ";
  489. ///實體校
  490. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  491. {
  492. string schId = item.GetProperty("id").ToString();
  493. string schName = item.GetProperty("name").ToString();
  494. string geoName = item.GetProperty(groupKey).ToString();
  495. if (groupKey.Equals("city") || groupKey.Equals("province"))
  496. {
  497. if (geoName.Equals("荆州市")) geoName = "荆州市"; //例外處理
  498. else comeRemoveStr.ForEach(c => { geoName = geoName.Replace(c, ""); }); //常規處理
  499. }
  500. string geoId = (!string.IsNullOrWhiteSpace(geoName)) ? geoIdNameDic.FirstOrDefault(g => g.Value.Contains(geoName)).Key : string.Empty;
  501. if (!schGeoDic.ContainsKey(schId))
  502. {
  503. schGeoDic.Add(schId, geoId);
  504. schNameDic.Add(schId, schName);
  505. }
  506. if (!teacherCodes.Contains($"Teacher-{schId}"))
  507. {
  508. teacherCodes.Add($"Teacher-{schId}");
  509. }
  510. }
  511. ///虛擬校
  512. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"VirtualBase") }))
  513. {
  514. string schId = item.GetProperty("id").ToString();
  515. string schName = item.GetProperty("name").ToString();
  516. string geoName = item.GetProperty(groupKey).ToString();
  517. if (groupKey.Equals("city") || groupKey.Equals("province"))
  518. {
  519. if (geoName.Equals("荆州市")) geoName = "荆州市"; //例外處理
  520. else comeRemoveStr.ForEach(c => { geoName = geoName.Replace(c, ""); }); //常規處理
  521. }
  522. string geoId = (!string.IsNullOrWhiteSpace(geoName)) ? geoIdNameDic.FirstOrDefault(g => g.Value.Contains(geoName)).Key : string.Empty;
  523. if (!schGeoDic.ContainsKey(schId))
  524. {
  525. schGeoDic.Add(schId, geoId);
  526. schNameDic.Add(schId, schName);
  527. }
  528. }
  529. //取得學校教師數
  530. string sqlTch = $"SELECT REPLACE(c.code, 'Teacher-', '') as schoolId, COUNT(c.id) AS tchCnt FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code) GROUP BY c.code";
  531. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  532. {
  533. string schId = item.GetProperty("schoolId").ToString();
  534. int tchCnt = item.GetProperty("tchCnt").GetInt32();
  535. schTeacherCntDic.Add(schId, tchCnt);
  536. }
  537. }
  538. //資料整理1 有教師則記入
  539. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  540. {
  541. string schId = item.Key;
  542. int tchCnt = item.Value;
  543. string geoId = schGeoDic[schId];
  544. AreaInfo geoInfo = geoInfos.Where(g => g.id.Equals(geoId)).FirstOrDefault();
  545. if (geoInfo == null)
  546. {
  547. AreaInfo geoInfoCrt = new AreaInfo();
  548. geoInfoCrt.id = (groupKey.Equals("city") || groupKey.Equals("province")) ? geoId : schId;
  549. geoInfoCrt.name = (_option.Location.Contains("Global")) ? "無法取得名稱" : "无法取得名称";
  550. if(groupKey.Equals("city") || groupKey.Equals("province"))
  551. {
  552. if(!string.IsNullOrWhiteSpace(geoId) && geoIdNameDic.ContainsKey(geoId))
  553. {
  554. geoInfoCrt.name = geoIdNameDic[geoId];
  555. }
  556. }
  557. else if(schNameDic.ContainsKey(schId))
  558. {
  559. geoInfoCrt.name = schNameDic[schId];
  560. }
  561. geoInfos.Add(geoInfoCrt);
  562. geoInfo = geoInfos.Where(g => g.id.Equals(geoInfoCrt.id)).FirstOrDefault();
  563. }
  564. geoInfo.scCnt++;
  565. geoInfo.tchCnt += tchCnt;
  566. if (showSchool && (groupKey.Equals("city") || groupKey.Equals("province")))
  567. {
  568. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  569. geoInfo.schools.Add(sch);
  570. }
  571. }
  572. //資料整理2 移除無學校學區
  573. var result = geoInfos.Where(a => a.scCnt > 0).ToList();
  574. if (groupKey.Equals("name")) groupKey = "school";
  575. return Ok(new { state = 200, dataType = groupKey, data = result });
  576. }
  577. /// <summary>
  578. /// 取得教育機構所屬的學校或TMID
  579. /// </summary>
  580. /// <param name="jsonElement"></param>
  581. /// <returns></returns>
  582. [HttpPost("get-units")]
  583. #if !DEBUG
  584. [Authorize(Roles = "IES")]
  585. [AuthToken(Roles = "admin")]
  586. #endif
  587. public async Task<IActionResult> GetUnitTypes(JsonElement jsonElement)
  588. {
  589. var cosmosClient = _azureCosmos.GetCosmosClient();
  590. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  591. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : string.Empty; //教育機構類型 1:基礎教育機構(K-小學) 2:中等教育機構(國中、高中/職) 3:高等教育機構(大學、研究所) 4:其他
  592. bool showSchool = (jsonElement.TryGetProperty("showSchool", out JsonElement _showSchool)) ? _showSchool.GetBoolean() : false; //是否列出學校
  593. //檢索類型轉換
  594. string iesSql = "SELECT c.id, c.name, c.type FROM c WHERE 1=1 ";
  595. string iesWhere = string.Empty;
  596. //IES學校ID取得、學校類型取得
  597. List<string> iesSchIds = new List<string>();
  598. Dictionary<string, string> schTypeDic = new Dictionary<string, string>(); //IES5學校ID與學校類型對照表
  599. Dictionary<string, string> schNameDic = new Dictionary<string, string>(); //IES5學校ID與學校名稱
  600. List<string> teacherCodes = new List<string>(); //用來取得老師資料的分區鍵
  601. string sqlSch = $"{iesSql}{iesWhere}";
  602. ///實體校
  603. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  604. {
  605. string schId = item.GetProperty("id").ToString();
  606. string schName = item.GetProperty("name").ToString();
  607. int schType = item.GetProperty("type").GetInt32();
  608. iesSchIds.Add(schId);
  609. if (!schTypeDic.ContainsKey(schId)) schTypeDic.Add(schId, schType.ToString());
  610. if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
  611. }
  612. //Core 篩選取得的學校、學校類型取得
  613. string coreSql = "SELECT c.shortCode, c.unitType FROM c";
  614. string coreWhere = $" WHERE 1=1 AND ARRAY_CONTAINS({JsonSerializer.Serialize(iesSchIds)}, c.shortCode) ";
  615. Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
  616. string sqlCore = $"{coreSql}{coreWhere}";
  617. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  618. {
  619. string shortCode = item.GetProperty("shortCode").ToString();
  620. string unitType = item.GetProperty("unitType").ToString();
  621. if (!teacherCodes.Contains($"Teacher-{shortCode}")) teacherCodes.Add($"Teacher-{shortCode}");
  622. if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
  623. }
  624. //IES學校數及老師數取得
  625. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>(); //key: schoolId val:學校教師數
  626. string sqlTch = $"SELECT REPLACE(c.code, 'Teacher-', '') as schoolId, COUNT(c.id) AS tchCnt FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code) GROUP BY c.code";
  627. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  628. {
  629. string schId = item.GetProperty("schoolId").ToString();
  630. int tchCnt = item.GetProperty("tchCnt").GetInt32();
  631. schTeacherCntDic.Add(schId, tchCnt);
  632. }
  633. //資料整理1 有教師則記入
  634. List<AreaInfo> unitInfos = new();
  635. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  636. {
  637. string schId = item.Key;
  638. int tchCnt = item.Value;
  639. string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
  640. string iesUnitType = (schTypeDic.ContainsKey(schId)) ? schTypeDic[schId] : string.Empty;
  641. string unitTypeF = string.Empty; //機構類型(最終判斷)
  642. if (!string.IsNullOrWhiteSpace(coreUnitType))
  643. {
  644. switch (coreUnitType)
  645. {
  646. case "1": //基礎教育機構
  647. case "8": //學前教育
  648. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  649. break;
  650. case "2": //中等教育機構
  651. unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
  652. break;
  653. case "3": //高等教育機構
  654. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  655. break;
  656. case "4": //政府單位機構
  657. case "5": //NGO機構
  658. case "6": //企業機構
  659. case "7": //其他
  660. case "9": //特殊教育
  661. unitTypeF = "4"; // => 其他
  662. break;
  663. }
  664. }
  665. else if (!string.IsNullOrWhiteSpace(iesUnitType))
  666. {
  667. switch (iesUnitType) //1 普教,2 高职教
  668. {
  669. case "1": //國教(K-12)
  670. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  671. break;
  672. case "2": //大專院校
  673. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  674. break;
  675. default: //未設定
  676. unitTypeF = "4"; // => 其他
  677. break;
  678. }
  679. }
  680. string lang = (_option.Location.Contains("China")) ? "zh_cn" : "zh_tw";
  681. Dictionary<string, string> unitNameDic = getSchoolUnitName(lang);
  682. string id = unitTypeF;
  683. string name = unitNameDic[id];
  684. AreaInfo unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
  685. if (unitInfo == null)
  686. {
  687. AreaInfo unitInfoCrt = new AreaInfo();
  688. unitInfoCrt.id = id;
  689. unitInfoCrt.name = name;
  690. unitInfos.Add(unitInfoCrt);
  691. unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
  692. }
  693. unitInfo.scCnt++;
  694. unitInfo.tchCnt += tchCnt;
  695. if (showSchool)
  696. {
  697. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  698. unitInfo.schools.Add(sch);
  699. }
  700. }
  701. if (!string.IsNullOrWhiteSpace(type))
  702. {
  703. unitInfos = unitInfos.Where(u => u.id.Equals(type)).ToList();
  704. }
  705. return Ok(new { state = 200, data = unitInfos });
  706. }
  707. /// <summary>
  708. /// (個別挑選)取得TMID資訊
  709. /// </summary>
  710. [HttpPost("get-tmidinfo")]
  711. #if !DEBUG
  712. [Authorize(Roles = "IES")]
  713. [AuthToken(Roles = "admin")]
  714. #endif
  715. public async Task<IActionResult> GetTmidInfo(GetTmidInfoParam target)
  716. {
  717. try
  718. {
  719. var storageClientCsv2 = _azureStorage.GetCloudTableClient(name: "CoreServiceV2"); //Storage CSV2
  720. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  721. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  722. var tablePointsClient = storageClientCsv2.GetTableReference("Points");
  723. //各項值取聯集或交集
  724. string modeToAll = !string.IsNullOrWhiteSpace(target.mode) ? target.mode : "and";
  725. string sqlSel = "SELECT c.id FROM c WHERE 1=1 ";
  726. //生成時間
  727. List<string> passTmidCrt = new List<string>();
  728. List<string> sqlWhereListBase = new List<string>();
  729. if (target.creatTime != null)
  730. {
  731. if (target.creatTime.start > 0) sqlWhereListBase.Add($" {target.creatTime.start} <= StringToNumber(c.id) ");
  732. if (target.creatTime.end > 0) sqlWhereListBase.Add($" StringToNumber(c.id) <= {target.creatTime.end} ");
  733. }
  734. ///SQL文生成
  735. bool useCrtFlg = false;
  736. string sqlWhereBase = string.Empty;
  737. foreach (string w in sqlWhereListBase)
  738. {
  739. useCrtFlg = true;
  740. sqlWhereBase += $" AND {w}";
  741. }
  742. if (!string.IsNullOrWhiteSpace(sqlWhereBase))
  743. {
  744. string sqlBase = $"{sqlSel}{sqlWhereBase}";
  745. await foreach (var item in cosmosClientCsv2
  746. .GetContainer("Core", "ID2")
  747. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBase, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  748. {
  749. string id = item.GetProperty("id").ToString();
  750. if (!passTmidCrt.Contains(id)) passTmidCrt.Add(id);
  751. }
  752. }
  753. //地理資訊 (base-ex)
  754. List<string> passTmidGeo = new List<string>();
  755. List<string> sqlWhereListEx = new List<string>();
  756. if (target.geo != null)
  757. {
  758. if (!string.IsNullOrWhiteSpace(target.geo.countryId)) sqlWhereListEx.Add($"c.country = '{target.geo.countryId}'");
  759. if (!string.IsNullOrWhiteSpace(target.geo.provinceId)) sqlWhereListEx.Add($"c.province = '{target.geo.provinceId}'");
  760. if (!string.IsNullOrWhiteSpace(target.geo.cityId)) sqlWhereListEx.Add($"c.city = '{target.geo.cityId}'");
  761. }
  762. ///SQL文生成
  763. bool useGeoFlg = false;
  764. string sqlWhereEx = string.Empty;
  765. foreach (string w in sqlWhereListEx)
  766. {
  767. useGeoFlg = true;
  768. sqlWhereEx += $" AND {w}";
  769. }
  770. if (!string.IsNullOrWhiteSpace(sqlWhereEx))
  771. {
  772. string sqlEx = $"{sqlSel}{sqlWhereEx}";
  773. await foreach (var item in cosmosClientCsv2
  774. .GetContainer("Core", "ID2")
  775. .GetItemQueryIteratorSql<JsonElement>(sqlEx, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
  776. {
  777. string id = item.GetProperty("id").ToString();
  778. if (!passTmidGeo.Contains(id)) passTmidGeo.Add(id);
  779. }
  780. }
  781. //使用產品 ARRAY_CONTAINS(['hiteach', 'hiteachcc', 'sokapp', 'sokrates', 'webirs'], c.type)
  782. bool usePrdFlg = false;
  783. List<string> passTmidPrd = new List<string>();
  784. var tmidProdDic = new Dictionary<string, List<string>>(); //各ID使用過的的產品List
  785. List<string> prodWhereList = new List<string>();
  786. if (target.product != null && target.product.id.Count > 0)
  787. {
  788. usePrdFlg = true;
  789. foreach (string prodCode in target.product.id)
  790. {
  791. prodWhereList.Add(prodCode);
  792. }
  793. }
  794. if (prodWhereList.Count > 0)
  795. {
  796. string sqlSelCross = "SELECT DISTINCT c.id, c.type FROM c ";
  797. string sqlWhereCross = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(prodWhereList)}, c.type)";
  798. string sqlCross = $"{sqlSelCross}{sqlWhereCross}";
  799. await foreach (var item in cosmosClientCsv2
  800. .GetContainer("Core", "ID2")
  801. .GetItemQueryIteratorSql<JsonElement>(sqlCross, requestOptions: null))
  802. {
  803. string id = item.GetProperty("id").ToString();
  804. string prod = item.GetProperty("type").ToString();
  805. if (!tmidProdDic.ContainsKey(id)) tmidProdDic.Add(id, new List<string>());
  806. tmidProdDic[id].Add(prod);
  807. }
  808. ///生成符合AndOr條件的TMID製作
  809. if (target.product.mode.Equals("and"))
  810. {
  811. foreach (var prodItem in tmidProdDic)
  812. {
  813. int hasProdCount = 0;
  814. string tmid = prodItem.Key;
  815. ///產品比對
  816. foreach (string prod in target.product.id)
  817. {
  818. if (prodItem.Value.Contains(prod)) hasProdCount++;
  819. }
  820. if (hasProdCount.Equals(target.product.id.Count))
  821. {
  822. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  823. }
  824. }
  825. }
  826. else if (target.product.mode.Equals("or"))
  827. {
  828. foreach (var prodItem in tmidProdDic)
  829. {
  830. int hasProdCount = 0;
  831. string tmid = prodItem.Key;
  832. ///產品比對
  833. foreach (string prod in target.product.id)
  834. {
  835. if (prodItem.Value.Contains(prod))
  836. {
  837. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  838. break;
  839. }
  840. }
  841. }
  842. }
  843. }
  844. //點數
  845. bool usePntFlg = false;
  846. List<string> passTmidPnt = new List<string>();
  847. string filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Points");
  848. string rkFilterCombine = string.Empty;
  849. if (target.point != null)
  850. {
  851. if (target.point.start > 0 || target.point.end > 0)
  852. {
  853. usePntFlg = true;
  854. if (target.point.start > 0)
  855. {
  856. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.GreaterThanOrEqual, Convert.ToInt32(target.point.start));
  857. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  858. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  859. }
  860. if (target.point.end > 0)
  861. {
  862. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.LessThanOrEqual, Convert.ToInt32(target.point.end));
  863. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  864. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  865. }
  866. filter = TableQuery.CombineFilters(filter, TableOperators.And, rkFilterCombine);
  867. TableQuery tableQuery = new TableQuery().Where(filter);
  868. var usersPoints = tablePointsClient.ExecuteQuery(tableQuery);
  869. if (usersPoints.Any())
  870. {
  871. foreach (DynamicTableEntity item in usersPoints)
  872. {
  873. string tmid = item.RowKey;
  874. if (!passTmidPnt.Contains(tmid)) passTmidPnt.Add(tmid);
  875. }
  876. }
  877. }
  878. }
  879. //學校
  880. bool useSchFlg = false;
  881. List<string> passTmidSch = new List<string>();
  882. if (target.school != null && target.school.Count > 0)
  883. {
  884. useSchFlg = true;
  885. List<string> schTeacherCodeList = target.school.Select(s => $"Teacher-{s}").ToList();
  886. string sqlWhereSch = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(schTeacherCodeList)}, c.code)";
  887. string sqlSch = $"{sqlSel}{sqlWhereSch}";
  888. await foreach (var item in cosmosClientIes
  889. .GetContainer(Constant.TEAMModelOS, Constant.School)
  890. .GetItemQueryIteratorSql<JsonElement>(sqlSch, requestOptions: null))
  891. {
  892. string id = item.GetProperty("id").ToString();
  893. if (!passTmidSch.Contains(id)) passTmidSch.Add(id);
  894. }
  895. }
  896. //TMID
  897. bool useTmidFlg = false;
  898. List<string> passTmidMid = new List<string>();
  899. if (target.tmid != null && target.tmid.Count > 0)
  900. {
  901. useTmidFlg = true;
  902. string sqlWhereTmid = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(target.tmid)}, c.id)";
  903. string sqlTmid = $"{sqlSel}{sqlWhereTmid}";
  904. await foreach (var item in cosmosClientCsv2
  905. .GetContainer("Core", "ID2")
  906. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlTmid, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  907. {
  908. string id = item.GetProperty("id").ToString();
  909. if (!passTmidMid.Contains(id)) passTmidMid.Add(id);
  910. }
  911. }
  912. //所有TMID做聯集交集整合
  913. List<string> passTmid = new List<string>(); //最終條件符合的TMID列表
  914. ///初始化
  915. if (passTmidCrt.Count > 0) passTmid = passTmidCrt;
  916. else if (passTmidGeo.Count > 0) passTmid = passTmidGeo;
  917. else if (passTmidPrd.Count > 0) passTmid = passTmidPrd;
  918. else if (passTmidPnt.Count > 0) passTmid = passTmidPnt;
  919. else if (passTmidSch.Count > 0) passTmid = passTmidSch;
  920. else if (passTmidMid.Count > 0) passTmid = passTmidMid;
  921. if (modeToAll.Equals("or")) //聯集
  922. {
  923. if (useCrtFlg) passTmid = passTmid.Union(passTmidCrt).ToList();
  924. if (useGeoFlg) passTmid = passTmid.Union(passTmidGeo).ToList();
  925. if (usePrdFlg) passTmid = passTmid.Union(passTmidPrd).ToList();
  926. if (usePntFlg) passTmid = passTmid.Union(passTmidPnt).ToList();
  927. if (useSchFlg) passTmid = passTmid.Union(passTmidSch).ToList();
  928. if (useTmidFlg) passTmid = passTmid.Union(passTmidMid).ToList();
  929. }
  930. else //交集
  931. {
  932. if (useCrtFlg) passTmid = passTmid.Intersect(passTmidCrt).ToList();
  933. if (useGeoFlg) passTmid = passTmid.Intersect(passTmidGeo).ToList();
  934. if (usePrdFlg) passTmid = passTmid.Intersect(passTmidPrd).ToList();
  935. if (usePntFlg) passTmid = passTmid.Intersect(passTmidPnt).ToList();
  936. if (useSchFlg) passTmid = passTmid.Intersect(passTmidSch).ToList();
  937. if (useTmidFlg) passTmid = passTmid.Intersect(passTmidMid).ToList();
  938. //if (useCrtFlg) passTmid = passTmid.Where(p => passTmidCrt.Contains(p)).ToList();
  939. //if (useGeoFlg) passTmid = passTmid.Where(p => passTmidGeo.Contains(p)).ToList();
  940. //if (usePrdFlg) passTmid = passTmid.Where(p => passTmidPrd.Contains(p)).ToList();
  941. //if (usePntFlg) passTmid = passTmid.Where(p => passTmidPnt.Contains(p)).ToList();
  942. //if (useSchFlg) passTmid = passTmid.Where(p => passTmidSch.Contains(p)).ToList();
  943. }
  944. //最終ID基本資訊取得
  945. List<IdName> result = new List<IdName>();
  946. string sqlBaseInfo = $"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(passTmid)}, c.id)";
  947. await foreach (var item in cosmosClientCsv2
  948. .GetContainer("Core", "ID2")
  949. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  950. {
  951. string id = item.GetProperty("id").ToString();
  952. string name = item.GetProperty("name").ToString();
  953. IdName resultRow = new IdName() { id = id, name = name };
  954. result.Add(resultRow);
  955. }
  956. return Ok(new { state = RespondCode.Ok, data = result });
  957. }
  958. catch (Exception ex)
  959. {
  960. return BadRequest(new { state = RespondCode.NotFound, data = new List<IdName>() });
  961. }
  962. }
  963. /// <summary>
  964. /// 寄發訊息API
  965. /// </summary>
  966. /// <param name="target"></param>
  967. /// <param name="type">發送類型</param>
  968. /// <param name="method">挑選方式</param>
  969. /// <param name="title">標題</param>
  970. /// <param name="body">內文</param>
  971. /// <param name="data">傳遞資料</param>
  972. /// <param name="action">傳遞動作</param>
  973. [HttpPost("send-message")]
  974. #if !DEBUG
  975. [Authorize(Roles = "IES")]
  976. [AuthToken(Roles = "admin")]
  977. #endif
  978. public async Task<IActionResult> SendMessage(JsonElement jsonElement)
  979. {
  980. SendMessageParam target = (jsonElement.TryGetProperty("target", out JsonElement _target)) ? _target.ToObject<SendMessageParam>() : null; //發送對象
  981. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.ToString() : string.Empty; //發送類型 mail:郵件、notify:端外、sms:簡訊
  982. string method = (jsonElement.TryGetProperty("method", out JsonElement _method)) ? _method.ToString() : string.Empty; //挑選方式 single:個別 multi:批次
  983. string title = (jsonElement.TryGetProperty("title", out JsonElement _title)) ? _title.ToString() : string.Empty; //標題
  984. string body = (jsonElement.TryGetProperty("body", out JsonElement _body)) ? _body.ToString() : string.Empty; //內文
  985. var dataParam = (jsonElement.TryGetProperty("data", out JsonElement _data)) ? _data : new JsonElement { };
  986. List<NotifyAction> action = (jsonElement.TryGetProperty("action", out JsonElement _action)) ? _action.ToObject<List<NotifyAction>>() : new List<NotifyAction>();
  987. if (target == null || string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(method) || string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(body)) return BadRequest();
  988. string eventKey = "bi-gen-notify";
  989. string eventId = $"{eventKey}_{_snowflakeId.NextId()}";
  990. string eventName = "BI send notification";
  991. DataInNotify data = new DataInNotify();
  992. if(dataParam.ValueKind != JsonValueKind.Undefined) data.value = dataParam;
  993. if (action.Count > 0) data.action = action;
  994. await SendMessageCore(target, type, method, title, body, data, eventId, eventName);
  995. return Ok(new { state = RespondCode.Ok });
  996. }
  997. ///寄發訊息核心邏輯
  998. private async Task<IActionResult> SendMessageCore(SendMessageParam target, string type, string method, string title, string body, DataInNotify data, string eventId = "", string eventName = "")
  999. {
  1000. #region target 內容例
  1001. //{
  1002. // "area":[
  1003. // "1234"
  1004. // ],
  1005. // "geo":[
  1006. // {
  1007. // "countryId":"TW",
  1008. // "provinceId":"",
  1009. // "cityId":"30",
  1010. // "type":"tmid"
  1011. // },
  1012. // {
  1013. // "countryId":"TW",
  1014. // "provinceId":"",
  1015. // "cityId":"30",
  1016. // "type":"school"
  1017. // }
  1018. // ],
  1019. // "unit":[
  1020. // "1"
  1021. // ],
  1022. // "school":[
  1023. // "1234"
  1024. // ],
  1025. // "tmid": [
  1026. // "1234"
  1027. // ]
  1028. //}
  1029. #endregion
  1030. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1031. List<string> tmids_area = await GetTmidByAreaId(target.area);
  1032. List<string> tmids_geo = await GetTmidByGeo(target.geo);
  1033. List<string> tmids_unit = await GetTmidByUnitId(target.unit);
  1034. List<string> tmids_school = await GetTmidBySchoolId(target.school);
  1035. List<string> tmids_direct = target.tmid;
  1036. List<string> tmids = new List<string>(); //聯集化
  1037. tmids = tmids.Union(tmids_area).ToList();
  1038. tmids = tmids.Union(tmids_geo).ToList();
  1039. tmids = tmids.Union(tmids_unit).ToList();
  1040. tmids = tmids.Union(tmids_school).ToList();
  1041. tmids = tmids.Union(tmids_direct).ToList();
  1042. tmids = tmids.Distinct().ToList(); //唯一化
  1043. //取得TMID資料
  1044. List<IdInfo> tmidInfos = new List<IdInfo>();
  1045. string sqlBaseInfo = $"SELECT c.id, c.name, c.mail, c.mobile FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(tmids)}, c.id)";
  1046. await foreach (var item in cosmosClientCsv2
  1047. .GetContainer("Core", "ID2")
  1048. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  1049. {
  1050. IdInfo idInfo = new IdInfo();
  1051. idInfo.id = item.GetProperty("id").ToString();
  1052. idInfo.name = item.GetProperty("name").ToString();
  1053. idInfo.mail = item.GetProperty("mail").ToString();
  1054. idInfo.mobile = item.GetProperty("mobile").ToString();
  1055. tmidInfos.Add(idInfo);
  1056. }
  1057. //寄發訊息
  1058. if (type.Equals("notify")) //端內外通知
  1059. {
  1060. List<string> tmIds = tmidInfos.Select(i => i.id).ToList();
  1061. HttpResponseMessage response = CallPushNotifyApi(tmIds, title, body, data, eventId, eventName);
  1062. var result = new { status = response.StatusCode, content = response.Content };
  1063. return Ok(new { state = RespondCode.Ok, result = result });
  1064. }
  1065. else if(type.Equals("mail")) //Email
  1066. {
  1067. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mail)).Select(i => i.id).ToList();
  1068. //呼叫Email API [未]
  1069. var result = new { };
  1070. return Ok(new { state = RespondCode.Ok, result = result });
  1071. }
  1072. else if (type.Equals("sms")) //短訊
  1073. {
  1074. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mobile)).Select(i => i.id).ToList();
  1075. //呼叫短訊API [未]
  1076. var result = new { };
  1077. return Ok(new { state = RespondCode.Ok, result = result });
  1078. }
  1079. return Ok(new { state = RespondCode.Ok, result = new { } });
  1080. }
  1081. //取得學區所屬學校教師
  1082. private async Task<List<string>> GetTmidByAreaId(List<string> areaIds)
  1083. {
  1084. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1085. //取得學校ID列表
  1086. List<string> schIds = new List<string>();
  1087. string sqlSch = $"SELECT c.id FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(areaIds)}, c.areaId)";
  1088. ///實體校
  1089. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  1090. {
  1091. string schId = item.GetProperty("id").ToString();
  1092. schIds.Add(schId);
  1093. }
  1094. List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1095. //取得學校教師ID列表
  1096. List<string> tmids = new List<string>();
  1097. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1098. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1099. {
  1100. string tmid = item.GetProperty("id").ToString();
  1101. tmids.Add(tmid);
  1102. }
  1103. return tmids;
  1104. }
  1105. //取得地理資訊所屬TMID
  1106. private async Task<List<string>> GetTmidByGeo(List<Geo> geos)
  1107. {
  1108. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1109. string sqlWhere = string.Empty;
  1110. List<string> sqlWhereOrList = new List<string>();
  1111. foreach (Geo geo in geos)
  1112. {
  1113. string sqlWhereRow = String.Empty;
  1114. if (!string.IsNullOrWhiteSpace(geo.countryId))
  1115. {
  1116. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1117. sqlWhereRow += $"c.country = '{geo.countryId}'";
  1118. }
  1119. if (!string.IsNullOrWhiteSpace(geo.provinceId))
  1120. {
  1121. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1122. sqlWhereRow += $"c.province = '{geo.provinceId}'";
  1123. }
  1124. if (!string.IsNullOrWhiteSpace(geo.cityId))
  1125. {
  1126. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1127. sqlWhereRow += $"c.city = '{geo.cityId}'";
  1128. }
  1129. if (!string.IsNullOrWhiteSpace(sqlWhereRow))
  1130. {
  1131. sqlWhereOrList.Add(sqlWhereRow);
  1132. }
  1133. }
  1134. if (sqlWhereOrList.Count > 0)
  1135. {
  1136. foreach (string sqlWhereOrRow in sqlWhereOrList)
  1137. {
  1138. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += " OR ";
  1139. sqlWhere += $"({sqlWhereOrRow})";
  1140. }
  1141. }
  1142. List<string> tmids = new List<string>();
  1143. if (!string.IsNullOrWhiteSpace(sqlWhere))
  1144. {
  1145. string sqlEx = $"SELECT DISTINCT c.id FROM c WHERE {sqlWhere}";
  1146. await foreach (var item in cosmosClientCsv2
  1147. .GetContainer("Core", "ID2")
  1148. .GetItemQueryIteratorSql<JsonElement>(sqlEx, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
  1149. {
  1150. string id = item.GetProperty("id").ToString();
  1151. tmids.Add(id);
  1152. }
  1153. }
  1154. return tmids;
  1155. }
  1156. //取得學校機構所屬學校教師
  1157. private async Task<List<string>> GetTmidByUnitId(List<string> units)
  1158. {
  1159. if (units.Count.Equals(0)) return new List<string>();
  1160. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1161. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  1162. //取得IES5學校ID
  1163. string iesSql = "SELECT c.id, c.type FROM c WHERE 1=1 ";
  1164. string iesWhere = string.Empty;
  1165. //IES學校ID取得、學校類型取得
  1166. List<string> iesSchIds = new List<string>();
  1167. Dictionary<string, string> schTypeDic = new Dictionary<string, string>(); //IES5學校ID與學校類型對照表
  1168. List<string> teacherCodes = new List<string>(); //用來取得老師資料的分區鍵
  1169. string sqlSch = $"{iesSql}{iesWhere}";
  1170. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  1171. {
  1172. string schId = item.GetProperty("id").ToString();
  1173. int schType = item.GetProperty("type").GetInt32();
  1174. iesSchIds.Add(schId);
  1175. if (!schTypeDic.ContainsKey(schId)) schTypeDic.Add(schId, schType.ToString());
  1176. }
  1177. //取得Core學校ID及類型
  1178. string coreSql = "SELECT c.shortCode, c.unitType FROM c";
  1179. string coreWhere = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(iesSchIds)}, c.shortCode) ";
  1180. string coreWhereUnittype = string.Empty;
  1181. if (units.Contains("1"))
  1182. {
  1183. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1184. coreWhereUnittype += $" ARRAY_CONTAINS(['1','8'], c.unitType) ";
  1185. }
  1186. if (units.Contains("2"))
  1187. {
  1188. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1189. coreWhereUnittype += $" c.unitType = '2' ";
  1190. }
  1191. if (units.Contains("3"))
  1192. {
  1193. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1194. coreWhereUnittype += $" c.unitType = '3' ";
  1195. }
  1196. if (units.Contains("4"))
  1197. {
  1198. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1199. coreWhereUnittype += $" ARRAY_CONTAINS(['4','5','6','7','9'], c.unitType) ";
  1200. }
  1201. if (!string.IsNullOrWhiteSpace(coreWhereUnittype))
  1202. {
  1203. coreWhere += $" AND ({coreWhereUnittype})";
  1204. }
  1205. Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
  1206. string sqlCore = $"{coreSql}{coreWhere}";
  1207. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  1208. {
  1209. string shortCode = item.GetProperty("shortCode").ToString();
  1210. string unitType = item.GetProperty("unitType").ToString();
  1211. if (!teacherCodes.Contains($"Teacher-{shortCode}")) teacherCodes.Add($"Teacher-{shortCode}");
  1212. if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
  1213. }
  1214. //學校類型轉換
  1215. Dictionary<string, string> finalSchUnitTypeDic = new Dictionary<string, string>();
  1216. foreach (KeyValuePair<string, string> item in coreSchUnitTypeDic)
  1217. {
  1218. string schId = item.Key;
  1219. string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
  1220. string iesUnitType = (schTypeDic.ContainsKey(schId)) ? schTypeDic[schId] : string.Empty;
  1221. string unitTypeF = string.Empty; //機構類型(最終判斷)
  1222. if (!string.IsNullOrWhiteSpace(coreUnitType))
  1223. {
  1224. switch (coreUnitType)
  1225. {
  1226. case "1": //基礎教育機構
  1227. case "8": //學前教育
  1228. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  1229. break;
  1230. case "2": //中等教育機構
  1231. unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
  1232. break;
  1233. case "3": //高等教育機構
  1234. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  1235. break;
  1236. case "4": //政府單位機構
  1237. case "5": //NGO機構
  1238. case "6": //企業機構
  1239. case "7": //其他
  1240. case "9": //特殊教育
  1241. unitTypeF = "4"; // => 其他
  1242. break;
  1243. }
  1244. }
  1245. else if (!string.IsNullOrWhiteSpace(iesUnitType))
  1246. {
  1247. switch (iesUnitType) //1 普教,2 高职教
  1248. {
  1249. case "1": //國教(K-12)
  1250. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  1251. break;
  1252. case "2": //大專院校
  1253. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  1254. break;
  1255. default: //未設定
  1256. unitTypeF = "4"; // => 其他
  1257. break;
  1258. }
  1259. }
  1260. finalSchUnitTypeDic.Add(schId, unitTypeF);
  1261. }
  1262. //取得學校所屬老師TMID
  1263. teacherCodes = finalSchUnitTypeDic.Select(s => $"Teacher-{s.Key}").ToList();
  1264. List<string> tmids = new List<string>();
  1265. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1266. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1267. {
  1268. string tmid = item.GetProperty("id").ToString();
  1269. tmids.Add(tmid);
  1270. }
  1271. return tmids;
  1272. }
  1273. //取得學校所屬學校教師
  1274. private async Task<List<string>> GetTmidBySchoolId(List<string> schIds)
  1275. {
  1276. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1277. //取得學校ID列表
  1278. List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1279. //取得學校教師ID列表
  1280. List<string> tmids = new List<string>();
  1281. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1282. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1283. {
  1284. string tmid = item.GetProperty("id").ToString();
  1285. tmids.Add(tmid);
  1286. }
  1287. return tmids;
  1288. }
  1289. /// <summary>
  1290. /// 寄發端外通知
  1291. /// </summary>
  1292. /// <param name="tmIds"></param>
  1293. /// <param name="title"></param>
  1294. /// <param name="body"></param>
  1295. /// <param name="eventId"></param>
  1296. /// <param name="eventName"></param>
  1297. /// <param name="data"></param>
  1298. /// <returns></returns>
  1299. private HttpResponseMessage CallPushNotifyApi(List<string> tmIds, string title, string body, DataInNotify data, string eventId = "", string eventName = "")
  1300. {
  1301. NotifyData notify = new NotifyData();
  1302. notify.hubName = "hita5";
  1303. notify.sender = "IES"; //先填IES 若之後有需求要標BI 再修正
  1304. #if DEBUG //測試模式時限制TMID帳號,正式站佈署時不生效
  1305. List<string> filterTmid = new List<string>() { "1522758684", "1595321354" };
  1306. tmIds = tmIds.Intersect(filterTmid).ToList();
  1307. #endif
  1308. notify.tags = tmIds.Select(s => $"{s}_BI").ToList();
  1309. notify.title = title;
  1310. notify.body = body;
  1311. notify.eventId = eventId;
  1312. notify.eventName = eventName;
  1313. notify.data = data.ToJsonString();
  1314. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1315. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1316. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  1317. var client = _httpClient;
  1318. string sendSite = (_option.Location.Contains("China")) ? "China" : "Global";
  1319. var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, sendSite).Result;
  1320. if (client.DefaultRequestHeaders.Contains("Authorization"))
  1321. {
  1322. client.DefaultRequestHeaders.Remove("Authorization");
  1323. }
  1324. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  1325. HttpResponseMessage responseMessage = client.PostAsJsonAsync($"{url}/service/PushNotify", notify).Result;
  1326. return responseMessage;
  1327. }
  1328. /// <summary>
  1329. /// 取得TMID資訊 接收參數class
  1330. /// </summary>
  1331. public record GetTmidInfoParam
  1332. {
  1333. public string mode { get; set; } //and or
  1334. public StartEnd creatTime { get; set; }
  1335. public Geo geo { get; set; }
  1336. public Product product { get; set; }
  1337. public StartEnd point { get; set; }
  1338. public List<string> school { get; set; }
  1339. public List<string> tmid { get; set; }
  1340. public record StartEnd
  1341. {
  1342. public long start { get; set; }
  1343. public long end { get; set; }
  1344. }
  1345. public record Product
  1346. {
  1347. public string mode { get; set; } //and or
  1348. public List<string> id { get; set; } = new(); //產品類型
  1349. }
  1350. }
  1351. public record Geo //TMID用
  1352. {
  1353. public string countryId { get; set; }
  1354. public string provinceId { get; set; }
  1355. public string cityId { get; set; }
  1356. public string distId { get; set; }
  1357. //public string type { get; set; } //tmid、school
  1358. }
  1359. /// <summary>
  1360. /// 發送訊息核心邏輯 接收參數class
  1361. /// </summary>
  1362. public record SendMessageParam
  1363. {
  1364. public List<string> area { get; set; } = new(); //學區ID
  1365. public List<Geo> geo { get; set; } = new();
  1366. public List<string> unit { get; set; } = new(); //學校機構
  1367. public List<string> school { get; set; } = new(); //學校ID
  1368. public List<string> tmid { get; set; } = new(); //TMID
  1369. }
  1370. //取得學校機構ID及名稱
  1371. public Dictionary<string, string> getSchoolUnitName(string lang)
  1372. {
  1373. Dictionary<string, string> tw = new Dictionary<string, string>();
  1374. tw.Add("1", "基礎教育機構(K-小學)");
  1375. tw.Add("2", "中等教育機構(國中、高中/職)");
  1376. tw.Add("3", "高等教育機構(大學、研究所)");
  1377. tw.Add("4", "其他");
  1378. Dictionary<string, string> cn = new Dictionary<string, string>();
  1379. cn.Add("1", "基础教育机构(K-小学)");
  1380. cn.Add("2", "中等教育机构(初中、高中/职)");
  1381. cn.Add("3", "高等教育机构(大学、研究生院)");
  1382. cn.Add("4", "其他");
  1383. if(lang.Equals("zh-cn")) return cn;
  1384. else return tw;
  1385. }
  1386. /// <summary>
  1387. /// 學區、地理位置、機構類型 回傳信息
  1388. /// </summary>
  1389. public record AreaInfo
  1390. {
  1391. public string id { get; set; }
  1392. public string name { get; set; }
  1393. public int scCnt { get; set; } = 0;
  1394. public int tchCnt { get; set; } = 0;
  1395. public List<AreaSchoolInfo> schools { get; set; } = new();
  1396. }
  1397. /// <summary>
  1398. /// 學區附屬學校
  1399. /// </summary>
  1400. public record AreaSchoolInfo
  1401. {
  1402. public string id { get; set; }
  1403. public string name { get; set; }
  1404. public int tchCnt { get; set; } = 0;
  1405. }
  1406. /// <summary>
  1407. /// TMID個人積分
  1408. /// </summary>
  1409. private record TmidPoints
  1410. {
  1411. public int points { get; set; } = 0; //累積的點數(只加不減)
  1412. public int balance { get; set; } = 0; //可用的點數
  1413. public int level { get; set; } = 0; //等級
  1414. }
  1415. private record IdName
  1416. {
  1417. public string id { get; set; }
  1418. public string name { get; set; }
  1419. }
  1420. private record IdInfo : IdName
  1421. {
  1422. public string mail { get; set; }
  1423. public string mobile { get; set; }
  1424. }
  1425. /// <summary>
  1426. /// 呼叫端外通知API用 NotifyData.data格式
  1427. /// </summary>
  1428. private record DataInNotify
  1429. {
  1430. public object value { get; set; } = new();
  1431. public List<NotifyAction> action { get; set; } = new();
  1432. }
  1433. private record NotifyAction
  1434. {
  1435. public string type { get; set; } = "click";
  1436. public string label { get; set; }
  1437. public string url { get; set; }
  1438. }
  1439. //地區要去除的特殊字
  1440. public List<string> comeRemoveStr = new List<string>() { "省", "市", "区", "州", "县", "旗", "盟", "回族", "藏族", "羌族", "哈尼族", "彝族", "壮族", "苗族", "自治", "地區", "區", "縣" };
  1441. }
  1442. }