BINoticeController.cs 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. foreach (KeyValuePair<string, regionbase> item in regionData.city[countryId][countryId.ToLower()])
  410. {
  411. geoIdNameDic.Add(item.Value.code, item.Value.name);
  412. }
  413. }
  414. }
  415. else
  416. {
  417. foreach (KeyValuePair<string, regionbase> item in regionData.province[countryId])
  418. {
  419. geoIdNameDic.Add(item.Value.code, item.Value.name);
  420. }
  421. }
  422. }
  423. if (regionData.province.ContainsKey(countryId) && !string.IsNullOrWhiteSpace(provinceId))
  424. {
  425. provinceName = (regionData.province[countryId].ContainsKey(provinceId)) ? regionData.province[countryId][provinceId].name : string.Empty;
  426. foreach (KeyValuePair<string, regionbase> item in regionData.city[countryId][provinceId])
  427. {
  428. geoIdNameDic.Add(item.Value.code, item.Value.name);
  429. }
  430. }
  431. if (isGlobal)
  432. {
  433. if (regionData.city.ContainsKey(countryId))
  434. {
  435. if (countryId.ToLower().Equals("tw"))
  436. {
  437. if (!string.IsNullOrWhiteSpace(cityId) && regionData.city[countryId][countryId.ToLower()].ContainsKey(cityId))
  438. {
  439. cityName = regionData.city[countryId][countryId.ToLower()][cityId].name;
  440. }
  441. }
  442. }
  443. } else
  444. {
  445. if (regionData.city.ContainsKey(countryId) &&
  446. !string.IsNullOrWhiteSpace(provinceId) && regionData.city[countryId].ContainsKey(provinceId) &&
  447. !string.IsNullOrWhiteSpace(cityId) && regionData.city[countryId][provinceId].ContainsKey(cityId)
  448. )
  449. {
  450. cityName = regionData.city[countryId][provinceId][cityId].name;
  451. }
  452. }
  453. //SQL文製作
  454. string groupKey = string.Empty;
  455. string sqlWhere = string.Empty;
  456. if (!string.IsNullOrWhiteSpace(countryName))
  457. {
  458. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  459. comeRemoveStr.ForEach(c => { countryName = countryName.Replace(c, ""); });
  460. sqlWhere += $" CONTAINS(c.region, '{countryName}') ";
  461. groupKey = (isGlobal) ? "city" : "province";
  462. }
  463. if (!string.IsNullOrWhiteSpace(provinceName))
  464. {
  465. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  466. comeRemoveStr.ForEach(c => { provinceName = provinceName.Replace(c, ""); });
  467. sqlWhere += $" CONTAINS(c.province, '{provinceName}') ";
  468. groupKey = "city";
  469. }
  470. if (!string.IsNullOrWhiteSpace(cityName))
  471. {
  472. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += $" AND";
  473. comeRemoveStr.ForEach(c => { cityName = cityName.Replace(c, ""); });
  474. sqlWhere += $" CONTAINS(c.city, '{cityName}') ";
  475. groupKey = "name";
  476. }
  477. Dictionary<string, string> schGeoDic = new Dictionary<string, string>(); //key: schoolId val:統計的geoName
  478. Dictionary<string, string> schNameDic = new Dictionary<string, string>(); //key: schoolId val:學校名稱
  479. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>(); //key: schoolId val:學校教師數
  480. if (!string.IsNullOrWhiteSpace(sqlWhere))
  481. {
  482. //取得學校ID列表
  483. List<string> teacherCodes = new List<string>();
  484. sqlWhere = $" WHERE {sqlWhere}";
  485. string sqlSch = $"SELECT c.id, c.name, c.region, c.province, c.city, c.dist FROM c {sqlWhere} ";
  486. ///實體校
  487. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  488. {
  489. string schId = item.GetProperty("id").ToString();
  490. string schName = item.GetProperty("name").ToString();
  491. string geoName = item.GetProperty(groupKey).ToString();
  492. comeRemoveStr.ForEach(c => { geoName = geoName.Replace(c, ""); });
  493. if (!schGeoDic.ContainsKey(schId))
  494. {
  495. schGeoDic.Add(schId, geoName);
  496. schNameDic.Add(schId, schName);
  497. }
  498. if (!teacherCodes.Contains($"Teacher-{schId}"))
  499. {
  500. teacherCodes.Add($"Teacher-{schId}");
  501. }
  502. }
  503. ///虛擬校
  504. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"VirtualBase") }))
  505. {
  506. string schId = item.GetProperty("id").ToString();
  507. string schName = item.GetProperty("name").ToString();
  508. string geoId = item.GetProperty(groupKey).ToString();
  509. if (!schGeoDic.ContainsKey(schId))
  510. {
  511. schGeoDic.Add(schId, geoId);
  512. schNameDic.Add(schId, schName);
  513. }
  514. }
  515. //取得學校教師數
  516. 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";
  517. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  518. {
  519. string schId = item.GetProperty("schoolId").ToString();
  520. int tchCnt = item.GetProperty("tchCnt").GetInt32();
  521. schTeacherCntDic.Add(schId, tchCnt);
  522. }
  523. }
  524. //資料整理1 有教師則記入
  525. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  526. {
  527. string schId = item.Key;
  528. int tchCnt = item.Value;
  529. string geoName = schGeoDic[schId];
  530. AreaInfo geoInfo = geoInfos.Where(g => g.name.Equals(geoName)).FirstOrDefault();
  531. if (geoInfo == null)
  532. {
  533. AreaInfo geoInfoCrt = new AreaInfo();
  534. geoInfoCrt.id = (groupKey.Equals("city") || groupKey.Equals("province")) ? geoIdNameDic.FirstOrDefault(x => x.Value.Contains(geoName)).Key : schId;
  535. geoInfoCrt.name = geoName;
  536. geoInfos.Add(geoInfoCrt);
  537. geoInfo = geoInfos.Where(g => g.name.Equals(geoName)).FirstOrDefault();
  538. }
  539. geoInfo.scCnt++;
  540. geoInfo.tchCnt += tchCnt;
  541. if (showSchool && (groupKey.Equals("city") || groupKey.Equals("province")))
  542. {
  543. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  544. geoInfo.schools.Add(sch);
  545. }
  546. }
  547. //資料整理2 移除無學校學區
  548. var result = geoInfos.Where(a => a.scCnt > 0).ToList();
  549. if (groupKey.Equals("name")) groupKey = "school";
  550. return Ok(new { state = 200, dataType = groupKey, data = result });
  551. }
  552. /// <summary>
  553. /// 取得教育機構所屬的學校或TMID
  554. /// </summary>
  555. /// <param name="jsonElement"></param>
  556. /// <returns></returns>
  557. [HttpPost("get-units")]
  558. #if !DEBUG
  559. [Authorize(Roles = "IES")]
  560. [AuthToken(Roles = "admin")]
  561. #endif
  562. public async Task<IActionResult> GetUnitTypes(JsonElement jsonElement)
  563. {
  564. var cosmosClient = _azureCosmos.GetCosmosClient();
  565. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  566. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : string.Empty; //教育機構類型 1:基礎教育機構(K-小學) 2:中等教育機構(國中、高中/職) 3:高等教育機構(大學、研究所) 4:其他
  567. bool showSchool = (jsonElement.TryGetProperty("showSchool", out JsonElement _showSchool)) ? _showSchool.GetBoolean() : false; //是否列出學校
  568. //檢索類型轉換
  569. string iesSql = "SELECT c.id, c.name, c.type FROM c WHERE 1=1 ";
  570. string iesWhere = string.Empty;
  571. //IES學校ID取得、學校類型取得
  572. List<string> iesSchIds = new List<string>();
  573. Dictionary<string, string> schTypeDic = new Dictionary<string, string>(); //IES5學校ID與學校類型對照表
  574. Dictionary<string, string> schNameDic = new Dictionary<string, string>(); //IES5學校ID與學校名稱
  575. List<string> teacherCodes = new List<string>(); //用來取得老師資料的分區鍵
  576. string sqlSch = $"{iesSql}{iesWhere}";
  577. ///實體校
  578. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  579. {
  580. string schId = item.GetProperty("id").ToString();
  581. string schName = item.GetProperty("name").ToString();
  582. int schType = item.GetProperty("type").GetInt32();
  583. iesSchIds.Add(schId);
  584. if (!schTypeDic.ContainsKey(schId)) schTypeDic.Add(schId, schType.ToString());
  585. if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
  586. }
  587. //Core 篩選取得的學校、學校類型取得
  588. string coreSql = "SELECT c.shortCode, c.unitType FROM c";
  589. string coreWhere = $" WHERE 1=1 AND ARRAY_CONTAINS({JsonSerializer.Serialize(iesSchIds)}, c.shortCode) ";
  590. Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
  591. string sqlCore = $"{coreSql}{coreWhere}";
  592. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  593. {
  594. string shortCode = item.GetProperty("shortCode").ToString();
  595. string unitType = item.GetProperty("unitType").ToString();
  596. if (!teacherCodes.Contains($"Teacher-{shortCode}")) teacherCodes.Add($"Teacher-{shortCode}");
  597. if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
  598. }
  599. //IES學校數及老師數取得
  600. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>(); //key: schoolId val:學校教師數
  601. 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";
  602. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  603. {
  604. string schId = item.GetProperty("schoolId").ToString();
  605. int tchCnt = item.GetProperty("tchCnt").GetInt32();
  606. schTeacherCntDic.Add(schId, tchCnt);
  607. }
  608. //資料整理1 有教師則記入
  609. List<AreaInfo> unitInfos = new();
  610. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  611. {
  612. string schId = item.Key;
  613. int tchCnt = item.Value;
  614. string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
  615. string iesUnitType = (schTypeDic.ContainsKey(schId)) ? schTypeDic[schId] : string.Empty;
  616. string unitTypeF = string.Empty; //機構類型(最終判斷)
  617. if (!string.IsNullOrWhiteSpace(coreUnitType))
  618. {
  619. switch (coreUnitType)
  620. {
  621. case "1": //基礎教育機構
  622. case "8": //學前教育
  623. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  624. break;
  625. case "2": //中等教育機構
  626. unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
  627. break;
  628. case "3": //高等教育機構
  629. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  630. break;
  631. case "4": //政府單位機構
  632. case "5": //NGO機構
  633. case "6": //企業機構
  634. case "7": //其他
  635. case "9": //特殊教育
  636. unitTypeF = "4"; // => 其他
  637. break;
  638. }
  639. }
  640. else if (!string.IsNullOrWhiteSpace(iesUnitType))
  641. {
  642. switch (iesUnitType) //1 普教,2 高职教
  643. {
  644. case "1": //國教(K-12)
  645. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  646. break;
  647. case "2": //大專院校
  648. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  649. break;
  650. default: //未設定
  651. unitTypeF = "4"; // => 其他
  652. break;
  653. }
  654. }
  655. string lang = (_option.Location.Contains("China")) ? "zh_cn" : "zh_tw";
  656. Dictionary<string, string> unitNameDic = getSchoolUnitName(lang);
  657. string id = unitTypeF;
  658. string name = unitNameDic[id];
  659. AreaInfo unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
  660. if (unitInfo == null)
  661. {
  662. AreaInfo unitInfoCrt = new AreaInfo();
  663. unitInfoCrt.id = id;
  664. unitInfoCrt.name = name;
  665. unitInfos.Add(unitInfoCrt);
  666. unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
  667. }
  668. unitInfo.scCnt++;
  669. unitInfo.tchCnt += tchCnt;
  670. if (showSchool)
  671. {
  672. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  673. unitInfo.schools.Add(sch);
  674. }
  675. }
  676. if (!string.IsNullOrWhiteSpace(type))
  677. {
  678. unitInfos = unitInfos.Where(u => u.id.Equals(type)).ToList();
  679. }
  680. return Ok(new { state = 200, data = unitInfos });
  681. }
  682. /// <summary>
  683. /// (個別挑選)取得TMID資訊後繼送訊息
  684. /// </summary>
  685. [HttpPost("get-tmidinfo-single")]
  686. #if !DEBUG
  687. [Authorize(Roles = "IES")]
  688. [AuthToken(Roles = "admin")]
  689. #endif
  690. public async Task<IActionResult> GetTmidInfo(GetTmidInfoParam target)
  691. {
  692. try
  693. {
  694. var storageClientCsv2 = _azureStorage.GetCloudTableClient(name: "CoreServiceV2"); //Storage CSV2
  695. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  696. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  697. var tablePointsClient = storageClientCsv2.GetTableReference("Points");
  698. //各項值取聯集或交集
  699. string modeToAll = !string.IsNullOrWhiteSpace(target.mode) ? target.mode : "and";
  700. string sqlSel = "SELECT c.id FROM c WHERE 1=1 ";
  701. //生成時間
  702. List<string> passTmidCrt = new List<string>();
  703. List<string> sqlWhereListBase = new List<string>();
  704. if (target.creatTime != null)
  705. {
  706. if (target.creatTime.start > 0) sqlWhereListBase.Add($" {target.creatTime.start} <= StringToNumber(c.id) ");
  707. if (target.creatTime.end > 0) sqlWhereListBase.Add($" StringToNumber(c.id) <= {target.creatTime.end} ");
  708. }
  709. ///SQL文生成
  710. bool useCrtFlg = false;
  711. string sqlWhereBase = string.Empty;
  712. foreach (string w in sqlWhereListBase)
  713. {
  714. useCrtFlg = true;
  715. sqlWhereBase += $" AND {w}";
  716. }
  717. if (!string.IsNullOrWhiteSpace(sqlWhereBase))
  718. {
  719. string sqlBase = $"{sqlSel}{sqlWhereBase}";
  720. await foreach (var item in cosmosClientCsv2
  721. .GetContainer("Core", "ID2")
  722. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBase, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  723. {
  724. string id = item.GetProperty("id").ToString();
  725. if (!passTmidCrt.Contains(id)) passTmidCrt.Add(id);
  726. }
  727. }
  728. //地理資訊 (base-ex)
  729. List<string> passTmidGeo = new List<string>();
  730. List<string> sqlWhereListEx = new List<string>();
  731. if (target.geo != null)
  732. {
  733. if (!string.IsNullOrWhiteSpace(target.geo.countryId)) sqlWhereListEx.Add($"c.country = '{target.geo.countryId}'");
  734. if (!string.IsNullOrWhiteSpace(target.geo.provinceId)) sqlWhereListEx.Add($"c.province = '{target.geo.provinceId}'");
  735. if (!string.IsNullOrWhiteSpace(target.geo.cityId)) sqlWhereListEx.Add($"c.city = '{target.geo.cityId}'");
  736. }
  737. ///SQL文生成
  738. bool useGeoFlg = false;
  739. string sqlWhereEx = string.Empty;
  740. foreach (string w in sqlWhereListEx)
  741. {
  742. useGeoFlg = true;
  743. sqlWhereEx += $" AND {w}";
  744. }
  745. if (!string.IsNullOrWhiteSpace(sqlWhereEx))
  746. {
  747. string sqlEx = $"{sqlSel}{sqlWhereEx}";
  748. await foreach (var item in cosmosClientCsv2
  749. .GetContainer("Core", "ID2")
  750. .GetItemQueryIteratorSql<JsonElement>(sqlEx, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
  751. {
  752. string id = item.GetProperty("id").ToString();
  753. if (!passTmidGeo.Contains(id)) passTmidGeo.Add(id);
  754. }
  755. }
  756. //使用產品 ARRAY_CONTAINS(['hiteach', 'hiteachcc', 'sokapp', 'sokrates', 'webirs'], c.type)
  757. bool usePrdFlg = false;
  758. List<string> passTmidPrd = new List<string>();
  759. var tmidProdDic = new Dictionary<string, List<string>>(); //各ID使用過的的產品List
  760. List<string> prodWhereList = new List<string>();
  761. if (target.product != null && target.product.id.Count > 0)
  762. {
  763. usePrdFlg = true;
  764. foreach (string prodCode in target.product.id)
  765. {
  766. prodWhereList.Add(prodCode);
  767. }
  768. }
  769. if (prodWhereList.Count > 0)
  770. {
  771. string sqlSelCross = "SELECT DISTINCT c.id, c.type FROM c ";
  772. string sqlWhereCross = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(prodWhereList)}, c.type)";
  773. string sqlCross = $"{sqlSelCross}{sqlWhereCross}";
  774. await foreach (var item in cosmosClientCsv2
  775. .GetContainer("Core", "ID2")
  776. .GetItemQueryIteratorSql<JsonElement>(sqlCross, requestOptions: null))
  777. {
  778. string id = item.GetProperty("id").ToString();
  779. string prod = item.GetProperty("type").ToString();
  780. if (!tmidProdDic.ContainsKey(id)) tmidProdDic.Add(id, new List<string>());
  781. tmidProdDic[id].Add(prod);
  782. }
  783. ///生成符合AndOr條件的TMID製作
  784. if (target.product.mode.Equals("and"))
  785. {
  786. foreach (var prodItem in tmidProdDic)
  787. {
  788. int hasProdCount = 0;
  789. string tmid = prodItem.Key;
  790. ///產品比對
  791. foreach (string prod in target.product.id)
  792. {
  793. if (prodItem.Value.Contains(prod)) hasProdCount++;
  794. }
  795. if (hasProdCount.Equals(target.product.id.Count))
  796. {
  797. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  798. }
  799. }
  800. }
  801. else if (target.product.mode.Equals("or"))
  802. {
  803. foreach (var prodItem in tmidProdDic)
  804. {
  805. int hasProdCount = 0;
  806. string tmid = prodItem.Key;
  807. ///產品比對
  808. foreach (string prod in target.product.id)
  809. {
  810. if (prodItem.Value.Contains(prod))
  811. {
  812. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  813. break;
  814. }
  815. }
  816. }
  817. }
  818. }
  819. //點數
  820. bool usePntFlg = false;
  821. List<string> passTmidPnt = new List<string>();
  822. string filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Points");
  823. string rkFilterCombine = string.Empty;
  824. if (target.point != null)
  825. {
  826. if (target.point.start > 0 || target.point.end > 0)
  827. {
  828. usePntFlg = true;
  829. if (target.point.start > 0)
  830. {
  831. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.GreaterThanOrEqual, Convert.ToInt32(target.point.start));
  832. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  833. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  834. }
  835. if (target.point.end > 0)
  836. {
  837. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.LessThanOrEqual, Convert.ToInt32(target.point.end));
  838. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  839. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  840. }
  841. filter = TableQuery.CombineFilters(filter, TableOperators.And, rkFilterCombine);
  842. TableQuery tableQuery = new TableQuery().Where(filter);
  843. var usersPoints = tablePointsClient.ExecuteQuery(tableQuery);
  844. if (usersPoints.Any())
  845. {
  846. foreach (DynamicTableEntity item in usersPoints)
  847. {
  848. string tmid = item.RowKey;
  849. if (!passTmidPnt.Contains(tmid)) passTmidPnt.Add(tmid);
  850. }
  851. }
  852. }
  853. }
  854. //學校
  855. bool useSchFlg = false;
  856. List<string> passTmidSch = new List<string>();
  857. if (target.school != null && target.school.Count > 0)
  858. {
  859. useSchFlg = true;
  860. List<string> schTeacherCodeList = target.school.Select(s => $"Teacher-{s}").ToList();
  861. string sqlWhereSch = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(schTeacherCodeList)}, c.code)";
  862. string sqlSch = $"{sqlSel}{sqlWhereSch}";
  863. await foreach (var item in cosmosClientIes
  864. .GetContainer(Constant.TEAMModelOS, Constant.School)
  865. .GetItemQueryIteratorSql<JsonElement>(sqlSch, requestOptions: null))
  866. {
  867. string id = item.GetProperty("id").ToString();
  868. if (!passTmidSch.Contains(id)) passTmidSch.Add(id);
  869. }
  870. }
  871. //TMID
  872. bool useTmidFlg = false;
  873. List<string> passTmidMid = new List<string>();
  874. if (target.tmid != null && target.tmid.Count > 0)
  875. {
  876. useTmidFlg = true;
  877. string sqlWhereTmid = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(target.tmid)}, c.id)";
  878. string sqlTmid = $"{sqlSel}{sqlWhereTmid}";
  879. await foreach (var item in cosmosClientCsv2
  880. .GetContainer("Core", "ID2")
  881. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlTmid, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  882. {
  883. string id = item.GetProperty("id").ToString();
  884. if (!passTmidMid.Contains(id)) passTmidMid.Add(id);
  885. }
  886. }
  887. //所有TMID做聯集交集整合
  888. List<string> passTmid = new List<string>(); //最終條件符合的TMID列表
  889. ///初始化
  890. if (passTmidCrt.Count > 0) passTmid = passTmidCrt;
  891. else if (passTmidGeo.Count > 0) passTmid = passTmidGeo;
  892. else if (passTmidPrd.Count > 0) passTmid = passTmidPrd;
  893. else if (passTmidPnt.Count > 0) passTmid = passTmidPnt;
  894. else if (passTmidSch.Count > 0) passTmid = passTmidSch;
  895. else if (passTmidMid.Count > 0) passTmid = passTmidMid;
  896. if (modeToAll.Equals("or")) //聯集
  897. {
  898. if (useCrtFlg) passTmid = passTmid.Union(passTmidCrt).ToList();
  899. if (useGeoFlg) passTmid = passTmid.Union(passTmidGeo).ToList();
  900. if (usePrdFlg) passTmid = passTmid.Union(passTmidPrd).ToList();
  901. if (usePntFlg) passTmid = passTmid.Union(passTmidPnt).ToList();
  902. if (useSchFlg) passTmid = passTmid.Union(passTmidSch).ToList();
  903. if (useTmidFlg) passTmid = passTmid.Union(passTmidMid).ToList();
  904. }
  905. else //交集
  906. {
  907. if (useCrtFlg) passTmid = passTmid.Intersect(passTmidCrt).ToList();
  908. if (useGeoFlg) passTmid = passTmid.Intersect(passTmidGeo).ToList();
  909. if (usePrdFlg) passTmid = passTmid.Intersect(passTmidPrd).ToList();
  910. if (usePntFlg) passTmid = passTmid.Intersect(passTmidPnt).ToList();
  911. if (useSchFlg) passTmid = passTmid.Intersect(passTmidSch).ToList();
  912. if (useTmidFlg) passTmid = passTmid.Intersect(passTmidMid).ToList();
  913. //if (useCrtFlg) passTmid = passTmid.Where(p => passTmidCrt.Contains(p)).ToList();
  914. //if (useGeoFlg) passTmid = passTmid.Where(p => passTmidGeo.Contains(p)).ToList();
  915. //if (usePrdFlg) passTmid = passTmid.Where(p => passTmidPrd.Contains(p)).ToList();
  916. //if (usePntFlg) passTmid = passTmid.Where(p => passTmidPnt.Contains(p)).ToList();
  917. //if (useSchFlg) passTmid = passTmid.Where(p => passTmidSch.Contains(p)).ToList();
  918. }
  919. //最終ID基本資訊取得
  920. List<IdName> result = new List<IdName>();
  921. string sqlBaseInfo = $"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(passTmid)}, c.id)";
  922. await foreach (var item in cosmosClientCsv2
  923. .GetContainer("Core", "ID2")
  924. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  925. {
  926. string id = item.GetProperty("id").ToString();
  927. string name = item.GetProperty("name").ToString();
  928. IdName resultRow = new IdName() { id = id, name = name };
  929. result.Add(resultRow);
  930. }
  931. return Ok(new { state = RespondCode.Ok, data = result });
  932. }
  933. catch (Exception ex)
  934. {
  935. return BadRequest(new { state = RespondCode.NotFound, data = new List<IdName>() });
  936. }
  937. }
  938. /// <summary>
  939. /// 寄發訊息API
  940. /// </summary>
  941. /// <param name="target"></param>
  942. /// <param name="type">發送類型</param>
  943. /// <param name="method">挑選方式</param>
  944. /// <param name="title">標題</param>
  945. /// <param name="body">內文</param>
  946. /// <param name="data">傳遞資料</param>
  947. /// <param name="action">傳遞動作</param>
  948. [HttpPost("send-message")]
  949. #if !DEBUG
  950. [Authorize(Roles = "IES")]
  951. [AuthToken(Roles = "admin")]
  952. #endif
  953. public async Task<IActionResult> SendMessage(JsonElement jsonElement)
  954. {
  955. SendMessageParam target = (jsonElement.TryGetProperty("target", out JsonElement _target)) ? _target.ToObject<SendMessageParam>() : null; //發送對象
  956. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.ToString() : string.Empty; //發送類型 mail:郵件、notify:端外、sms:簡訊
  957. string method = (jsonElement.TryGetProperty("method", out JsonElement _method)) ? _method.ToString() : string.Empty; //挑選方式 single:個別 multi:批次
  958. string title = (jsonElement.TryGetProperty("title", out JsonElement _title)) ? _title.ToString() : string.Empty; //標題
  959. string body = (jsonElement.TryGetProperty("body", out JsonElement _body)) ? _body.ToString() : string.Empty; //內文
  960. var dataParam = (jsonElement.TryGetProperty("data", out JsonElement _data)) ? _data : new JsonElement { };
  961. List<NotifyAction> action = (jsonElement.TryGetProperty("action", out JsonElement _action)) ? _action.ToObject<List<NotifyAction>>() : new List<NotifyAction>();
  962. if (target == null || string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(method) || string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(body)) return BadRequest();
  963. string eventKey = "bi-gen-notify";
  964. string eventId = $"{eventKey}_{_snowflakeId.NextId()}";
  965. string eventName = "BI send notification";
  966. DataInNotify data = new DataInNotify();
  967. if(dataParam.ValueKind != JsonValueKind.Undefined) data.value = dataParam;
  968. if (action.Count > 0) data.action = action;
  969. await SendMessageCore(target, type, method, title, body, data, eventId, eventName);
  970. return Ok(new { state = RespondCode.Ok });
  971. }
  972. ///寄發訊息核心邏輯
  973. private async Task<IActionResult> SendMessageCore(SendMessageParam target, string type, string method, string title, string body, DataInNotify data, string eventId = "", string eventName = "")
  974. {
  975. #region target 內容例
  976. //{
  977. // "area":[
  978. // "1234"
  979. // ],
  980. // "geo":[
  981. // {
  982. // "countryId":"TW",
  983. // "provinceId":"",
  984. // "cityId":"30",
  985. // "type":"tmid"
  986. // },
  987. // {
  988. // "countryId":"TW",
  989. // "provinceId":"",
  990. // "cityId":"30",
  991. // "type":"school"
  992. // }
  993. // ],
  994. // "unit":[
  995. // "1"
  996. // ],
  997. // "school":[
  998. // "1234"
  999. // ],
  1000. // "tmid": [
  1001. // "1234"
  1002. // ]
  1003. //}
  1004. #endregion
  1005. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1006. List<string> tmids_area = await GetTmidByAreaId(target.area);
  1007. List<string> tmids_geo = await GetTmidByGeo(target.geo);
  1008. List<string> tmids_unit = await GetTmidByUnitId(target.unit);
  1009. List<string> tmids_school = await GetTmidBySchoolId(target.school);
  1010. List<string> tmids_direct = target.tmid;
  1011. List<string> tmids = new List<string>(); //聯集化
  1012. tmids = tmids.Union(tmids_area).ToList();
  1013. tmids = tmids.Union(tmids_geo).ToList();
  1014. tmids = tmids.Union(tmids_unit).ToList();
  1015. tmids = tmids.Union(tmids_school).ToList();
  1016. tmids = tmids.Union(tmids_direct).ToList();
  1017. tmids = tmids.Distinct().ToList(); //唯一化
  1018. //取得TMID資料
  1019. List<IdInfo> tmidInfos = new List<IdInfo>();
  1020. string sqlBaseInfo = $"SELECT c.id, c.name, c.mail, c.mobile FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(tmids)}, c.id)";
  1021. await foreach (var item in cosmosClientCsv2
  1022. .GetContainer("Core", "ID2")
  1023. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  1024. {
  1025. IdInfo idInfo = new IdInfo();
  1026. idInfo.id = item.GetProperty("id").ToString();
  1027. idInfo.name = item.GetProperty("name").ToString();
  1028. idInfo.mail = item.GetProperty("mail").ToString();
  1029. idInfo.mobile = item.GetProperty("mobile").ToString();
  1030. tmidInfos.Add(idInfo);
  1031. }
  1032. //寄發訊息
  1033. if (type.Equals("notify")) //端內外通知
  1034. {
  1035. List<string> tmIds = tmidInfos.Select(i => i.id).ToList();
  1036. HttpResponseMessage response = CallPushNotifyApi(tmIds, title, body, data, eventId, eventName);
  1037. var result = new { status = response.StatusCode, content = response.Content };
  1038. return Ok(new { state = RespondCode.Ok, result = result });
  1039. }
  1040. else if(type.Equals("mail")) //Email
  1041. {
  1042. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mail)).Select(i => i.id).ToList();
  1043. //呼叫Email API [未]
  1044. var result = new { };
  1045. return Ok(new { state = RespondCode.Ok, result = result });
  1046. }
  1047. else if (type.Equals("sms")) //短訊
  1048. {
  1049. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mobile)).Select(i => i.id).ToList();
  1050. //呼叫短訊API [未]
  1051. var result = new { };
  1052. return Ok(new { state = RespondCode.Ok, result = result });
  1053. }
  1054. return Ok(new { state = RespondCode.Ok, result = new { } });
  1055. }
  1056. //取得學區所屬學校教師
  1057. private async Task<List<string>> GetTmidByAreaId(List<string> areaIds)
  1058. {
  1059. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1060. //取得學校ID列表
  1061. List<string> schIds = new List<string>();
  1062. string sqlSch = $"SELECT c.id FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(areaIds)}, c.areaId)";
  1063. ///實體校
  1064. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  1065. {
  1066. string schId = item.GetProperty("id").ToString();
  1067. schIds.Add(schId);
  1068. }
  1069. List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1070. //取得學校教師ID列表
  1071. List<string> tmids = new List<string>();
  1072. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1073. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1074. {
  1075. string tmid = item.GetProperty("id").ToString();
  1076. tmids.Add(tmid);
  1077. }
  1078. return tmids;
  1079. }
  1080. //取得地理資訊所屬TMID
  1081. private async Task<List<string>> GetTmidByGeo(List<Geo> geos)
  1082. {
  1083. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1084. string sqlWhere = string.Empty;
  1085. List<string> sqlWhereOrList = new List<string>();
  1086. foreach (Geo geo in geos)
  1087. {
  1088. string sqlWhereRow = String.Empty;
  1089. if (!string.IsNullOrWhiteSpace(geo.countryId))
  1090. {
  1091. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1092. sqlWhereRow += $"c.country = '{geo.countryId}'";
  1093. }
  1094. if (!string.IsNullOrWhiteSpace(geo.provinceId))
  1095. {
  1096. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1097. sqlWhereRow += $"c.province = '{geo.provinceId}'";
  1098. }
  1099. if (!string.IsNullOrWhiteSpace(geo.cityId))
  1100. {
  1101. if (!string.IsNullOrWhiteSpace(sqlWhereRow)) sqlWhereRow += " AND ";
  1102. sqlWhereRow += $"c.city = '{geo.cityId}'";
  1103. }
  1104. if (!string.IsNullOrWhiteSpace(sqlWhereRow))
  1105. {
  1106. sqlWhereOrList.Add(sqlWhereRow);
  1107. }
  1108. }
  1109. if (sqlWhereOrList.Count > 0)
  1110. {
  1111. foreach (string sqlWhereOrRow in sqlWhereOrList)
  1112. {
  1113. if (!string.IsNullOrWhiteSpace(sqlWhere)) sqlWhere += " OR ";
  1114. sqlWhere += $"({sqlWhereOrRow})";
  1115. }
  1116. }
  1117. List<string> tmids = new List<string>();
  1118. if (!string.IsNullOrWhiteSpace(sqlWhere))
  1119. {
  1120. string sqlEx = $"SELECT DISTINCT c.id FROM c WHERE {sqlWhere}";
  1121. await foreach (var item in cosmosClientCsv2
  1122. .GetContainer("Core", "ID2")
  1123. .GetItemQueryIteratorSql<JsonElement>(sqlEx, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
  1124. {
  1125. string id = item.GetProperty("id").ToString();
  1126. tmids.Add(id);
  1127. }
  1128. }
  1129. return tmids;
  1130. }
  1131. //取得學校機構所屬學校教師
  1132. private async Task<List<string>> GetTmidByUnitId(List<string> units)
  1133. {
  1134. if (units.Count.Equals(0)) return new List<string>();
  1135. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1136. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  1137. //取得IES5學校ID
  1138. string iesSql = "SELECT c.id, c.type FROM c WHERE 1=1 ";
  1139. string iesWhere = string.Empty;
  1140. //IES學校ID取得、學校類型取得
  1141. List<string> iesSchIds = new List<string>();
  1142. Dictionary<string, string> schTypeDic = new Dictionary<string, string>(); //IES5學校ID與學校類型對照表
  1143. List<string> teacherCodes = new List<string>(); //用來取得老師資料的分區鍵
  1144. string sqlSch = $"{iesSql}{iesWhere}";
  1145. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  1146. {
  1147. string schId = item.GetProperty("id").ToString();
  1148. int schType = item.GetProperty("type").GetInt32();
  1149. iesSchIds.Add(schId);
  1150. if (!schTypeDic.ContainsKey(schId)) schTypeDic.Add(schId, schType.ToString());
  1151. }
  1152. //取得Core學校ID及類型
  1153. string coreSql = "SELECT c.shortCode, c.unitType FROM c";
  1154. string coreWhere = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(iesSchIds)}, c.shortCode) ";
  1155. string coreWhereUnittype = string.Empty;
  1156. if (units.Contains("1"))
  1157. {
  1158. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1159. coreWhereUnittype += $" ARRAY_CONTAINS(['1','8'], c.unitType) ";
  1160. }
  1161. if (units.Contains("2"))
  1162. {
  1163. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1164. coreWhereUnittype += $" c.unitType = '2' ";
  1165. }
  1166. if (units.Contains("3"))
  1167. {
  1168. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1169. coreWhereUnittype += $" c.unitType = '3' ";
  1170. }
  1171. if (units.Contains("4"))
  1172. {
  1173. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1174. coreWhereUnittype += $" ARRAY_CONTAINS(['4','5','6','7','9'], c.unitType) ";
  1175. }
  1176. if (!string.IsNullOrWhiteSpace(coreWhereUnittype))
  1177. {
  1178. coreWhere += $" AND ({coreWhereUnittype})";
  1179. }
  1180. Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
  1181. string sqlCore = $"{coreSql}{coreWhere}";
  1182. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  1183. {
  1184. string shortCode = item.GetProperty("shortCode").ToString();
  1185. string unitType = item.GetProperty("unitType").ToString();
  1186. if (!teacherCodes.Contains($"Teacher-{shortCode}")) teacherCodes.Add($"Teacher-{shortCode}");
  1187. if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
  1188. }
  1189. //學校類型轉換
  1190. Dictionary<string, string> finalSchUnitTypeDic = new Dictionary<string, string>();
  1191. foreach (KeyValuePair<string, string> item in coreSchUnitTypeDic)
  1192. {
  1193. string schId = item.Key;
  1194. string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
  1195. string iesUnitType = (schTypeDic.ContainsKey(schId)) ? schTypeDic[schId] : string.Empty;
  1196. string unitTypeF = string.Empty; //機構類型(最終判斷)
  1197. if (!string.IsNullOrWhiteSpace(coreUnitType))
  1198. {
  1199. switch (coreUnitType)
  1200. {
  1201. case "1": //基礎教育機構
  1202. case "8": //學前教育
  1203. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  1204. break;
  1205. case "2": //中等教育機構
  1206. unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
  1207. break;
  1208. case "3": //高等教育機構
  1209. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  1210. break;
  1211. case "4": //政府單位機構
  1212. case "5": //NGO機構
  1213. case "6": //企業機構
  1214. case "7": //其他
  1215. case "9": //特殊教育
  1216. unitTypeF = "4"; // => 其他
  1217. break;
  1218. }
  1219. }
  1220. else if (!string.IsNullOrWhiteSpace(iesUnitType))
  1221. {
  1222. switch (iesUnitType) //1 普教,2 高职教
  1223. {
  1224. case "1": //國教(K-12)
  1225. unitTypeF = "1"; // => 基礎教育機構(K-小學)
  1226. break;
  1227. case "2": //大專院校
  1228. unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  1229. break;
  1230. default: //未設定
  1231. unitTypeF = "4"; // => 其他
  1232. break;
  1233. }
  1234. }
  1235. finalSchUnitTypeDic.Add(schId, unitTypeF);
  1236. }
  1237. //取得學校所屬老師TMID
  1238. teacherCodes = finalSchUnitTypeDic.Select(s => $"Teacher-{s.Key}").ToList();
  1239. List<string> tmids = new List<string>();
  1240. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1241. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1242. {
  1243. string tmid = item.GetProperty("id").ToString();
  1244. tmids.Add(tmid);
  1245. }
  1246. return tmids;
  1247. }
  1248. //取得學校所屬學校教師
  1249. private async Task<List<string>> GetTmidBySchoolId(List<string> schIds)
  1250. {
  1251. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1252. //取得學校ID列表
  1253. List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1254. //取得學校教師ID列表
  1255. List<string> tmids = new List<string>();
  1256. string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1257. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1258. {
  1259. string tmid = item.GetProperty("id").ToString();
  1260. tmids.Add(tmid);
  1261. }
  1262. return tmids;
  1263. }
  1264. /// <summary>
  1265. /// 寄發端外通知
  1266. /// </summary>
  1267. /// <param name="tmIds"></param>
  1268. /// <param name="title"></param>
  1269. /// <param name="body"></param>
  1270. /// <param name="eventId"></param>
  1271. /// <param name="eventName"></param>
  1272. /// <param name="data"></param>
  1273. /// <returns></returns>
  1274. private HttpResponseMessage CallPushNotifyApi(List<string> tmIds, string title, string body, DataInNotify data, string eventId = "", string eventName = "")
  1275. {
  1276. NotifyData notify = new NotifyData();
  1277. notify.hubName = "hita5";
  1278. notify.sender = "IES"; //先填IES 若之後有需求要標BI 再修正
  1279. #if DEBUG //測試模式時限制TMID帳號,正式站佈署時不生效
  1280. List<string> filterTmid = new List<string>() { "1522758684", "1595321354" };
  1281. tmIds = tmIds.Intersect(filterTmid).ToList();
  1282. #endif
  1283. notify.tags = tmIds.Select(s => $"{s}_BI").ToList();
  1284. notify.title = title;
  1285. notify.body = body;
  1286. notify.eventId = eventId;
  1287. notify.eventName = eventName;
  1288. notify.data = data.ToJsonString();
  1289. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1290. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1291. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  1292. var client = _httpClient;
  1293. string sendSite = (_option.Location.Contains("China")) ? "China" : "Global";
  1294. var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, sendSite).Result;
  1295. if (client.DefaultRequestHeaders.Contains("Authorization"))
  1296. {
  1297. client.DefaultRequestHeaders.Remove("Authorization");
  1298. }
  1299. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  1300. HttpResponseMessage responseMessage = client.PostAsJsonAsync($"{url}/service/PushNotify", notify).Result;
  1301. return responseMessage;
  1302. }
  1303. /// <summary>
  1304. /// 取得TMID資訊 接收參數class
  1305. /// </summary>
  1306. public record GetTmidInfoParam
  1307. {
  1308. public string mode { get; set; } //and or
  1309. public StartEnd creatTime { get; set; }
  1310. public Geo geo { get; set; }
  1311. public Product product { get; set; }
  1312. public StartEnd point { get; set; }
  1313. public List<string> school { get; set; }
  1314. public List<string> tmid { get; set; }
  1315. public record StartEnd
  1316. {
  1317. public long start { get; set; }
  1318. public long end { get; set; }
  1319. }
  1320. public record Product
  1321. {
  1322. public string mode { get; set; } //and or
  1323. public List<string> id { get; set; } = new(); //產品類型
  1324. }
  1325. }
  1326. public record Geo
  1327. {
  1328. public string countryId { get; set; }
  1329. public string provinceId { get; set; }
  1330. public string cityId { get; set; }
  1331. public string distId { get; set; }
  1332. public string type { get; set; } //tmid、school
  1333. }
  1334. /// <summary>
  1335. /// 發送訊息核心邏輯 接收參數class
  1336. /// </summary>
  1337. public record SendMessageParam
  1338. {
  1339. public List<string> area { get; set; } = new(); //學區ID
  1340. public List<Geo> geo { get; set; } = new();
  1341. public List<string> unit { get; set; } = new(); //學校機構
  1342. public List<string> school { get; set; } = new(); //學校ID
  1343. public List<string> tmid { get; set; } = new(); //TMID
  1344. }
  1345. //取得學校機構ID及名稱
  1346. public Dictionary<string, string> getSchoolUnitName(string lang)
  1347. {
  1348. Dictionary<string, string> tw = new Dictionary<string, string>();
  1349. tw.Add("1", "基礎教育機構(K-小學)");
  1350. tw.Add("2", "中等教育機構(國中、高中/職)");
  1351. tw.Add("3", "高等教育機構(大學、研究所)");
  1352. tw.Add("4", "其他");
  1353. Dictionary<string, string> cn = new Dictionary<string, string>();
  1354. cn.Add("1", "基础教育机构(K-小学)");
  1355. cn.Add("2", "中等教育机构(初中、高中/职)");
  1356. cn.Add("3", "高等教育机构(大学、研究生院)");
  1357. cn.Add("4", "其他");
  1358. if(lang.Equals("zh-cn")) return cn;
  1359. else return tw;
  1360. }
  1361. /// <summary>
  1362. /// 學區、地理位置、機構類型 回傳信息
  1363. /// </summary>
  1364. public record AreaInfo
  1365. {
  1366. public string id { get; set; }
  1367. public string name { get; set; }
  1368. public int scCnt { get; set; } = 0;
  1369. public int tchCnt { get; set; } = 0;
  1370. public List<AreaSchoolInfo> schools { get; set; } = new();
  1371. }
  1372. /// <summary>
  1373. /// 學區附屬學校
  1374. /// </summary>
  1375. public record AreaSchoolInfo
  1376. {
  1377. public string id { get; set; }
  1378. public string name { get; set; }
  1379. public int tchCnt { get; set; } = 0;
  1380. }
  1381. /// <summary>
  1382. /// TMID個人積分
  1383. /// </summary>
  1384. private record TmidPoints
  1385. {
  1386. public int points { get; set; } = 0; //累積的點數(只加不減)
  1387. public int balance { get; set; } = 0; //可用的點數
  1388. public int level { get; set; } = 0; //等級
  1389. }
  1390. private record IdName
  1391. {
  1392. public string id { get; set; }
  1393. public string name { get; set; }
  1394. }
  1395. private record IdInfo : IdName
  1396. {
  1397. public string mail { get; set; }
  1398. public string mobile { get; set; }
  1399. }
  1400. /// <summary>
  1401. /// 呼叫端外通知API用 NotifyData.data格式
  1402. /// </summary>
  1403. private record DataInNotify
  1404. {
  1405. public object value { get; set; } = new();
  1406. public List<NotifyAction> action { get; set; } = new();
  1407. }
  1408. private record NotifyAction
  1409. {
  1410. public string type { get; set; } = "click";
  1411. public string label { get; set; }
  1412. public string url { get; set; }
  1413. }
  1414. //地區要去除的特殊字
  1415. public List<string> comeRemoveStr = new List<string>() { "省", "市", "区", "州", "县", "旗", "盟", "自治", "地區", "區", "縣" };
  1416. }
  1417. }