BINoticeController.cs 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  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. using System.Text.RegularExpressions;
  38. using MathNet.Numerics.Distributions;
  39. using System.Drawing.Drawing2D;
  40. using Microsoft.Azure.Amqp.Framing;
  41. using TEAMModelOS.SDK.DI.IPIP;
  42. using Azure;
  43. using Microsoft.AspNetCore.Http.HttpResults;
  44. using System.Net;
  45. using System.Dynamic;
  46. namespace TEAMModelBI.Controllers.BICommon
  47. {
  48. [Route("notice")]
  49. [ApiController]
  50. public class BINoticeController : ControllerBase
  51. {
  52. private readonly AzureCosmosFactory _azureCosmos;
  53. private readonly DingDing _dingDing;
  54. private readonly Option _option;
  55. private readonly AzureStorageFactory _azureStorage;
  56. private readonly IConfiguration _configuration;
  57. private readonly AzureServiceBusFactory _serviceBus;
  58. private readonly IHttpClientFactory _http;
  59. private readonly CoreAPIHttpService _coreAPIHttpService;
  60. private readonly IWebHostEnvironment _environment; //读取文件
  61. private readonly HttpClient _httpClient;
  62. private readonly SnowflakeId _snowflakeId;
  63. 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)
  64. {
  65. _azureCosmos = azureCosmos;
  66. _dingDing = dingDing;
  67. _azureStorage = azureStorage;
  68. _option = option?.Value;
  69. _configuration = configuration;
  70. _serviceBus = serviceBus;
  71. _http = http;
  72. _coreAPIHttpService = coreAPIHttpService;
  73. _environment = hostingEnvironment;
  74. _httpClient = httpClient;
  75. _snowflakeId = snowflakeId;
  76. }
  77. /// <summary>
  78. /// 查询账户信息
  79. /// </summary>
  80. /// <param name="jsonElement"></param>
  81. /// <returns></returns>
  82. [AuthToken(Roles = "admin,rdc,assist,sales")]
  83. [HttpPost("get-info")]
  84. public async Task<IActionResult> GetInfo(JsonElement jsonElement)
  85. {
  86. jsonElement.TryGetProperty("ids", out JsonElement _ids);
  87. var cosmosClient = _azureCosmos.GetCosmosClient();
  88. List<string> ids = new();
  89. ids = _ids.ToObject<List<string>>();
  90. List<TmdUserinfo> userinfos = new();
  91. List<string> noFound = new();
  92. if (ids.Count > 0)
  93. {
  94. var content = new StringContent(ids.ToArray().ToJsonString(), Encoding.UTF8, "application/json");
  95. string idJson = await _coreAPIHttpService.GetUserInfos(content);
  96. userinfos = idJson.ToObject<List<TmdUserinfo>>();
  97. foreach (var item in ids)
  98. {
  99. var tempId = userinfos.Where(s => s.id.Equals(item)).ToList();
  100. var tempMail = userinfos.Where(s => !string.IsNullOrEmpty($"{s.mail}") && s.mail.Equals(item)).ToList();
  101. var tempmobile = userinfos.Where(s => !string.IsNullOrEmpty($"{s.mobile}") && s.mobile.Equals(item)).ToList();
  102. if (tempId.Count == 0 && tempMail.Count == 0 && tempmobile.Count == 0)
  103. noFound.Add(item);
  104. }
  105. }
  106. return Ok(new { state = RespondCode.Ok, userinfos, noFound });
  107. }
  108. /// <summary>
  109. /// 依据学校id查询学校教师信息
  110. /// </summary>
  111. /// <param name="jsonElement"></param>
  112. /// <returns></returns>
  113. //[AuthToken(Roles = "admin,rdc,assist,sales")]
  114. [HttpPost("get-tchinfos")]
  115. public async Task<IActionResult> GetSchoolTeacher(JsonElement jsonElement)
  116. {
  117. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  118. List<IdInfo> idInfos = new();
  119. var cosmosClient = _azureCosmos.GetCosmosClient();
  120. 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}") }))
  121. {
  122. idInfos.Add(item);
  123. }
  124. return Ok(new { state = RespondCode.Ok, idInfos });
  125. }
  126. /// <summary>
  127. /// BI发布端外消息
  128. /// </summary>
  129. /// <param name="jsonElement"></param>
  130. /// <returns></returns>
  131. [AuthToken(Roles = "admin,rdc,assist,sales")]
  132. [HttpPost("push-info")]
  133. public async Task<IActionResult> PushNotion(JsonElement jsonElement)
  134. {
  135. try
  136. {
  137. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  138. jsonElement.TryGetProperty("type", out JsonElement type);
  139. jsonElement.TryGetProperty("jumpUrl", out JsonElement jumpUrl);
  140. jsonElement.TryGetProperty("callbackName", out JsonElement callbackName);
  141. jsonElement.TryGetProperty("refuseName", out JsonElement refuseName);
  142. if (!jsonElement.TryGetProperty("theme", out JsonElement theme)) return BadRequest();
  143. if (!jsonElement.TryGetProperty("content", out JsonElement content)) return BadRequest();
  144. jsonElement.TryGetProperty("tmdIds", out JsonElement _tmdIds);
  145. jsonElement.TryGetProperty("schoolIds", out JsonElement _schoolIds);
  146. jsonElement.TryGetProperty("areaIds", out JsonElement _areaIds);
  147. if (!jsonElement.TryGetProperty("crowdType", out JsonElement _crowdType)) return BadRequest();
  148. if (!jsonElement.TryGetProperty("sendTime", out JsonElement sendTime)) return BadRequest();
  149. jsonElement.TryGetProperty("source", out JsonElement source);
  150. jsonElement.TryGetProperty("isOnlySave", out JsonElement isOnlySave);
  151. var cosmosClient = _azureCosmos.GetCosmosClient();
  152. //DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  153. List<IdNameCode> idNameCodes = new();
  154. BINotice bINotice = new();
  155. List<CrowdInfo> tmdIds = new();
  156. List<CrowdInfo> schoolIds = new();
  157. List<CrowdInfo> areaIds = new();
  158. List<string> tempScIds = new();
  159. //if (!string.IsNullOrEmpty($"{sendTime}"))
  160. // dateTime = DateTimeOffset.Parse($"{sendTime}");
  161. if (string.IsNullOrEmpty($"{_tmdIds}") && string.IsNullOrEmpty($"{_schoolIds}") && string.IsNullOrEmpty($"{_areaIds}"))
  162. return Ok(new { state = RespondCode.ParamsError, msg = "发送人群不能为空" });
  163. if (!string.IsNullOrEmpty($"{_tmdIds}"))
  164. tmdIds = _tmdIds.ToObject<List<CrowdInfo>>();
  165. if (!string.IsNullOrEmpty($"{_schoolIds}"))
  166. schoolIds = _schoolIds.ToObject<List<CrowdInfo>>();
  167. if (!string.IsNullOrEmpty($"{_areaIds}"))
  168. areaIds = _areaIds.ToObject<List<CrowdInfo>>();
  169. Crowd crowd = new()
  170. {
  171. tmdIds = tmdIds.Count > 0 ? tmdIds : new List<CrowdInfo>(),
  172. schoolIds = schoolIds.Count > 0 ? schoolIds : new List<CrowdInfo>(),
  173. areaIds = areaIds.Count > 0 ? areaIds : new List<CrowdInfo>(),
  174. types = $"{_crowdType}"
  175. };
  176. if (tmdIds.Count > 0)
  177. {
  178. StringBuilder tchSql = new($"select c.id, c.name,c.code,c.picture,c.nickname from c ");
  179. if (tmdIds.Count > 0)
  180. {
  181. tchSql.Append(BICommonWay.ManyScSql(" where c.id ", tmdIds.Select(s => s.id).ToList()));
  182. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<IdNameCode>(queryText: tchSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  183. {
  184. var tempId = idNameCodes.FindAll(fa => fa.id.Equals(item.id)).ToList();
  185. if (tempId.Count == 0)
  186. idNameCodes.Add(item);
  187. }
  188. }
  189. }
  190. if (areaIds.Count > 0)
  191. {
  192. StringBuilder scAreaSql = new($"select value(c.id) from c");
  193. if (schoolIds.Count > 0)
  194. {
  195. scAreaSql.Append(BICommonWay.ManyScSql(" where c.areaId", areaIds.Select(s => s.id).ToList()));
  196. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<string>(queryText: scAreaSql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  197. {
  198. var tempScId = schoolIds.FindAll(fa => fa.Equals(item)).ToList();
  199. if (tempScId.Count == 0)
  200. tempScIds.Add(item);
  201. }
  202. }
  203. }
  204. if (schoolIds.Count > 0)
  205. {
  206. StringBuilder scTchSql = new($"select c.id, c.name, c.picture,c.nickname from c where c.pk='Teacher'");
  207. if (schoolIds.Count > 0)
  208. {
  209. scTchSql.Append(BICommonWay.ManyScSql(" and c.code", schoolIds.Select(s => s.id).ToList(), $"Teacher-"));
  210. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<IdNameCode>(queryText: scTchSql.ToString(), requestOptions: new QueryRequestOptions() { }))
  211. {
  212. var tempId = idNameCodes.FindAll(fa => fa.id.Equals(item.id)).ToList();
  213. if (tempId.Count == 0)
  214. idNameCodes.Add(item);
  215. }
  216. }
  217. }
  218. string tagServiceName = ($"{_crowdType}".ToLower().Contains("hita")) ? "HiTA" : $"{_crowdType}";
  219. bINotice = new()
  220. {
  221. id = Guid.NewGuid().ToString(),
  222. code = "BINotice",
  223. type = !string.IsNullOrEmpty($"{type}") ? type.GetInt32() : 0,
  224. jumpUrl = !string.IsNullOrEmpty($"{jumpUrl}") ? $"{jumpUrl}" : "",
  225. callbackName = !string.IsNullOrEmpty($"{callbackName}") ? $"{callbackName}" : "",
  226. refuseName = !string.IsNullOrEmpty($"{refuseName}") ? $"{refuseName}" : "",
  227. theme = $"{theme}",
  228. content = $"{content}",
  229. crowd = crowd,
  230. crowdIds = idNameCodes.Select(s => $"{s.id}_{tagServiceName}").ToList(),
  231. createId = _tmdId,
  232. sendTime = sendTime.GetInt64(),//发布时间待解决
  233. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  234. source = !string.IsNullOrEmpty($"{source}") ? $"{source}" : "BI"
  235. };
  236. bINotice = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<BINotice>(bINotice, new PartitionKey("BINotice"));
  237. if (isOnlySave.GetBoolean())
  238. {
  239. //BI发送端外通知
  240. _coreAPIHttpService.BIPushNotify(bINotice, new Dictionary<string, object> { { "tmdid", _tmdIds }, { "sendId", bINotice.crowdIds } }, _option.Location, _configuration, _dingDing);
  241. }
  242. return Ok(new { state = RespondCode.Ok, bINotice });
  243. }
  244. catch (Exception ex)
  245. {
  246. _ = _dingDing.SendBotMsg($"BI,{_option.Location},notion/PushNotion() \n{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  247. return BadRequest();
  248. }
  249. }
  250. /// <summary>
  251. /// 查询发布的消息信息
  252. /// </summary>
  253. /// <param name="jsonElement"></param>
  254. /// <returns></returns>
  255. [HttpPost("get-infos")]
  256. [AuthToken(Roles = "admin,rdc,assist,sales")]
  257. public async Task<IActionResult> GetInfos(JsonElement jsonElement)
  258. {
  259. jsonElement.TryGetProperty("id", out JsonElement id);
  260. var cosmosClient = _azureCosmos.GetCosmosClient();
  261. List<BINotice> bINotices = new();
  262. StringBuilder sql = new("select value(c) from c");
  263. if (!string.IsNullOrEmpty($"{id}"))
  264. sql.Append($" where c.id='{id}'");
  265. sql.Append($" order by c.sendTime desc ");
  266. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<BINotice>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BINotice") }))
  267. {
  268. bINotices.Add(item);
  269. }
  270. return Ok(new { state = RespondCode.Ok, bINotices });
  271. }
  272. /// <summary>
  273. /// 取得學區及所屬學校、教師數
  274. /// </summary>
  275. /// <param name="jsonElement"></param>
  276. /// <returns></returns>
  277. [HttpPost("get-areas")]
  278. #if !DEBUG
  279. [AuthToken(Roles = "admin")]
  280. #endif
  281. public async Task<IActionResult> GetAreas(JsonElement jsonElement)
  282. {
  283. try
  284. {
  285. string reqAreaId = (jsonElement.TryGetProperty("areaId", out JsonElement _areaId)) ? _areaId.GetString() : string.Empty;
  286. bool showList = (jsonElement.TryGetProperty("showList", out JsonElement _showList)) ? _showList.GetBoolean() : false; //是否列出學校
  287. bool hasMail = (jsonElement.TryGetProperty("hasMail", out JsonElement _hasMail)) ? _hasMail.GetBoolean() : false; //篩選是否有Email true:會排除沒有Mail的醍摩豆帳號
  288. var cosmosClient = _azureCosmos.GetCosmosClient();
  289. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  290. List<AreaInfo> areaInfos = new();
  291. //取得學區
  292. string sqlArea = $"SELECT c.id, c.name FROM c ";
  293. string whereArea = string.Empty;
  294. if (!string.IsNullOrWhiteSpace(reqAreaId))
  295. {
  296. string wherePre = (!string.IsNullOrWhiteSpace(whereArea)) ? " AND " : string.Empty;
  297. whereArea += $"{wherePre} c.id = '{reqAreaId}' ";
  298. }
  299. if (!string.IsNullOrWhiteSpace(whereArea))
  300. {
  301. whereArea = $" WHERE {whereArea}";
  302. sqlArea = sqlArea + whereArea;
  303. }
  304. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", Constant.Normal).GetItemQueryIteratorSql<AreaInfo>(queryText: sqlArea, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base-Area") }))
  305. {
  306. areaInfos.Add(item);
  307. }
  308. //取得學校ID列表
  309. Dictionary<string, string> schAreaDic = new Dictionary<string, string>();
  310. Dictionary<string, string> schNameDic = new Dictionary<string, string>();
  311. //List<string> teacherCodes = new List<string>();
  312. List<string> areaIds = areaInfos.Select(a => a.id).ToList();
  313. string sqlSch = $"SELECT c.id, c.name, c.areaId FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(areaIds)}, c.areaId)";
  314. ///實體校
  315. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  316. {
  317. string schId = item.GetProperty("id").ToString();
  318. string schName = item.GetProperty("name").ToString();
  319. string areaId = item.GetProperty("areaId").ToString();
  320. if (!schAreaDic.ContainsKey(schId)) schAreaDic.Add(schId, areaId);
  321. if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
  322. }
  323. ///虛擬校
  324. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"VirtualBase") }))
  325. {
  326. string schId = item.GetProperty("id").ToString();
  327. string schName = item.GetProperty("name").ToString();
  328. string areaId = item.GetProperty("areaId").ToString();
  329. if (!schAreaDic.ContainsKey(schId)) schAreaDic.Add(schId, areaId);
  330. if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
  331. }
  332. //取得歸戶學校教師數
  333. Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>();
  334. List<string> filterScid = schNameDic.Select(s => s.Key).ToList();
  335. string sqlEx = $"SELECT c.id, c.schoolCode, c.schoolCodeW FROM c WHERE ((ARRAY_CONTAINS({JsonSerializer.Serialize(filterScid)}, c.schoolCode) OR ARRAY_CONTAINS({JsonSerializer.Serialize(filterScid)}, c.schoolCodeW)))";
  336. if (hasMail)
  337. {
  338. sqlEx += " AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail) AND c.mail != '')";
  339. }
  340. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  341. {
  342. string tmid = item.GetProperty("id").ToString();
  343. string schoolCode = (item.TryGetProperty("schoolCode", out JsonElement _schoolCode)) ? _schoolCode.ToString() : string.Empty;
  344. string schoolCodeW = (item.TryGetProperty("schoolCodeW", out JsonElement _schoolCodeW)) ? _schoolCodeW.ToString() : string.Empty;
  345. string schId = (!string.IsNullOrWhiteSpace(schoolCode)) ? schoolCode : (!string.IsNullOrWhiteSpace(schoolCodeW)) ? schoolCodeW : string.Empty;
  346. if(filterScid.Contains(schId))
  347. {
  348. if (!schTeacherCntDic.ContainsKey(schId)) schTeacherCntDic.Add(schId, 0);
  349. schTeacherCntDic[schId]++;
  350. }
  351. }
  352. //資料整理1 有教師則記入
  353. foreach (KeyValuePair<string, int> item in schTeacherCntDic)
  354. {
  355. string schId = item.Key;
  356. int tchCnt = item.Value;
  357. string areaId = schAreaDic[schId];
  358. AreaInfo areaInfo = areaInfos.Where(a => a.id.Equals(areaId)).FirstOrDefault();
  359. if (areaInfo != null)
  360. {
  361. areaInfo.scCnt++;
  362. areaInfo.tchCnt += tchCnt;
  363. if (showList)
  364. {
  365. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
  366. areaInfo.lists.Add(sch);
  367. }
  368. }
  369. }
  370. //資料整理2 移除無學校學區
  371. var result = areaInfos.Where(a => a.scCnt > 0).ToList();
  372. return Ok(new { state = RespondCode.Ok, result });
  373. }
  374. catch (Exception ex)
  375. {
  376. return BadRequest(new { ex });
  377. }
  378. }
  379. /// <summary>
  380. /// 取得地理位置所屬的學校或TMID
  381. /// </summary>
  382. /// <param name="jsonElement"></param>
  383. /// <returns></returns>
  384. [HttpPost("get-geos")]
  385. #if !DEBUG
  386. [AuthToken(Roles = "admin")]
  387. #endif
  388. public async Task<IActionResult> GetGeos(JsonElement jsonElement)
  389. {
  390. bool showList = (jsonElement.TryGetProperty("showList", out JsonElement _showList)) ? _showList.GetBoolean() : false; //是否列出學校或TMID
  391. string countryId = (jsonElement.TryGetProperty("countryId", out JsonElement _countryId)) ? _countryId.GetString() : string.Empty; //地區ID(國ID)
  392. string provinceId = (jsonElement.TryGetProperty("provinceId", out JsonElement _provinceId)) ? _provinceId.GetString() : string.Empty; //省ID
  393. string cityId = (jsonElement.TryGetProperty("cityId", out JsonElement _cityId)) ? _cityId.GetString() : string.Empty; //市ID
  394. string distId = (jsonElement.TryGetProperty("dist", out JsonElement _distJobj)) ? _distJobj.GetString() : string.Empty; //區ID
  395. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : "school"; //類型 tmid、school
  396. bool hasMail = (jsonElement.TryGetProperty("hasMail", out JsonElement _hasMail)) ? _hasMail.GetBoolean() : false; //篩選是否有Email true:會排除沒有Mail的醍摩豆帳號
  397. string countryName = string.Empty;
  398. string provinceName = string.Empty;
  399. string cityName = string.Empty;
  400. string distName = string.Empty;
  401. var (geoInfos, groupKey) = await GetDataByGeo(type, "geo", showList, countryId, provinceId, cityId, hasMail);
  402. return Ok(new { state = 200, dataType = groupKey, data = geoInfos });
  403. }
  404. /// <summary>
  405. /// 取得教育機構所屬的學校或TMID
  406. /// </summary>
  407. /// <param name="jsonElement"></param>
  408. /// <returns></returns>
  409. [HttpPost("get-units")]
  410. #if !DEBUG
  411. [AuthToken(Roles = "admin")]
  412. #endif
  413. public async Task<IActionResult> GetUnitTypes(JsonElement jsonElement)
  414. {
  415. //var cosmosClient = _azureCosmos.GetCosmosClient();
  416. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  417. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  418. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : string.Empty; //教育機構類型 1:基礎教育機構(K-小學) 2:中等教育機構(國中、高中/職) 3:高等教育機構(大學、研究所) 4:其他
  419. bool showList = (jsonElement.TryGetProperty("showList", out JsonElement _showList)) ? _showList.GetBoolean() : false; //是否列出學校
  420. bool hasMail = (jsonElement.TryGetProperty("hasMail", out JsonElement _hasMail)) ? _hasMail.GetBoolean() : false; //篩選是否有Email true:會排除沒有Mail的醍摩豆帳號
  421. //取得ID帳號中所有的歸戶學校ID
  422. List<string> coreSchIds = new List<string>();
  423. Dictionary<string, List<string>> schTmidDic = new Dictionary<string, List<string>>(); //學校ID > TMID 字典
  424. string sqlEx = "SELECT c.id, c.schoolCode, c.schoolCodeW FROM c WHERE ((IS_DEFINED(c.schoolCode) AND NOT IS_NULL(c.schoolCode)) OR (IS_DEFINED(c.schoolCodeW) AND NOT IS_NULL(c.schoolCodeW)))";
  425. if (hasMail) sqlEx += " AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)) ";
  426. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  427. {
  428. string tmid = item.GetProperty("id").ToString();
  429. string schoolCode = (item.TryGetProperty("schoolCode", out JsonElement _schoolCode)) ? _schoolCode.ToString() : string.Empty;
  430. string schoolCodeW = (item.TryGetProperty("schoolCodeW", out JsonElement _schoolCodeW)) ? _schoolCodeW.ToString() : string.Empty;
  431. string schId = (!string.IsNullOrWhiteSpace(schoolCode)) ? schoolCode : (!string.IsNullOrWhiteSpace(schoolCodeW)) ? schoolCodeW : string.Empty;
  432. if (!string.IsNullOrWhiteSpace(schId))
  433. {
  434. if(!coreSchIds.Contains(schId)) coreSchIds.Add(schId);
  435. if (schTmidDic.ContainsKey(schId)) {
  436. if (!schTmidDic[schId].Contains(tmid)) schTmidDic[schId].Add(tmid);
  437. }
  438. else
  439. {
  440. schTmidDic.Add(schId, new List<string>() { tmid });
  441. }
  442. }
  443. }
  444. //Core 篩選取得的學校、學校類型取得
  445. string coreSql = "SELECT c.id, c.name, c.code, c.shortCode, c.unitType, c.unitType = '1' ? '1' : c.unitType = '8' ? '1' : c.unitType = '4' ? '1' : c.unitType = '5' ? '4' : c.unitType = '6' ? '4' : c.unitType = '7' ? '4' : c.unitType = '9' ? '4' : c.unitType as unitTypeFix FROM c";
  446. string coreWhere = $" WHERE 1=1 AND ARRAY_CONTAINS({JsonSerializer.Serialize(coreSchIds)}, c.shortCode) AND IS_DEFINED(c.unitType) AND NOT IS_NULL(c.unitType) ";
  447. switch (type)
  448. {
  449. case "1": ///基礎教育機構(K-小學)
  450. coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "1", "8" })}, c.unitType)";
  451. break;
  452. case "2": ///中等教育機構(國中、高中/職)
  453. coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "2" })}, c.unitType)";
  454. break;
  455. case "3": ///高等教育機構(大學、研究所)
  456. coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "3" })}, c.unitType)";
  457. break;
  458. case "4": ///其他
  459. coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "4", "5", "6", "7", "9" })}, c.unitType)";
  460. break;
  461. }
  462. string lang = (_option.Location.Contains("China")) ? "zh_cn" : "zh_tw";
  463. Dictionary<string, string> unitNameDic = getSchoolUnitName(lang);
  464. List<AreaInfo> unitInfos = new(); //輸出結果
  465. string sqlCore = $"{coreSql}{coreWhere}";
  466. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  467. {
  468. string schName = item.GetProperty("name").ToString();
  469. string shortCode = item.GetProperty("shortCode").ToString();
  470. string unitType = item.GetProperty("unitTypeFix").ToString();
  471. ///結果製作
  472. string unitId = unitType;
  473. string unitName = unitNameDic[unitId];
  474. AreaInfo unitInfo = unitInfos.Where(u => u.id.Equals(unitId)).FirstOrDefault();
  475. if (unitInfo == null)
  476. {
  477. AreaInfo unitInfoCrt = new AreaInfo();
  478. unitInfoCrt.id = unitId;
  479. unitInfoCrt.name = unitName;
  480. unitInfos.Add(unitInfoCrt);
  481. unitInfo = unitInfos.Where(u => u.id.Equals(unitId)).FirstOrDefault();
  482. }
  483. unitInfo.scCnt++;
  484. int tchCnt = (schTmidDic.ContainsKey(shortCode)) ? schTmidDic[shortCode].Count : 0;
  485. unitInfo.tchCnt += tchCnt;
  486. if (showList)
  487. {
  488. AreaSchoolInfo sch = new AreaSchoolInfo() { id = shortCode, name = schName, tchCnt = tchCnt };
  489. unitInfo.lists.Add(sch);
  490. }
  491. }
  492. return Ok(new { state = 200, data = unitInfos });
  493. }
  494. //由地理資訊取得TMID或學校核心邏輯
  495. /// <summary>由地理資訊取得TMID或學校核心邏輯</summary>
  496. /// <param name="type">地理資訊取得對象:tmid、school</param>
  497. /// <param name="output">輸出:tmid、school</param>
  498. /// <param name="showList">輸出項lists是否要有值</param>
  499. /// <param name="countryId"></param>
  500. /// <param name="provinceId"></param>
  501. /// <param name="cityId"></param>
  502. /// <param name="hasMail">醍魔豆帳號是否有Email</param>
  503. /// <returns></returns>
  504. private async Task<(List<AreaInfo>,string)> GetDataByGeo (string type, string output, bool showList, string countryId = "", string provinceId = "", string cityId = "", bool hasMail = false)
  505. {
  506. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  507. var cosmosClientCsv2Cn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  508. bool isChina = (_option.Location.Contains("China")) ? true : false;
  509. List<string> comeRemoveStr = GeoRegion.comeRemoveStr;
  510. if (isChina) countryId = "CN";
  511. List<TmidInfo> tmidExInfos = new List<TmidInfo>(); //TMID資訊
  512. List<AreaInfo> geoInfos = new(); //輸出:地理位置為單位
  513. List<AreaInfo> tmidInfos = new(); //輸出:TMID為單位
  514. regiondata regionData = GetRegionData(); //取得國省市區地理資訊架構
  515. regiondata regionDataEn = GetRegionDataEn(); //取得EN版國省市區地理資訊架構
  516. Dictionary<string, string> geoIdNameDic = new Dictionary<string, string>(); //key: geoId val:geoName
  517. Dictionary<string, string> geoCountryIdNameDicEn = new Dictionary<string, string>(); //key: geoId val:geoName
  518. string countryName = string.Empty;
  519. string provinceName = string.Empty;
  520. string cityName = string.Empty;
  521. string distName = string.Empty;
  522. //[TMID地理位置欄位 ID與名稱混雜對策] 取得搜尋的國省市名稱
  523. ///國字典製作
  524. var geoCountryIdNameDic = new Dictionary<string, string>();
  525. foreach (KeyValuePair<string, regionbase> item in regionData.country)
  526. {
  527. geoCountryIdNameDic.Add(item.Value.code, item.Value.name);
  528. }
  529. foreach (KeyValuePair<string, regionbase> item in regionDataEn.country)
  530. {
  531. geoCountryIdNameDicEn.Add(item.Value.code, item.Value.name);
  532. }
  533. if (!string.IsNullOrWhiteSpace(countryId))
  534. {
  535. countryName = (regionData.country.ContainsKey(countryId)) ? regionData.country[countryId].name : string.Empty;
  536. }
  537. ///省字典製作
  538. var geoProvinceIdNameDic = new Dictionary<string, string>();
  539. if (isChina)
  540. {
  541. foreach (KeyValuePair<string, regionbase> item in regionData.province["CN"])
  542. {
  543. geoProvinceIdNameDic.Add(item.Value.code, item.Value.name);
  544. }
  545. }
  546. if (!string.IsNullOrWhiteSpace(provinceId))
  547. {
  548. provinceName = (geoProvinceIdNameDic.ContainsKey(provinceId)) ? geoProvinceIdNameDic[provinceId] : string.Empty;
  549. }
  550. ///市字典製作
  551. var geoCityIdNameDic = new Dictionary<string, string>();
  552. if(isChina)
  553. {
  554. foreach (var dicProvince in regionData.city["CN"])
  555. {
  556. var pNow = dicProvince.Value;
  557. foreach (var item in pNow)
  558. {
  559. geoCityIdNameDic.Add(item.Value.code, item.Value.name);
  560. }
  561. }
  562. }
  563. else
  564. {
  565. foreach (var dicProvince in regionData.city["TW"])
  566. {
  567. var pNow = dicProvince.Value;
  568. foreach (var item in pNow)
  569. {
  570. geoCityIdNameDic.Add(item.Value.code, item.Value.name);
  571. }
  572. }
  573. }
  574. if (!string.IsNullOrWhiteSpace(cityId))
  575. {
  576. cityName = (geoCityIdNameDic.ContainsKey(cityId)) ? geoCityIdNameDic[cityId] : string.Empty;
  577. }
  578. string sqlWhere = string.Empty;
  579. string groupKey = "country";
  580. //地理資訊取得對象:TMID
  581. if (type.Equals("tmid"))
  582. {
  583. List<string> schIds = new List<string>(); //要取得的學校ID
  584. //取得ID資訊
  585. sqlWhere = $" (NOT IS_NULL(c.country) AND c.country != '') ";
  586. ///國
  587. if (!string.IsNullOrWhiteSpace(countryId))
  588. {
  589. groupKey = (!isChina) ? "city" : "province";
  590. string tmpSql = $" c.country = '{countryId}' ";
  591. if (!string.IsNullOrWhiteSpace(countryName))
  592. {
  593. comeRemoveStr.ForEach(c => { countryName = countryName.Replace(c, ""); });
  594. tmpSql += $" OR CONTAINS(c.country, '{countryName}') ";
  595. }
  596. sqlWhere += $" AND ({tmpSql}) ";
  597. }
  598. ///省
  599. if (!string.IsNullOrWhiteSpace(provinceId))
  600. {
  601. groupKey = "city";
  602. string tmpSql = $" c.province = '{provinceId}' ";
  603. if (!string.IsNullOrWhiteSpace(provinceName))
  604. {
  605. comeRemoveStr.ForEach(c => { provinceName = provinceName.Replace(c, ""); });
  606. tmpSql += $" OR CONTAINS(c.province, '{provinceName}') ";
  607. }
  608. sqlWhere += $" AND ({tmpSql}) ";
  609. }
  610. ///市
  611. if (!string.IsNullOrWhiteSpace(cityId))
  612. {
  613. groupKey = "name";
  614. string tmpSql = (!isChina) ? $" c.province = '{cityId}' " : $" c.city = '{cityId}' ";
  615. if (!string.IsNullOrWhiteSpace(cityName))
  616. {
  617. comeRemoveStr.ForEach(c => { cityName = cityName.Replace(c, ""); });
  618. tmpSql += (!isChina) ? $" OR CONTAINS(c.province, '{cityName}') " : $" OR CONTAINS(c.city, '{cityName}') ";
  619. }
  620. sqlWhere += $" AND ({tmpSql}) ";
  621. }
  622. //有Email篩選
  623. if (hasMail)
  624. {
  625. string tmpSql = "IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)";
  626. sqlWhere += $" AND ({tmpSql}) ";
  627. }
  628. if (!string.IsNullOrWhiteSpace(sqlWhere))
  629. {
  630. Regex regex = new Regex("^[a-zA-Z0-9]{2}$");
  631. string sqlTmidEx = $"SELECT * FROM c WHERE {sqlWhere}";
  632. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlTmidEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  633. {
  634. TmidInfo tmidExInfoTmp = item.ToObject<TmidInfo>();
  635. //地理位置名稱
  636. ///國
  637. if(!string.IsNullOrWhiteSpace(tmidExInfoTmp.country))
  638. {
  639. string countryIdNow = (regex.IsMatch(tmidExInfoTmp.country)) ? tmidExInfoTmp.country : string.Empty;
  640. if (string.IsNullOrWhiteSpace(countryIdNow)) //國欄位填入國名對策
  641. {
  642. var geoCountry = geoCountryIdNameDic.FirstOrDefault(x => x.Value.Contains(tmidExInfoTmp.country));
  643. if (!geoCountry.Equals(default(KeyValuePair<string, string>))) {
  644. countryIdNow = geoCountry.Key;
  645. }
  646. }
  647. if (string.IsNullOrWhiteSpace(countryIdNow)) //國欄位填入國名對策(英文)
  648. {
  649. var geoCountryEn = geoCountryIdNameDicEn.FirstOrDefault(x => x.Value.Equals(tmidExInfoTmp.country));
  650. if (!geoCountryEn.Equals(default(KeyValuePair<string, string>))) {
  651. countryIdNow = geoCountryEn.Key;
  652. }
  653. }
  654. if(!string.IsNullOrWhiteSpace(countryIdNow) && !tmidExInfoTmp.country.Equals(countryIdNow)) tmidExInfoTmp.country = countryIdNow;
  655. if (geoCountryIdNameDic.TryGetValue(countryIdNow, out var countryInfo))
  656. {
  657. tmidExInfoTmp.countryName = countryInfo;
  658. }
  659. }
  660. ///省
  661. if (!string.IsNullOrWhiteSpace(tmidExInfoTmp.province))
  662. {
  663. if (tmidExInfoTmp.country.Equals("TW")) //TW的省欄位填的是市資料
  664. {
  665. tmidExInfoTmp.city = tmidExInfoTmp.province;
  666. tmidExInfoTmp.province = string.Empty;
  667. }
  668. else
  669. {
  670. string provinceIdNow = (regex.IsMatch(tmidExInfoTmp.province)) ? tmidExInfoTmp.province : string.Empty;
  671. if (string.IsNullOrWhiteSpace(provinceIdNow)) //省欄位填入省名對策
  672. {
  673. var geoProvince = geoProvinceIdNameDic.FirstOrDefault(x => x.Value.Equals(tmidExInfoTmp.province));
  674. if (!geoProvince.Equals(default(KeyValuePair<string, string>)))
  675. {
  676. provinceIdNow = geoProvince.Key;
  677. }
  678. }
  679. if (!string.IsNullOrWhiteSpace(provinceIdNow) && !tmidExInfoTmp.province.Equals(provinceIdNow)) tmidExInfoTmp.province = provinceIdNow;
  680. //var provinceDic = regionData.province[tmidExInfoTmp.country];
  681. if (geoProvinceIdNameDic.TryGetValue(tmidExInfoTmp.province, out var provinceInfo))
  682. {
  683. tmidExInfoTmp.provinceName = provinceInfo;
  684. }
  685. }
  686. }
  687. ///市
  688. if (!string.IsNullOrWhiteSpace(tmidExInfoTmp.city))
  689. {
  690. string cityIdNow = (regex.IsMatch(tmidExInfoTmp.city)) ? tmidExInfoTmp.city : string.Empty;
  691. if (string.IsNullOrWhiteSpace(cityIdNow)) //市欄位填入市名對策
  692. {
  693. var geoCity = geoCityIdNameDic.FirstOrDefault(x => x.Value.Equals(tmidExInfoTmp.city));
  694. if (!geoCity.Equals(default(KeyValuePair<string, string>)))
  695. {
  696. cityIdNow = geoCity.Key;
  697. }
  698. }
  699. if (!string.IsNullOrWhiteSpace(cityIdNow) && !tmidExInfoTmp.city.Equals(cityIdNow)) tmidExInfoTmp.city = cityIdNow;
  700. if(geoCityIdNameDic.TryGetValue(tmidExInfoTmp.city, out var cityInfo))
  701. {
  702. tmidExInfoTmp.cityName = cityInfo;
  703. }
  704. }
  705. //要取得的學校ID
  706. if (!string.IsNullOrWhiteSpace(tmidExInfoTmp.schoolCode) && !schIds.Contains(tmidExInfoTmp.schoolCode)) schIds.Add(tmidExInfoTmp.schoolCode);
  707. if (!string.IsNullOrWhiteSpace(tmidExInfoTmp.schoolCodeW) && !schIds.Contains(tmidExInfoTmp.schoolCodeW)) schIds.Add(tmidExInfoTmp.schoolCodeW);
  708. //輸出項生成
  709. tmidExInfos.Add(tmidExInfoTmp);
  710. }
  711. }
  712. //取得學校資訊
  713. Dictionary<string, string> schIdNameDic = new Dictionary<string, string>(); //key: schId val:schName
  714. string sqlWhereSch = $" ARRAY_CONTAINS({JsonSerializer.Serialize(schIds)}, c.shortCode)";
  715. string sqlSch = $"SELECT c.id, c.code, c.shortCode, c.name FROM c WHERE {sqlWhereSch} ";
  716. await foreach (var item in cosmosClientCsv2Cn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  717. {
  718. string schId = item.GetProperty("shortCode").ToString();
  719. string schName = item.GetProperty("name").ToString();
  720. schIdNameDic.Add(schId, schName);
  721. }
  722. //輸出項整理
  723. foreach (TmidInfo tmidInfo in tmidExInfos)
  724. {
  725. ///tmidInfos
  726. AreaInfo tmidInfoRow = new AreaInfo() { id = tmidInfo.id, name = tmidInfo.name };
  727. tmidInfos.Add(tmidInfoRow);
  728. ///geoInfos
  729. string geoId = tmidInfo.country;
  730. string geoName = tmidInfo.countryName;
  731. if(!string.IsNullOrWhiteSpace(geoName)) comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  732. switch (groupKey)
  733. {
  734. case "province":
  735. geoId = tmidInfo.province;
  736. geoName = tmidInfo.provinceName;
  737. if (!string.IsNullOrWhiteSpace(geoName)) comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  738. break;
  739. case "city":
  740. geoId = tmidInfo.city;
  741. geoName = tmidInfo.cityName;
  742. if (!string.IsNullOrWhiteSpace(geoName)) comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  743. break;
  744. case "name":
  745. geoId = tmidInfo.schoolCode;
  746. if (string.IsNullOrWhiteSpace(geoId)) geoId = tmidInfo.schoolCodeW;
  747. if (!string.IsNullOrWhiteSpace(geoName)) geoName = (!string.IsNullOrWhiteSpace(geoId) && schIdNameDic.ContainsKey(geoId)) ? schIdNameDic[geoId] : string.Empty;
  748. break;
  749. }
  750. //輸出
  751. if (!string.IsNullOrWhiteSpace(geoId))
  752. {
  753. AreaInfo geoInfo = geoInfos.Where(g => g.id.Equals(geoId)).FirstOrDefault();
  754. if (geoInfo == null)
  755. {
  756. AreaInfo geoInfoCrt = new AreaInfo();
  757. geoInfoCrt.id = geoId;
  758. geoInfoCrt.name = (_option.Location.Contains("Global")) ? "無法取得名稱" : "无法取得名称";
  759. if (!string.IsNullOrWhiteSpace(geoName)) geoInfoCrt.name = geoName;
  760. geoInfos.Add(geoInfoCrt);
  761. geoInfo = geoInfos.Where(g => g.id.Equals(geoInfoCrt.id)).FirstOrDefault();
  762. }
  763. string schId = (!string.IsNullOrWhiteSpace(tmidInfo.schoolCode)) ? tmidInfo.schoolCode : (!string.IsNullOrWhiteSpace(tmidInfo.schoolCodeW)) ? tmidInfo.schoolCodeW : string.Empty;
  764. string schName = (!string.IsNullOrWhiteSpace(schId) && schIdNameDic.ContainsKey(schId)) ? schIdNameDic[schId] : string.Empty;
  765. if (!string.IsNullOrWhiteSpace(schId))
  766. {
  767. AreaSchoolInfo schInGeo = geoInfo.lists.FirstOrDefault(s => s.id.Equals(schId));
  768. if (schInGeo == null)
  769. {
  770. geoInfo.lists.Add(new AreaSchoolInfo() { id = schId, name = schName });
  771. schInGeo = geoInfo.lists.FirstOrDefault(s => s.id.Equals(schId));
  772. }
  773. schInGeo.tchCnt++;
  774. geoInfo.scCnt++;
  775. geoInfo.tchCnt++;
  776. }
  777. }
  778. }
  779. ///移除無校列
  780. geoInfos.RemoveAll(g => g.lists.Count.Equals(0));
  781. if (!showList)
  782. {
  783. geoInfos.ForEach(g => g.lists.Clear());
  784. }
  785. }
  786. //地理資訊取得對象:學校
  787. else if (type.Equals("school"))
  788. {
  789. List<string> schIds = new List<string>(); //要取得的學校ID
  790. //取得ID資訊
  791. sqlWhere = $" ((IS_DEFINED(c.schoolCode) AND NOT IS_NULL(c.schoolCode)) OR (IS_DEFINED(c.schoolCodeW) AND NOT IS_NULL(c.schoolCodeW))) ";
  792. //有Email篩選
  793. if (hasMail)
  794. {
  795. string tmpSql = "(IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail) AND c.mail != '')";
  796. sqlWhere += $" AND {tmpSql} ";
  797. }
  798. if (!string.IsNullOrWhiteSpace(sqlWhere))
  799. {
  800. string sqlTmidEx = $"SELECT * FROM c WHERE {sqlWhere}";
  801. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlTmidEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  802. {
  803. TmidInfo tmidEx = item.ToObject<TmidInfo>();
  804. tmidEx.schId = (!string.IsNullOrWhiteSpace(tmidEx.schoolCode)) ? tmidEx.schoolCode : (!string.IsNullOrWhiteSpace(tmidEx.schoolCodeW)) ? tmidEx.schoolCodeW : string.Empty;
  805. tmidExInfos.Add(tmidEx);
  806. if (!string.IsNullOrWhiteSpace(tmidEx.schId) && !schIds.Contains(tmidEx.schId)) schIds.Add(tmidEx.schId);
  807. }
  808. }
  809. //取得學校資訊
  810. if(schIds.Count > 0)
  811. {
  812. sqlWhere = $" (NOT IS_NULL(c.countryId) AND c.countryId != '') ";
  813. ///國
  814. if (!string.IsNullOrWhiteSpace(countryId))
  815. {
  816. groupKey = (isChina) ? "province" : (!countryId.Equals("TW")) ? "name" : "city";
  817. sqlWhere += $" AND c.countryId = '{countryId}' ";
  818. }
  819. ///省
  820. if (!string.IsNullOrWhiteSpace(provinceId))
  821. {
  822. groupKey = "city";
  823. sqlWhere += $" AND c.provinceId = '{provinceId}' ";
  824. }
  825. ///市
  826. if (!string.IsNullOrWhiteSpace(cityId))
  827. {
  828. groupKey = "name";
  829. sqlWhere += $" AND c.cityId = '{cityId}' ";
  830. }
  831. sqlWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(schIds)}, c.shortCode)";
  832. string sqlSch = $"SELECT c.id, c.code, c.shortCode, c.name, c.countryId, c.provinceId, c.cityId, c.distId FROM c WHERE {sqlWhere} ";
  833. await foreach (var item in cosmosClientCsv2Cn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  834. {
  835. string schId = item.GetProperty("shortCode").ToString();
  836. string schName = item.GetProperty("name").ToString();
  837. string geoId = Convert.ToString(item.GetProperty("countryId"));
  838. var countryInfo = regionData.country.FirstOrDefault(c => c.Key.Equals(geoId));
  839. string geoName = (!countryInfo.Equals(default(KeyValuePair<string, regionbase>))) ? countryInfo.Value.name : string.Empty;
  840. if (!string.IsNullOrWhiteSpace(geoName)) comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  841. switch (groupKey)
  842. {
  843. case "province":
  844. geoId = Convert.ToString(item.GetProperty("provinceId"));
  845. var provinceDic = regionData.province[countryId];
  846. if(provinceDic.TryGetValue(geoId, out var provinceInfo))
  847. {
  848. geoName = provinceInfo.name;
  849. }
  850. if (!string.IsNullOrWhiteSpace(geoName)) comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  851. break;
  852. case "city":
  853. geoId = Convert.ToString(item.GetProperty("cityId"));
  854. if(regionData.city.ContainsKey(countryId))
  855. {
  856. if (regionData.city[countryId].ContainsKey("tw"))
  857. {
  858. var cityDic = regionData.city[countryId]["tw"];
  859. if(cityDic.TryGetValue(geoId, out var cityInfo))
  860. {
  861. geoName = cityInfo.name;
  862. }
  863. }
  864. else if (!string.IsNullOrWhiteSpace(provinceId) && regionData.city[countryId].ContainsKey(provinceId))
  865. {
  866. var cityDic = regionData.city[countryId][provinceId];
  867. if (cityDic.TryGetValue(geoId, out var cityInfo))
  868. {
  869. geoName = cityInfo.name;
  870. }
  871. }
  872. }
  873. comeRemoveStr.ForEach(c => { geoName = ReplaceLastMatch(geoName, c, string.Empty); }); //字串替換
  874. break;
  875. case "name":
  876. geoId = Convert.ToString(item.GetProperty("shortCode"));
  877. geoName = Convert.ToString(item.GetProperty("name"));
  878. break;
  879. }
  880. //輸出項製作
  881. if (!string.IsNullOrWhiteSpace(geoId))
  882. {
  883. ///geoInfos
  884. AreaInfo geoInfo = geoInfos.Where(g => g.id.Equals(geoId)).FirstOrDefault();
  885. if (geoInfo == null)
  886. {
  887. AreaInfo geoInfoCrt = new AreaInfo();
  888. geoInfoCrt.id = geoId;
  889. geoInfoCrt.name = (_option.Location.Contains("Global")) ? "無法取得名稱" : "无法取得名称";
  890. if(!string.IsNullOrWhiteSpace(geoName)) geoInfoCrt.name = geoName;
  891. geoInfos.Add(geoInfoCrt);
  892. geoInfo = geoInfos.Where(g => g.id.Equals(geoInfoCrt.id)).FirstOrDefault();
  893. }
  894. geoInfo.scCnt++;
  895. //List<TmidInfo> tmidInfoSelectedStrong = tmidExInfos.Where(g => (!string.IsNullOrWhiteSpace(g.schoolCode) && g.schoolCode.Equals(schId))).ToList();
  896. //List<string> tmidListStrong = tmidInfoSelectedStrong.Select(g => g.id).ToList();
  897. //List<TmidInfo> tmidInfoSelectedWeek = tmidExInfos.Where(g => !tmidListStrong.Contains(g.id) && (!string.IsNullOrWhiteSpace(g.schoolCodeW) && g.schoolCodeW.Equals(schId))).ToList();
  898. //List<TmidInfo> tmidInfoSelected = tmidInfoSelectedStrong.Union(tmidInfoSelectedWeek).ToList();
  899. List<TmidInfo> tmidInfoSelected = tmidExInfos.Where(g => (!string.IsNullOrWhiteSpace(g.schId) && g.schId.Equals(schId))).ToList();
  900. geoInfo.tchCnt += tmidInfoSelected.Count;
  901. if (showList && (groupKey.Equals("country") || groupKey.Equals("province") || groupKey.Equals("city")))
  902. {
  903. AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schName, tchCnt = tmidInfoSelected.Count };
  904. geoInfo.lists.Add(sch);
  905. }
  906. ///tmidInfos
  907. List<AreaInfo> tmidAddToList = tmidInfoSelected.Select(g => new AreaInfo() { id = g.id, name = g.name }).ToList();
  908. tmidInfos.AddRange(tmidAddToList);
  909. }
  910. }
  911. }
  912. }
  913. //輸出
  914. if (output.Equals("tmid"))
  915. {
  916. return (tmidInfos, groupKey);
  917. }
  918. else
  919. {
  920. return (geoInfos, groupKey);
  921. }
  922. }
  923. /// <summary>
  924. /// (個別挑選)取得TMID資訊
  925. /// </summary>
  926. [HttpPost("get-tmidinfo")]
  927. #if !DEBUG
  928. [AuthToken(Roles = "admin")]
  929. #endif
  930. public async Task<IActionResult> GetTmidInfo(GetTmidInfoParam target)
  931. {
  932. try
  933. {
  934. var storageClientCsv2 = _azureStorage.GetCloudTableClient(name: "CoreServiceV2"); //Storage CSV2
  935. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  936. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  937. var tablePointsClient = storageClientCsv2.GetTableReference("Points");
  938. //各項值取聯集或交集
  939. string modeToAll = !string.IsNullOrWhiteSpace(target.mode) ? target.mode : "and";
  940. string sqlSel = "SELECT c.id FROM c WHERE 1=1 ";
  941. //生成時間
  942. List<string> passTmidCrt = new List<string>();
  943. List<string> sqlWhereListBase = new List<string>();
  944. if (target.creatTime != null)
  945. {
  946. if (target.creatTime.start > 0) sqlWhereListBase.Add($" {target.creatTime.start} <= StringToNumber(c.id) ");
  947. if (target.creatTime.end > 0) sqlWhereListBase.Add($" StringToNumber(c.id) <= {target.creatTime.end} ");
  948. }
  949. ///SQL文生成
  950. bool useCrtFlg = false;
  951. string sqlWhereBase = string.Empty;
  952. foreach (string w in sqlWhereListBase)
  953. {
  954. useCrtFlg = true;
  955. sqlWhereBase += $" AND {w}";
  956. }
  957. if (!string.IsNullOrWhiteSpace(sqlWhereBase))
  958. {
  959. string sqlBase = $"{sqlSel}{sqlWhereBase}";
  960. await foreach (var item in cosmosClientCsv2
  961. .GetContainer("Core", "ID2")
  962. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBase, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  963. {
  964. string id = item.GetProperty("id").ToString();
  965. if (!passTmidCrt.Contains(id)) passTmidCrt.Add(id);
  966. }
  967. }
  968. //地理資訊 (base-ex)
  969. bool useGeoFlg = (target.geo != null && (!string.IsNullOrWhiteSpace(target.geo.countryId) || !string.IsNullOrWhiteSpace(target.geo.provinceId) || !string.IsNullOrWhiteSpace(target.geo.cityId))) ? true : false;
  970. List<string> passTmidGeo = new List<string>();
  971. var (geoInfos, _) = await GetDataByGeo("tmid", "tmid", true, target.geo.countryId, target.geo.provinceId, target.geo.cityId, target.hasMail);
  972. foreach(var geoInfo in geoInfos)
  973. {
  974. if (!passTmidGeo.Contains(geoInfo.id)) passTmidGeo.Add(geoInfo.id);
  975. }
  976. //使用產品 ARRAY_CONTAINS(['hiteach', 'hiteachcc', 'sokapp', 'sokrates', 'webirs'], c.type)
  977. bool usePrdFlg = false;
  978. List<string> passTmidPrd = new List<string>();
  979. var tmidProdDic = new Dictionary<string, List<string>>(); //各ID使用過的的產品List
  980. List<string> prodWhereList = new List<string>();
  981. if (target.product != null && target.product.id.Count > 0)
  982. {
  983. usePrdFlg = true;
  984. foreach (string prodCode in target.product.id)
  985. {
  986. prodWhereList.Add(prodCode);
  987. }
  988. }
  989. if (prodWhereList.Count > 0)
  990. {
  991. string sqlSelCross = "SELECT DISTINCT c.id, c.type FROM c ";
  992. string sqlWhereCross = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(prodWhereList)}, c.type)";
  993. string sqlCross = $"{sqlSelCross}{sqlWhereCross}";
  994. await foreach (var item in cosmosClientCsv2
  995. .GetContainer("Core", "ID2")
  996. .GetItemQueryIteratorSql<JsonElement>(sqlCross, requestOptions: null))
  997. {
  998. string id = item.GetProperty("id").ToString();
  999. string prod = item.GetProperty("type").ToString();
  1000. if (!tmidProdDic.ContainsKey(id)) tmidProdDic.Add(id, new List<string>());
  1001. tmidProdDic[id].Add(prod);
  1002. }
  1003. ///生成符合AndOr條件的TMID製作
  1004. if (target.product.mode.Equals("and"))
  1005. {
  1006. foreach (var prodItem in tmidProdDic)
  1007. {
  1008. int hasProdCount = 0;
  1009. string tmid = prodItem.Key;
  1010. ///產品比對
  1011. foreach (string prod in target.product.id)
  1012. {
  1013. if (prodItem.Value.Contains(prod)) hasProdCount++;
  1014. }
  1015. if (hasProdCount.Equals(target.product.id.Count))
  1016. {
  1017. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  1018. }
  1019. }
  1020. }
  1021. else if (target.product.mode.Equals("or"))
  1022. {
  1023. foreach (var prodItem in tmidProdDic)
  1024. {
  1025. int hasProdCount = 0;
  1026. string tmid = prodItem.Key;
  1027. ///產品比對
  1028. foreach (string prod in target.product.id)
  1029. {
  1030. if (prodItem.Value.Contains(prod))
  1031. {
  1032. if (!passTmidPrd.Contains(tmid)) passTmidPrd.Add(tmid);
  1033. break;
  1034. }
  1035. }
  1036. }
  1037. }
  1038. }
  1039. //點數
  1040. bool usePntFlg = false;
  1041. List<string> passTmidPnt = new List<string>();
  1042. string filter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Points");
  1043. string rkFilterCombine = string.Empty;
  1044. if (target.point != null)
  1045. {
  1046. if (target.point.start > 0 || target.point.end > 0)
  1047. {
  1048. usePntFlg = true;
  1049. if (target.point.start > 0)
  1050. {
  1051. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.GreaterThanOrEqual, Convert.ToInt32(target.point.start));
  1052. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  1053. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  1054. }
  1055. if (target.point.end > 0)
  1056. {
  1057. string rkFilter = TableQuery.GenerateFilterConditionForInt("Points", QueryComparisons.LessThanOrEqual, Convert.ToInt32(target.point.end));
  1058. if (string.IsNullOrWhiteSpace(rkFilterCombine)) rkFilterCombine = rkFilter;
  1059. else rkFilterCombine = TableQuery.CombineFilters(rkFilterCombine, TableOperators.And, rkFilter);
  1060. }
  1061. filter = TableQuery.CombineFilters(filter, TableOperators.And, rkFilterCombine);
  1062. TableQuery tableQuery = new TableQuery().Where(filter);
  1063. var usersPoints = tablePointsClient.ExecuteQuery(tableQuery);
  1064. if (usersPoints.Any())
  1065. {
  1066. foreach (DynamicTableEntity item in usersPoints)
  1067. {
  1068. string tmid = item.RowKey;
  1069. if (!passTmidPnt.Contains(tmid)) passTmidPnt.Add(tmid);
  1070. }
  1071. }
  1072. }
  1073. }
  1074. //學校
  1075. bool useSchFlg = false;
  1076. List<string> passTmidSch = new List<string>();
  1077. if (target.school != null && target.school.Count > 0)
  1078. {
  1079. useSchFlg = true;
  1080. List<string> schTeacherCodeList = target.school.Select(s => $"Teacher-{s}").ToList();
  1081. string sqlWhereSch = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(schTeacherCodeList)}, c.code)";
  1082. string sqlSch = $"{sqlSel}{sqlWhereSch}";
  1083. await foreach (var item in cosmosClientIes
  1084. .GetContainer(Constant.TEAMModelOS, Constant.School)
  1085. .GetItemQueryIteratorSql<JsonElement>(sqlSch, requestOptions: null))
  1086. {
  1087. string id = item.GetProperty("id").ToString();
  1088. if (!passTmidSch.Contains(id)) passTmidSch.Add(id);
  1089. }
  1090. }
  1091. //TMID
  1092. bool useTmidFlg = false;
  1093. List<string> passTmidMid = new List<string>();
  1094. if (target.tmid != null && target.tmid.Count > 0)
  1095. {
  1096. useTmidFlg = true;
  1097. string sqlWhereTmid = $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(target.tmid)}, c.id)";
  1098. string sqlTmid = $"{sqlSel}{sqlWhereTmid}";
  1099. await foreach (var item in cosmosClientCsv2
  1100. .GetContainer("Core", "ID2")
  1101. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlTmid, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  1102. {
  1103. string id = item.GetProperty("id").ToString();
  1104. if (!passTmidMid.Contains(id)) passTmidMid.Add(id);
  1105. }
  1106. }
  1107. //所有TMID做聯集交集整合
  1108. List<string> passTmid = new List<string>(); //最終條件符合的TMID列表
  1109. ///初始化
  1110. if (passTmidCrt.Count > 0) passTmid = passTmidCrt;
  1111. else if (passTmidGeo.Count > 0) passTmid = passTmidGeo;
  1112. else if (passTmidPrd.Count > 0) passTmid = passTmidPrd;
  1113. else if (passTmidPnt.Count > 0) passTmid = passTmidPnt;
  1114. else if (passTmidSch.Count > 0) passTmid = passTmidSch;
  1115. else if (passTmidMid.Count > 0) passTmid = passTmidMid;
  1116. if (modeToAll.Equals("or")) //聯集
  1117. {
  1118. if (useCrtFlg) passTmid = passTmid.Union(passTmidCrt).ToList();
  1119. if (useGeoFlg) passTmid = passTmid.Union(passTmidGeo).ToList();
  1120. if (usePrdFlg) passTmid = passTmid.Union(passTmidPrd).ToList();
  1121. if (usePntFlg) passTmid = passTmid.Union(passTmidPnt).ToList();
  1122. if (useSchFlg) passTmid = passTmid.Union(passTmidSch).ToList();
  1123. if (useTmidFlg) passTmid = passTmid.Union(passTmidMid).ToList();
  1124. }
  1125. else //交集
  1126. {
  1127. if (useCrtFlg) passTmid = passTmid.Intersect(passTmidCrt).ToList();
  1128. if (useGeoFlg) passTmid = passTmid.Intersect(passTmidGeo).ToList();
  1129. if (usePrdFlg) passTmid = passTmid.Intersect(passTmidPrd).ToList();
  1130. if (usePntFlg) passTmid = passTmid.Intersect(passTmidPnt).ToList();
  1131. if (useSchFlg) passTmid = passTmid.Intersect(passTmidSch).ToList();
  1132. if (useTmidFlg) passTmid = passTmid.Intersect(passTmidMid).ToList();
  1133. }
  1134. //最終ID基本資訊取得
  1135. List<IdName> result = new List<IdName>();
  1136. string sqlBaseInfo = $"SELECT c.id, c.name FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(passTmid)}, c.id)";
  1137. await foreach (var item in cosmosClientCsv2
  1138. .GetContainer("Core", "ID2")
  1139. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base") }))
  1140. {
  1141. string id = item.GetProperty("id").ToString();
  1142. string name = item.GetProperty("name").ToString();
  1143. IdName resultRow = new IdName() { id = id, name = name };
  1144. result.Add(resultRow);
  1145. }
  1146. return Ok(new { state = RespondCode.Ok, data = result });
  1147. }
  1148. catch (Exception ex)
  1149. {
  1150. return BadRequest(new { state = RespondCode.NotFound, data = new List<IdName>() });
  1151. }
  1152. }
  1153. /// <summary>
  1154. /// 寄發訊息API
  1155. /// </summary>
  1156. /// <param name="target"></param>
  1157. /// <param name="type">發送類型</param>
  1158. /// <param name="method">挑選方式</param>
  1159. /// <param name="title">標題</param>
  1160. /// <param name="body">內文</param>
  1161. /// <param name="data">傳遞資料</param>
  1162. /// <param name="action">傳遞動作</param>
  1163. [HttpPost("send-message")]
  1164. #if !DEBUG
  1165. [AuthToken(Roles = "admin")]
  1166. #endif
  1167. public async Task<IActionResult> SendMessage(JsonElement jsonElement)
  1168. {
  1169. SendMessageParam target = (jsonElement.TryGetProperty("target", out JsonElement _target)) ? _target.ToObject<SendMessageParam>() : null; //發送對象
  1170. string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.ToString() : string.Empty; //發送類型 mail:郵件、notify:端外、sms:簡訊
  1171. string method = (jsonElement.TryGetProperty("method", out JsonElement _method)) ? _method.ToString() : string.Empty; //挑選方式 single:個別 multi:批次
  1172. string subject = (jsonElement.TryGetProperty("subject", out JsonElement _subject)) ? _subject.ToString() : string.Empty; //主題 (Email用)
  1173. string title = (jsonElement.TryGetProperty("title", out JsonElement _title)) ? _title.ToString() : string.Empty; //標題
  1174. string body = (jsonElement.TryGetProperty("body", out JsonElement _body)) ? _body.ToString() : string.Empty; //內文
  1175. string sender = (jsonElement.TryGetProperty("sender", out JsonElement _sender)) ? _sender.ToString() : string.Empty; //發送者
  1176. string hubName = (jsonElement.TryGetProperty("hubName", out JsonElement _hubName)) ? _hubName.ToString() : "hita5"; //訊息中樞
  1177. string data = (jsonElement.TryGetProperty("data", out JsonElement _data)) ? _data.ToString() : string.Empty; //額外資料
  1178. long send = (jsonElement.TryGetProperty("send", out JsonElement _send)) ? _send.GetInt64() : 0; //發送時間 0:立即發送
  1179. string template = (jsonElement.TryGetProperty("template", out JsonElement _template)) ? _template.ToString() : string.Empty; //模板ID
  1180. //必須項檢驗
  1181. bool hasMail = false;
  1182. if (target == null || string.IsNullOrWhiteSpace(type) || string.IsNullOrWhiteSpace(method) || string.IsNullOrWhiteSpace(title) || string.IsNullOrWhiteSpace(body)) return BadRequest();
  1183. if(type.Equals("notify"))
  1184. {
  1185. if(string.IsNullOrWhiteSpace(sender)) return BadRequest();
  1186. }
  1187. else if(type.Equals("mail"))
  1188. {
  1189. if (string.IsNullOrWhiteSpace(subject)) return BadRequest();
  1190. hasMail = true;
  1191. }
  1192. string eventKey = "bi-gen-notify";
  1193. string eventId = $"{eventKey}_{_snowflakeId.NextId()}";
  1194. string eventName = "BI send notification";
  1195. var result = await SendMessageCore(target, type, method, subject, title, body, data, sender, hubName, template, send, eventId, eventName, hasMail);
  1196. return Ok(new { state = RespondCode.Ok, result });
  1197. }
  1198. ///寄發訊息核心邏輯
  1199. private async Task<object> SendMessageCore(SendMessageParam target, string type, string method, string subject, string title, string body, string data, string sender, string hubName, string template, long send, string eventId = "", string eventName = "", bool hasMail = false)
  1200. {
  1201. #region target 內容例
  1202. //{
  1203. // "area":[
  1204. // "1234"
  1205. // ],
  1206. // "geo":[
  1207. // {
  1208. // "countryId":"TW",
  1209. // "provinceId":"",
  1210. // "cityId":"30",
  1211. // "type":"tmid"
  1212. // },
  1213. // {
  1214. // "countryId":"TW",
  1215. // "provinceId":"",
  1216. // "cityId":"30",
  1217. // "type":"school"
  1218. // }
  1219. // ],
  1220. // "unit":[
  1221. // "1"
  1222. // ],
  1223. // "school":[
  1224. // "1234"
  1225. // ],
  1226. // "tmid": [
  1227. // "1234"
  1228. // ]
  1229. //}
  1230. #endregion
  1231. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1232. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1233. var (_tmdId, _tmdName, _, _, _, _) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  1234. List<string> tmids_area = await GetTmidByAreaId(target.area, hasMail);
  1235. List<string> tmids_geo = await GetTmidByGeo(target.geo, hasMail);
  1236. List<string> tmids_unit = await GetTmidByUnitId(target.unit, hasMail);
  1237. List<string> tmids_school = await GetTmidBySchoolId(target.school, hasMail);
  1238. List<string> tmids_direct = target.tmid;
  1239. List<string> tmids = new List<string>(); //聯集化
  1240. tmids = tmids.Union(tmids_area).ToList();
  1241. tmids = tmids.Union(tmids_geo).ToList();
  1242. tmids = tmids.Union(tmids_unit).ToList();
  1243. tmids = tmids.Union(tmids_school).ToList();
  1244. tmids = tmids.Union(tmids_direct).ToList();
  1245. tmids = tmids.Distinct().ToList(); //唯一化
  1246. //#if DEBUG //測試模式時限制TMID帳號,正式站佈署時不生效
  1247. // List<string> filterTmid = new List<string>() { "1522758684", "1595321354", "1629875867" }; //"1522758684", "1595321354"
  1248. // tmids = tmids.Intersect(filterTmid).ToList();
  1249. //#endif
  1250. //取得TMID資料
  1251. List<IdInfo> tmidInfos = new List<IdInfo>();
  1252. string sqlBaseInfo = $"SELECT c.id, c.name, c.mail, c.mobile FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(tmids)}, c.id)";
  1253. if(type.Equals("mail")) //發送類型 mail:郵件
  1254. {
  1255. sqlBaseInfo += $" AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail) AND c.mail != '') ";
  1256. }
  1257. else if(type.Equals("sms")) //發送類型 sms:簡訊
  1258. {
  1259. sqlBaseInfo += $" AND (IS_DEFINED(c.mobile) AND NOT IS_NULL(c.mobile) AND c.mobile != '') ";
  1260. }
  1261. await foreach (var item in cosmosClientCsv2
  1262. .GetContainer("Core", "ID2")
  1263. .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
  1264. {
  1265. IdInfo idInfo = new IdInfo();
  1266. idInfo.id = item.GetProperty("id").ToString();
  1267. idInfo.name = (item.TryGetProperty("name", out JsonElement _name)) ? _name.ToString() : string.Empty;
  1268. idInfo.mail = (item.TryGetProperty("mail", out JsonElement _mail)) ? _mail.ToString() : string.Empty;
  1269. idInfo.mobile = (item.TryGetProperty("mobile", out JsonElement _mobile)) ? _mobile.ToString() : string.Empty;
  1270. tmidInfos.Add(idInfo);
  1271. }
  1272. //寄發訊息
  1273. if (type.Equals("notify")) //端內外通知
  1274. {
  1275. List<string> tmIds = tmidInfos.Select(i => i.id).ToList();
  1276. if(send.Equals(0)) //立即寄送
  1277. {
  1278. //訊息寄送
  1279. HttpResponseMessage response = CallPushNotifyApi(tmIds, title, body, sender, hubName, template, data, eventId, eventName);
  1280. //寄送訊息DB記入
  1281. if(response.IsSuccessStatusCode)
  1282. {
  1283. BINotice bINotice = TransMsgRequestToBINotice(type, method, subject, title, body, sender, hubName, target, tmIds, data);
  1284. bINotice.id = Guid.NewGuid().ToString();
  1285. bINotice.createId = _tmdId;
  1286. bINotice.sendTime = (send.Equals(0)) ? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() : send; //先處理"及時寄送","定時寄送"待處理
  1287. await cosmosClientIes.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<BINotice>(bINotice, new PartitionKey("BINotice"));
  1288. }
  1289. var result = new { status = response.StatusCode, content = await response.Content.ReadAsStringAsync() };
  1290. return result;
  1291. }
  1292. else //定時寄送 [待做]
  1293. {
  1294. }
  1295. }
  1296. else if(type.Equals("mail")) //Email
  1297. {
  1298. string defaultTemplate = "d-f1c5abd8247f4be79ceaecdd327e9a68"; //國際站預設模板 ※CN站還沒有
  1299. List<string> mailList = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mail)).Select(i => i.mail).ToList();
  1300. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mail)).Select(i => i.id).ToList();
  1301. //呼叫Email API [未]
  1302. ///模板設定
  1303. if (_option.Location.Contains("Global"))
  1304. {
  1305. if (string.IsNullOrWhiteSpace(template))
  1306. template = defaultTemplate; //若未指定模板ID,用預設模板
  1307. }
  1308. if(string.IsNullOrWhiteSpace(template)) //無模板ID,就不執行
  1309. {
  1310. var result = new { status = HttpStatusCode.BadRequest };
  1311. return result;
  1312. }
  1313. //Email寄送
  1314. bool sendMail = false;
  1315. if (send.Equals(0)) //立即寄送
  1316. {
  1317. List<string> imgArr = new List<string>();
  1318. try
  1319. {
  1320. JsonElement dataJobj = JsonSerializer.Deserialize<JsonElement>(data);
  1321. if(dataJobj.TryGetProperty("img", out JsonElement _img))
  1322. {
  1323. imgArr = _img.ToObject<List<string>>();
  1324. }
  1325. }
  1326. catch (JsonException) { }
  1327. string image = (imgArr.Count > 0) ? imgArr[0] : string.Empty;
  1328. foreach(string email in mailList)
  1329. {
  1330. await CallSendMailApiAsync(email, subject, title, body, template, image);
  1331. sendMail = true;
  1332. }
  1333. //寄送訊息DB記入
  1334. if (sendMail)
  1335. {
  1336. BINotice bINotice = TransMsgRequestToBINotice(type, method, subject, title, body, sender, hubName, target, tmIds, data);
  1337. bINotice.id = Guid.NewGuid().ToString();
  1338. bINotice.createId = _tmdId;
  1339. bINotice.sendTime = (send.Equals(0)) ? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() : send; //先處理"及時寄送","定時寄送"待處理
  1340. await cosmosClientIes.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<BINotice>(bINotice, new PartitionKey("BINotice"));
  1341. }
  1342. var result = new { status = HttpStatusCode.OK, content = string.Empty };
  1343. return result;
  1344. }
  1345. else //定時寄送 [待做]
  1346. {
  1347. }
  1348. }
  1349. else if (type.Equals("sms")) //短訊
  1350. {
  1351. List<string> tmIds = tmidInfos.Where(i => !string.IsNullOrWhiteSpace(i.mobile)).Select(i => i.id).ToList();
  1352. //呼叫短訊API [未]
  1353. var result = new { };
  1354. return result;
  1355. }
  1356. return new { };
  1357. }
  1358. //取得學區所屬學校教師
  1359. private async Task<List<string>> GetTmidByAreaId(List<string> areaIds, bool hasMail)
  1360. {
  1361. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1362. //取得學校ID列表
  1363. List<string> schIds = new List<string>();
  1364. string sqlSch = $"SELECT c.id FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(areaIds)}, c.areaId)";
  1365. ///實體校
  1366. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
  1367. {
  1368. string schId = item.GetProperty("id").ToString();
  1369. schIds.Add(schId);
  1370. }
  1371. ///虛擬校
  1372. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"VirtualBase") }))
  1373. {
  1374. string schId = item.GetProperty("id").ToString();
  1375. if(!schIds.Contains(schId)) schIds.Add(schId);
  1376. }
  1377. //結果輸出
  1378. List<string> tmids = new List<string>();
  1379. tmids = await GetTmidBySchoolId(schIds, hasMail);
  1380. //List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1381. ////取得學校教師ID列表
  1382. //List<string> tmids = new List<string>();
  1383. //string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1384. //await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1385. //{
  1386. // string tmid = item.GetProperty("id").ToString();
  1387. // tmids.Add(tmid);
  1388. //}
  1389. return tmids;
  1390. }
  1391. //取得地理資訊所屬TMID
  1392. private async Task<List<string>> GetTmidByGeo(List<Geo> geos, bool hasMail)
  1393. {
  1394. List<string> tmids = new List<string>();
  1395. foreach (Geo geo in geos)
  1396. {
  1397. if(!string.IsNullOrWhiteSpace(geo.type) && geo.type.Equals("tmid"))
  1398. {
  1399. var (geoInfos, _) = await GetDataByGeo("tmid", "tmid", true, geo.countryId, geo.provinceId, geo.cityId, hasMail);
  1400. foreach (var geoInfo in geoInfos)
  1401. {
  1402. if (!tmids.Contains(geoInfo.id)) tmids.Add(geoInfo.id);
  1403. }
  1404. }
  1405. else if(!string.IsNullOrWhiteSpace(geo.type) && geo.type.Equals("school"))
  1406. {
  1407. var (geoInfos, _) = await GetDataByGeo("school", "tmid", true, geo.countryId, geo.provinceId, geo.cityId, hasMail);
  1408. foreach (var geoInfo in geoInfos)
  1409. {
  1410. if (!tmids.Contains(geoInfo.id)) tmids.Add(geoInfo.id);
  1411. }
  1412. }
  1413. }
  1414. return tmids;
  1415. }
  1416. //取得學校機構所屬學校教師
  1417. private async Task<List<string>> GetTmidByUnitId(List<string> units, bool hasMail = false)
  1418. {
  1419. if (units.Count.Equals(0)) return new List<string>();
  1420. //var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1421. var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
  1422. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1423. List<string> tmids = new List<string>();
  1424. List<string> coreSchIds = new List<string>();
  1425. Dictionary<string, List<string>> schTmidDic = new Dictionary<string, List<string>>(); //學校ID > TMID 字典
  1426. //取得有歸戶的所有TMID
  1427. string sqlEx = "SELECT c.id, c.schoolCode, c.schoolCodeW FROM c WHERE ((IS_DEFINED(c.schoolCode) AND NOT IS_NULL(c.schoolCode)) OR (IS_DEFINED(c.schoolCodeW) AND NOT IS_NULL(c.schoolCodeW)))";
  1428. if (hasMail) sqlEx += " AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)) ";
  1429. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  1430. {
  1431. string tmid = item.GetProperty("id").ToString();
  1432. string schoolCode = (item.TryGetProperty("schoolCode", out JsonElement _schoolCode)) ? _schoolCode.ToString() : string.Empty;
  1433. string schoolCodeW = (item.TryGetProperty("schoolCodeW", out JsonElement _schoolCodeW)) ? _schoolCodeW.ToString() : string.Empty;
  1434. string schId = (!string.IsNullOrWhiteSpace(schoolCode)) ? schoolCode : (!string.IsNullOrWhiteSpace(schoolCodeW)) ? schoolCodeW : string.Empty;
  1435. if (!string.IsNullOrWhiteSpace(schId))
  1436. {
  1437. if (!coreSchIds.Contains(schId)) coreSchIds.Add(schId);
  1438. if (schTmidDic.ContainsKey(schId))
  1439. {
  1440. if (!schTmidDic[schId].Contains(tmid)) schTmidDic[schId].Add(tmid);
  1441. }
  1442. else
  1443. {
  1444. schTmidDic.Add(schId, new List<string>() { tmid });
  1445. }
  1446. }
  1447. }
  1448. //取得Core學校ID及類型
  1449. string coreSql = "SELECT c.shortCode, c.unitType FROM c";
  1450. string coreWhere = $" WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(coreSchIds)}, c.shortCode) ";
  1451. string coreWhereUnittype = string.Empty;
  1452. if (units.Contains("1"))
  1453. {
  1454. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1455. coreWhereUnittype += $" ARRAY_CONTAINS(['1','8'], c.unitType) ";
  1456. }
  1457. if (units.Contains("2"))
  1458. {
  1459. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1460. coreWhereUnittype += $" c.unitType = '2' ";
  1461. }
  1462. if (units.Contains("3"))
  1463. {
  1464. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1465. coreWhereUnittype += $" c.unitType = '3' ";
  1466. }
  1467. if (units.Contains("4"))
  1468. {
  1469. if (!string.IsNullOrWhiteSpace(coreWhereUnittype)) coreWhereUnittype += " OR ";
  1470. coreWhereUnittype += $" ARRAY_CONTAINS(['4','5','6','7','9'], c.unitType) ";
  1471. }
  1472. if (!string.IsNullOrWhiteSpace(coreWhereUnittype))
  1473. {
  1474. coreWhere += $" AND ({coreWhereUnittype})";
  1475. }
  1476. Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
  1477. string sqlCore = $"{coreSql}{coreWhere}";
  1478. await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
  1479. {
  1480. string shortCode = item.GetProperty("shortCode").ToString();
  1481. string unitType = (item.TryGetProperty("unitType", out JsonElement _unitType)) ? _unitType.ToString() : string.Empty;
  1482. if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
  1483. }
  1484. //學校類型轉換
  1485. //Dictionary<string, string> finalSchUnitTypeDic = new Dictionary<string, string>();
  1486. //foreach (KeyValuePair<string, string> item in coreSchUnitTypeDic)
  1487. //{
  1488. // string schId = item.Key;
  1489. // string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
  1490. // string unitTypeF = string.Empty; //機構類型(最終判斷)
  1491. // if (!string.IsNullOrWhiteSpace(coreUnitType))
  1492. // {
  1493. // switch (coreUnitType)
  1494. // {
  1495. // case "1": //基礎教育機構
  1496. // case "8": //學前教育
  1497. // unitTypeF = "1"; // => 基礎教育機構(K-小學)
  1498. // break;
  1499. // case "2": //中等教育機構
  1500. // unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
  1501. // break;
  1502. // case "3": //高等教育機構
  1503. // unitTypeF = "3"; // => 高等教育機構(大學、研究所)
  1504. // break;
  1505. // case "4": //政府單位機構
  1506. // case "5": //NGO機構
  1507. // case "6": //企業機構
  1508. // case "7": //其他
  1509. // case "9": //特殊教育
  1510. // unitTypeF = "4"; // => 其他
  1511. // break;
  1512. // }
  1513. // }
  1514. // finalSchUnitTypeDic.Add(schId, unitTypeF);
  1515. //}
  1516. //結果輸出
  1517. List<string> filterSchIds = coreSchUnitTypeDic.Keys.ToList();
  1518. var schTmidLists = schTmidDic.Where(s => filterSchIds.Contains(s.Key)).Select(s => s.Value).ToList();
  1519. foreach(List<string> schTmid in schTmidLists)
  1520. {
  1521. tmids.AddRange(schTmid);
  1522. }
  1523. tmids = tmids.Distinct().ToList();
  1524. return tmids;
  1525. }
  1526. //取得歸戶學校的TMID
  1527. private async Task<List<string>> GetTmidBySchoolId(List<string> schIds, bool hasMail = false)
  1528. {
  1529. var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
  1530. List<string> tmids = new List<string>();
  1531. string sqlEx = $"SELECT c.id, c.schoolCode, c.schoolCodeW FROM c WHERE ((ARRAY_CONTAINS({JsonSerializer.Serialize(schIds)}, c.schoolCode) OR ARRAY_CONTAINS({JsonSerializer.Serialize(schIds)}, c.schoolCodeW))) ";
  1532. if (hasMail) sqlEx += " AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail) AND c.mail != '')";
  1533. await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
  1534. {
  1535. string tmid = item.GetProperty("id").ToString();
  1536. string schoolCode = (item.TryGetProperty("schoolCode", out JsonElement _schoolCode)) ? _schoolCode.ToString() : string.Empty;
  1537. string schoolCodeW = (item.TryGetProperty("schoolCodeW", out JsonElement _schoolCodeW)) ? _schoolCodeW.ToString() : string.Empty;
  1538. string schId = (!string.IsNullOrWhiteSpace(schoolCode)) ? schoolCode : (!string.IsNullOrWhiteSpace(schoolCodeW)) ? schoolCodeW : string.Empty;
  1539. if(schIds.Contains(schId)) tmids.Add(tmid);
  1540. }
  1541. ////取得學校ID列表
  1542. //List<string> teacherCodes = schIds.Select(s => $"Teacher-{s}").ToList();
  1543. ////取得學校教師ID列表
  1544. //List<string> tmids = new List<string>();
  1545. //string sqlTch = $"SELECT DISTINCT c.id FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code)";
  1546. //await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
  1547. //{
  1548. // string tmid = item.GetProperty("id").ToString();
  1549. // tmids.Add(tmid);
  1550. //}
  1551. return tmids;
  1552. }
  1553. /// <summary>
  1554. /// 寄發端外通知
  1555. /// </summary>
  1556. /// <param name="tmIds"></param>
  1557. /// <param name="title"></param>
  1558. /// <param name="body"></param>
  1559. /// <param name="eventId"></param>
  1560. /// <param name="eventName"></param>
  1561. /// <param name="data"></param>
  1562. /// <returns></returns>
  1563. private HttpResponseMessage CallPushNotifyApi(List<string> tmIds, string title, string body, string sender, string hubName, string template, string data, string eventId = "", string eventName = "")
  1564. {
  1565. NotifyData notify = new NotifyData();
  1566. notify.hubName = hubName;
  1567. notify.sender = sender;
  1568. notify.tags = tmIds.Select(s => $"{s}_{sender}").ToList();
  1569. notify.title = title;
  1570. notify.body = body;
  1571. notify.eventId = eventId;
  1572. notify.eventName = eventName;
  1573. notify.data = data;
  1574. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  1575. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  1576. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  1577. var client = _httpClient;
  1578. string sendSite = (_option.Location.Contains("China")) ? "China" : "Global";
  1579. var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, sendSite).Result;
  1580. if (client.DefaultRequestHeaders.Contains("Authorization"))
  1581. {
  1582. client.DefaultRequestHeaders.Remove("Authorization");
  1583. }
  1584. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  1585. HttpResponseMessage responseMessage = client.PostAsJsonAsync($"{url}/service/PushNotify", notify).Result;
  1586. return responseMessage;
  1587. }
  1588. private async Task CallSendMailApiAsync(string email, string subject, string title, string body, string template, string image)
  1589. {
  1590. dynamic mailVars = new ExpandoObject();
  1591. mailVars.sub = subject;
  1592. mailVars.title = title;
  1593. mailVars.body = body;
  1594. if (!string.IsNullOrWhiteSpace(image))
  1595. mailVars.image = image;
  1596. await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", email }, { "tid", template }, { "vars", mailVars } }, _option.Location, _configuration);
  1597. }
  1598. /// <summary>
  1599. /// 取得訊息寄送紀錄
  1600. /// </summary>
  1601. /// <param name="msgType"></param>
  1602. /// <param name="selType"></param>
  1603. /// <param name="theme">標題(title)</param>
  1604. /// <param name="content">內文</param>
  1605. /// <param name="source">發送源(HiTeach、IES、Sokrates、Auth、Event)</param>
  1606. /// <returns></returns>
  1607. [HttpPost("get-notice-history")]
  1608. #if !DEBUG
  1609. [AuthToken(Roles = "admin")]
  1610. #endif
  1611. public async Task<List<BINotice>> GetBINoticeHistory(JsonElement jsonElement)
  1612. {
  1613. string msgType = (jsonElement.TryGetProperty("msgType", out JsonElement _msgType)) ? _msgType.ToString() : string.Empty; //發送類型 mail:郵件、notify:端外、sms:簡訊
  1614. string selType = (jsonElement.TryGetProperty("selType", out JsonElement _selType)) ? _selType.ToString() : string.Empty; //挑選方式 single:個別 multi:批次
  1615. string theme = (jsonElement.TryGetProperty("theme", out JsonElement _theme)) ? _theme.ToString() : string.Empty; //標題(title)
  1616. string content = (jsonElement.TryGetProperty("content", out JsonElement _content)) ? _content.ToString() : string.Empty; //內文
  1617. string source = (jsonElement.TryGetProperty("source", out JsonElement _source)) ? _source.ToString() : string.Empty; //发送消息来源 HiTeach、IES、Sokrates、Auth、Event
  1618. string createId = (jsonElement.TryGetProperty("createId", out JsonElement _createId)) ? _createId.ToString() : string.Empty;
  1619. Geo geo = (jsonElement.TryGetProperty("geo", out JsonElement _geo)) ? _geo.ToObject<Geo>() : null;
  1620. List<string> unitType = (jsonElement.TryGetProperty("unitType", out JsonElement _unitType)) ? _unitType.ToObject<List<string>>() : null;
  1621. List<string> school = (jsonElement.TryGetProperty("school", out JsonElement _school)) ? _school.ToObject<List<string>>() : null;
  1622. List<string> crowdIds = (jsonElement.TryGetProperty("crowdIds", out JsonElement _crowdIds)) ? _crowdIds.ToObject<List<string>>() : null; //寄送對象(tmid列表)
  1623. long sendTimeFrom = (jsonElement.TryGetProperty("sendTimeFrom", out JsonElement _sendTimeFrom)) ? _sendTimeFrom.GetInt64() : 0;
  1624. long sendTimeTo = (jsonElement.TryGetProperty("sendTimeTo", out JsonElement _sendTimeTo)) ? _sendTimeTo.GetInt64() : 0;
  1625. var cosmosClientIes = _azureCosmos.GetCosmosClient();
  1626. List<BINotice> result = new List<BINotice> ();
  1627. string sqlWhere = string.Empty;
  1628. if(!string.IsNullOrWhiteSpace(msgType))
  1629. sqlWhere += $" AND c.msgType = '{msgType}' ";
  1630. if (!string.IsNullOrWhiteSpace(selType))
  1631. sqlWhere += $" AND c.selType = '{selType}' ";
  1632. if (!string.IsNullOrWhiteSpace(theme))
  1633. sqlWhere += $" AND CONTAINS(c.theme, '{theme}') ";
  1634. if (!string.IsNullOrWhiteSpace(content))
  1635. sqlWhere += $" AND CONTAINS(c.content, '{content}') ";
  1636. if (!string.IsNullOrWhiteSpace(source))
  1637. sqlWhere += $" AND c.source = '{source}' ";
  1638. if (geo != null)
  1639. {
  1640. if(geo.type.Equals("tmid"))
  1641. sqlWhere += $" AND cs.mode = 'tmidGeo' ";
  1642. else if(geo.type.Equals("school"))
  1643. sqlWhere += $" AND cs.mode = 'schGeo' ";
  1644. if (!string.IsNullOrWhiteSpace(geo.countryId))
  1645. sqlWhere += $" AND cs.countryId = '{geo.countryId}' ";
  1646. if (!string.IsNullOrWhiteSpace(geo.provinceId))
  1647. sqlWhere += $" AND cs.provinceId = '{geo.provinceId}' ";
  1648. if (!string.IsNullOrWhiteSpace(geo.cityId))
  1649. sqlWhere += $" AND cs.cityId = '{geo.cityId}' ";
  1650. if (!string.IsNullOrWhiteSpace(geo.distId))
  1651. sqlWhere += $" AND cs.distId = '{geo.distId}' ";
  1652. }
  1653. if (school != null && school.Count > 0)
  1654. sqlWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(school)}, cs.school) ";
  1655. if (crowdIds != null && crowdIds.Count > 0)
  1656. sqlWhere += $" AND EXISTS( SELECT VALUE 1 FROM crowdId IN c.crowdIds WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(crowdIds)}, crowdId) ) ";
  1657. if (unitType != null && unitType.Count > 0)
  1658. sqlWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(unitType)}, cs.unitType) ";
  1659. if (sendTimeFrom > 0)
  1660. sqlWhere += $" AND c.sendTime >= {sendTimeFrom} ";
  1661. if (sendTimeTo > 0)
  1662. sqlWhere += $" AND c.sendTime <= {sendTimeTo} ";
  1663. string sql = $"SELECT c.id, c.msgType, c.selType, c.hubName, c.subject, c.template, c.search, c.data, c.type, c.theme, c.content, c.crowd, c.crowdIds, c.createId, c.sendTime, c.createTime, c.source FROM c JOIN cs IN c.search WHERE 1=1 {sqlWhere}";
  1664. await foreach (var item in cosmosClientIes.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIteratorSql<BINotice>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"BINotice") }))
  1665. {
  1666. result.Add(item);
  1667. }
  1668. return result;
  1669. }
  1670. //將訊息寄送轉換為訊息寄送DB紀錄架構
  1671. private BINotice TransMsgRequestToBINotice(string msgType, string method, string subject, string title, string body, string sender, string hubName, SendMessageParam target, List<string> tmids, string data)
  1672. {
  1673. List<PickParam> searchParams = new List<PickParam>();
  1674. ///學區
  1675. if (target.area.Count > 0)
  1676. {
  1677. foreach (string areaId in target.area)
  1678. {
  1679. searchParams.Add(new PickParam() { mode = "area", areaId = areaId });
  1680. }
  1681. }
  1682. ///地理資訊
  1683. if (target.geo.Count > 0)
  1684. {
  1685. foreach (Geo geo in target.geo)
  1686. {
  1687. PickParam pickParam = new PickParam() { mode = (geo.type.Equals("tmid")) ? "tmidGeo" : "schGeo" };
  1688. if (!string.IsNullOrWhiteSpace(geo.countryId)) pickParam.countryId = geo.countryId;
  1689. if (!string.IsNullOrWhiteSpace(geo.provinceId)) pickParam.provinceId = geo.provinceId;
  1690. if (!string.IsNullOrWhiteSpace(geo.cityId)) pickParam.cityId = geo.cityId;
  1691. if (!string.IsNullOrWhiteSpace(geo.distId)) pickParam.distId = geo.distId;
  1692. }
  1693. }
  1694. ///教育機構
  1695. if (target.unit.Count > 0)
  1696. {
  1697. foreach (string unitType in target.unit)
  1698. {
  1699. searchParams.Add(new PickParam() { mode = "unit", unitType = unitType });
  1700. }
  1701. }
  1702. ///學校
  1703. if (target.school.Count > 0)
  1704. {
  1705. foreach (string schId in target.school)
  1706. {
  1707. searchParams.Add(new PickParam() { mode = "school", school = schId });
  1708. }
  1709. }
  1710. ///TMID
  1711. if (target.tmid.Count > 0)
  1712. {
  1713. searchParams.Add(new PickParam() { mode = "tmid", tmId = target.tmid });
  1714. }
  1715. BINotice bINotice = new BINotice()
  1716. {
  1717. msgType = msgType,
  1718. selType = method,
  1719. search = searchParams,
  1720. crowdIds = tmids,
  1721. theme = title,
  1722. content = body,
  1723. subject = subject,
  1724. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1725. source = sender,
  1726. hubName = hubName,
  1727. data = data
  1728. };
  1729. return bINotice;
  1730. }
  1731. private string GetDictionaryKeyByValue(Dictionary<string, string> dic, string value)
  1732. {
  1733. string result = string.Empty;
  1734. foreach(KeyValuePair<string, string> d in dic)
  1735. {
  1736. if(d.Value.Equals(value))
  1737. {
  1738. result = d.Key;
  1739. }
  1740. }
  1741. return result;
  1742. }
  1743. /// <summary>
  1744. /// 取得TMID資訊 接收參數class
  1745. /// </summary>
  1746. public record GetTmidInfoParam
  1747. {
  1748. public string mode { get; set; } //and or
  1749. public StartEnd creatTime { get; set; }
  1750. public Geo geo { get; set; }
  1751. public Product product { get; set; }
  1752. public StartEnd point { get; set; }
  1753. public List<string> school { get; set; }
  1754. public List<string> tmid { get; set; }
  1755. public bool hasMail { get; set; } = false;
  1756. public record StartEnd
  1757. {
  1758. public long start { get; set; }
  1759. public long end { get; set; }
  1760. }
  1761. public record Product
  1762. {
  1763. public string mode { get; set; } //and or
  1764. public List<string> id { get; set; } = new(); //產品類型
  1765. }
  1766. }
  1767. public record Geo
  1768. {
  1769. public string countryId { get; set; }
  1770. public string provinceId { get; set; }
  1771. public string cityId { get; set; }
  1772. public string distId { get; set; }
  1773. public string type { get; set; } //tmid、school
  1774. }
  1775. /// <summary>
  1776. /// 發送訊息核心邏輯 接收參數class
  1777. /// </summary>
  1778. public record SendMessageParam
  1779. {
  1780. public List<string> area { get; set; } = new(); //學區ID
  1781. public List<Geo> geo { get; set; } = new();
  1782. public List<string> unit { get; set; } = new(); //學校機構
  1783. public List<string> school { get; set; } = new(); //學校ID
  1784. public List<string> tmid { get; set; } = new(); //TMID
  1785. }
  1786. //取得學校機構ID及名稱
  1787. public Dictionary<string, string> getSchoolUnitName(string lang)
  1788. {
  1789. Dictionary<string, string> tw = new Dictionary<string, string>();
  1790. tw.Add("1", "基礎教育機構(K-小學)");
  1791. tw.Add("2", "中等教育機構(國中、高中/職)");
  1792. tw.Add("3", "高等教育機構(大學、研究所)");
  1793. tw.Add("4", "其他");
  1794. Dictionary<string, string> cn = new Dictionary<string, string>();
  1795. cn.Add("1", "基础教育机构(K-小学)");
  1796. cn.Add("2", "中等教育机构(初中、高中/职)");
  1797. cn.Add("3", "高等教育机构(大学、研究生院)");
  1798. cn.Add("4", "其他");
  1799. if(lang.Equals("zh-cn")) return cn;
  1800. else return tw;
  1801. }
  1802. /// <summary>
  1803. /// TMID基本進階資訊(base-ex)
  1804. /// </summary>
  1805. private class TmidInfo
  1806. {
  1807. public string id { get; set; }
  1808. public string name { get; set; }
  1809. public string mobile { get; set; }
  1810. public string mail { get; set; }
  1811. public string countryCode { get; set; }
  1812. public string country { get; set; }
  1813. public string countryName { get; set; }
  1814. public string province { get; set; }
  1815. public string provinceName { get; set; }
  1816. public string city { get; set; }
  1817. public string cityName { get; set; }
  1818. public string dist { get; set; }
  1819. public string distName { get; set; }
  1820. public string schoolCode { get; set; }
  1821. public string schoolCodeW { get; set; }
  1822. public string schId { get; set; }
  1823. }
  1824. /// <summary>
  1825. /// 學區、地理位置、機構類型 回傳信息
  1826. /// </summary>
  1827. public record AreaInfo
  1828. {
  1829. public string id { get; set; }
  1830. public string name { get; set; }
  1831. public int scCnt { get; set; } = 0;
  1832. public int tchCnt { get; set; } = 0;
  1833. public List<AreaSchoolInfo> lists { get; set; } = new();
  1834. }
  1835. /// <summary>
  1836. /// 學區附屬學校
  1837. /// </summary>
  1838. public record AreaSchoolInfo
  1839. {
  1840. public string id { get; set; }
  1841. public string name { get; set; }
  1842. public int tchCnt { get; set; } = 0;
  1843. }
  1844. /// <summary>
  1845. /// TMID個人積分
  1846. /// </summary>
  1847. private record TmidPoints
  1848. {
  1849. public int points { get; set; } = 0; //累積的點數(只加不減)
  1850. public int balance { get; set; } = 0; //可用的點數
  1851. public int level { get; set; } = 0; //等級
  1852. }
  1853. private record IdName
  1854. {
  1855. public string id { get; set; }
  1856. public string name { get; set; }
  1857. }
  1858. private record IdInfo : IdName
  1859. {
  1860. public string mail { get; set; }
  1861. public string mobile { get; set; }
  1862. }
  1863. /// <summary>
  1864. /// 替換字串最後一個字
  1865. /// </summary>
  1866. /// <param name="str">目標字串</param>
  1867. /// <param name="target">被替換的字串</param>
  1868. /// <param name="alternative">要換上的字串</param>
  1869. /// <returns></returns>
  1870. public string ReplaceLastMatch(string str, string target, string alternative)
  1871. {
  1872. var pos = str.LastIndexOf(target);
  1873. if (pos >= 0)
  1874. return str.Substring(0, pos) + alternative + str.Substring(pos + target.Length);
  1875. return str;
  1876. }
  1877. //地區要去除的特殊字
  1878. public List<string> comeRemoveStr = new List<string>() { "省", "市", "区", "自治州", "县", "旗", "盟", "回族", "藏族", "羌族", "哈尼族", "彝族", "壮族", "苗族", "维吾尔", "自治", "地區", "區", "縣" };
  1879. }
  1880. }