Переглянути джерело

修正發送訊息 取得地理資訊API、取得教育機構API:取得學校由IES5學校轉為TMID歸屬學校

jeff 3 місяців тому
батько
коміт
b304125b59
1 змінених файлів з 90 додано та 101 видалено
  1. 90 101
      TEAMModelBI/Controllers/BICommon/BINoticeController.cs

+ 90 - 101
TEAMModelBI/Controllers/BICommon/BINoticeController.cs

@@ -418,12 +418,13 @@ namespace TEAMModelBI.Controllers.BICommon
             string cityId = (jsonElement.TryGetProperty("cityId", out JsonElement _cityId)) ? _cityId.GetString() : string.Empty; //市ID
             string distId = (jsonElement.TryGetProperty("dist", out JsonElement _distJobj)) ? _distJobj.GetString() : string.Empty; //區ID
             string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : "school"; //類型 tmid、school
+            bool hasMail = (jsonElement.TryGetProperty("hasMail", out JsonElement _hasMail)) ? _hasMail.GetBoolean() : false; //篩選是否有Email true:會排除沒有Mail的醍摩豆帳號
             string countryName = string.Empty;
             string provinceName = string.Empty;
             string cityName = string.Empty;
             string distName = string.Empty;
 
-            var (geoInfos, groupKey) = await GetDataByGeo(type, "geo", showList, countryId, provinceId, cityId);
+            var (geoInfos, groupKey) = await GetDataByGeo(type, "geo", showList, countryId, provinceId, cityId, hasMail);
             return Ok(new { state = 200, dataType = groupKey, data = geoInfos });
         }
 
@@ -438,133 +439,100 @@ namespace TEAMModelBI.Controllers.BICommon
 #endif
         public async Task<IActionResult> GetUnitTypes(JsonElement jsonElement)
         {
-            var cosmosClient = _azureCosmos.GetCosmosClient();
+            //var cosmosClient = _azureCosmos.GetCosmosClient();
+            var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
             var coreCosmosClientCn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
 
             string type = (jsonElement.TryGetProperty("type", out JsonElement _type)) ? _type.GetString() : string.Empty; //教育機構類型 1:基礎教育機構(K-小學) 2:中等教育機構(國中、高中/職) 3:高等教育機構(大學、研究所) 4:其他
             bool showList = (jsonElement.TryGetProperty("showList", out JsonElement _showList)) ? _showList.GetBoolean() : false; //是否列出學校
-
-            //檢索類型轉換
-            string iesSql = "SELECT c.id, c.name, c.type FROM c WHERE 1=1 ";
-            string iesWhere = string.Empty;
-            //IES學校ID取得、學校類型取得
-            List<string> iesSchIds = new List<string>();
-            Dictionary<string, string> schTypeDic = new Dictionary<string, string>(); //IES5學校ID與學校類型對照表
-            Dictionary<string, string> schNameDic = new Dictionary<string, string>(); //IES5學校ID與學校名稱
-            List<string> teacherCodes = new List<string>(); //用來取得老師資料的分區鍵
-            string sqlSch = $"{iesSql}{iesWhere}";
-            ///實體校
-            await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlSch, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Base") }))
+            bool hasMail = (jsonElement.TryGetProperty("hasMail", out JsonElement _hasMail)) ? _hasMail.GetBoolean() : false; //篩選是否有Email true:會排除沒有Mail的醍摩豆帳號            
+
+            //取得ID帳號中所有的歸戶學校ID
+            List<string> coreSchIds = new List<string>();
+            Dictionary<string, List<string>> schTmidDic = new Dictionary<string, List<string>>(); //學校ID > TMID 字典
+            string sqlEx = "SELECT c.id, c.schoolCode, c.schoolCodeW FROM c WHERE IS_DEFINED(c.schoolCode) AND NOT IS_NULL(c.schoolCode) AND IS_DEFINED(c.schoolCodeW) AND NOT IS_NULL(c.schoolCodeW)";
+            if (hasMail) sqlEx += " AND IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail) ";
+            await foreach (var item in cosmosClientCsv2.GetContainer("Core", "ID2").GetItemQueryIteratorSql<JsonElement>(queryText: sqlEx, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base-ex") }))
             {
-                string schId = item.GetProperty("id").ToString();
-                string schName = item.GetProperty("name").ToString();
-                int schType = item.GetProperty("type").GetInt32();
-                iesSchIds.Add(schId);
-                if (!schTypeDic.ContainsKey(schId)) schTypeDic.Add(schId, schType.ToString());
-                if (!schNameDic.ContainsKey(schId)) schNameDic.Add(schId, schName);
-                if (!teacherCodes.Contains($"Teacher-{schId}")) teacherCodes.Add($"Teacher-{schId}");
+                string tmid = item.GetProperty("id").ToString();
+                string shortCode = (item.TryGetProperty("shortCode", out JsonElement _shortCode)) ? _shortCode.ToString() : string.Empty;
+                string schoolCodeW = (item.TryGetProperty("schoolCodeW", out JsonElement _schoolCodeW)) ? _schoolCodeW.ToString() : string.Empty;
+                string schId = (!string.IsNullOrWhiteSpace(shortCode)) ? shortCode : (!string.IsNullOrWhiteSpace(schoolCodeW)) ? schoolCodeW : string.Empty;
+                if (!string.IsNullOrWhiteSpace(schId))
+                {
+                    if(!coreSchIds.Contains(schId)) coreSchIds.Add(schId);
+                    if (schTmidDic.ContainsKey(schId)) {
+                        if (!schTmidDic[schId].Contains(tmid)) schTmidDic[schId].Add(tmid);
+                    }
+                    else
+                    {
+                        schTmidDic.Add(schId, new List<string>() { tmid });
+                    }
+                }
             }
             //Core 篩選取得的學校、學校類型取得
-            string coreSql = "SELECT c.shortCode, c.unitType FROM c";
-            string coreWhere = $" WHERE 1=1 AND ARRAY_CONTAINS({JsonSerializer.Serialize(iesSchIds)}, c.shortCode) ";
-            Dictionary<string, string> coreSchUnitTypeDic = new Dictionary<string, string>(); //Core學校ID與學校類型對照表
+            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";
+            string coreWhere = $" WHERE 1=1 AND ARRAY_CONTAINS({JsonSerializer.Serialize(coreSchIds)}, c.shortCode) AND IS_DEFINED(c.unitType) AND NOT IS_NULL(c.unitType) ";
+            switch (type)
+            {
+                case "1": ///基礎教育機構(K-小學)
+                    coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "1", "8" })}, c.unitType)";
+                    break;
+                case "2": ///中等教育機構(國中、高中/職)
+                    coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "2" })}, c.unitType)";
+                    break;
+                case "3": ///高等教育機構(大學、研究所)
+                    coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "3" })}, c.unitType)";
+                    break;
+                case "4": ///其他
+                    coreWhere += $" AND ARRAY_CONTAINS({JsonSerializer.Serialize(new List<string>() { "4", "5", "6", "7", "9" })}, c.unitType)";
+                    break;
+            }
+            string lang = (_option.Location.Contains("China")) ? "zh_cn" : "zh_tw";
+            Dictionary<string, string> unitNameDic = getSchoolUnitName(lang);
+            List<AreaInfo> unitInfos = new(); //輸出結果
             string sqlCore = $"{coreSql}{coreWhere}";
             await foreach (var item in coreCosmosClientCn.GetContainer("Core", "School").GetItemQueryIteratorSql<JsonElement>(queryText: sqlCore, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"base") }))
             {
+                string schName = item.GetProperty("name").ToString();
                 string shortCode = item.GetProperty("shortCode").ToString();
-                string unitType = item.GetProperty("unitType").ToString();
-                if (!coreSchUnitTypeDic.ContainsKey(shortCode)) coreSchUnitTypeDic.Add(shortCode, unitType);
-            }
-            //IES學校數及老師數取得
-            Dictionary<string, int> schTeacherCntDic = new Dictionary<string, int>(); //key: schoolId val:學校教師數
-            string sqlTch = $"SELECT REPLACE(c.code, 'Teacher-', '') as schoolId, COUNT(c.id) AS tchCnt FROM c WHERE c.pk = 'Teacher' AND c.status = 'join' AND ARRAY_CONTAINS({JsonSerializer.Serialize(teacherCodes)}, c.code) GROUP BY c.code";
-            await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<JsonElement>(queryText: sqlTch, requestOptions: null))
-            {
-                string schId = item.GetProperty("schoolId").ToString();
-                int tchCnt = item.GetProperty("tchCnt").GetInt32();
-                schTeacherCntDic.Add(schId, tchCnt);
-            }
-
-            //資料整理1 有教師則記入
-            List<AreaInfo> unitInfos = new();
-            foreach (KeyValuePair<string, int> item in schTeacherCntDic)
-            {
-                string schId = item.Key;
-                int tchCnt = item.Value;
-                string coreUnitType = (coreSchUnitTypeDic.ContainsKey(schId)) ? coreSchUnitTypeDic[schId] : string.Empty;
-                string iesUnitType = (schTypeDic.ContainsKey(schId)) ? schTypeDic[schId] : string.Empty;
-                string unitTypeF = string.Empty; //機構類型(最終判斷) 
-                if (!string.IsNullOrWhiteSpace(coreUnitType))
-                {
-                    switch (coreUnitType)
-                    {
-                        case "1": //基礎教育機構
-                        case "8": //學前教育
-                            unitTypeF = "1"; // => 基礎教育機構(K-小學)
-                            break;
-                        case "2": //中等教育機構
-                            unitTypeF = "2"; // => 中等教育機構(國中、高中/職)
-                            break;
-
-                        case "3": //高等教育機構
-                            unitTypeF = "3"; // => 高等教育機構(大學、研究所)
-                            break;
-                        case "4": //政府單位機構
-                        case "5": //NGO機構
-                        case "6": //企業機構
-                        case "7": //其他
-                        case "9": //特殊教育
-                            unitTypeF = "4"; // => 其他
-                            break;
-                    }
-                }
-                else if (!string.IsNullOrWhiteSpace(iesUnitType))
-                {
-                    switch (iesUnitType)  //1 普教,2 高职教
-                    {
-                        case "1": //國教(K-12)
-                            unitTypeF = "1"; // => 基礎教育機構(K-小學)
-                            break;
-                        case "2": //大專院校
-                            unitTypeF = "3"; // => 高等教育機構(大學、研究所)
-                            break;
-                        default: //未設定
-                            unitTypeF = "4"; // => 其他
-                            break;
-                    }
-                }
-                string lang = (_option.Location.Contains("China")) ? "zh_cn" : "zh_tw";
-                Dictionary<string, string> unitNameDic = getSchoolUnitName(lang);
-                string id = unitTypeF;
-                string name = unitNameDic[id];
-                AreaInfo unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
+                string unitType = item.GetProperty("unitTypeFix").ToString();
+                ///結果製作
+                string unitId = unitType;
+                string unitName = unitNameDic[unitId];
+                AreaInfo unitInfo = unitInfos.Where(u => u.id.Equals(unitId)).FirstOrDefault();
                 if (unitInfo == null)
                 {
                     AreaInfo unitInfoCrt = new AreaInfo();
-                    unitInfoCrt.id = id;
-                    unitInfoCrt.name = name;
+                    unitInfoCrt.id = unitId;
+                    unitInfoCrt.name = unitName;
                     unitInfos.Add(unitInfoCrt);
-                    unitInfo = unitInfos.Where(u => u.id.Equals(id)).FirstOrDefault();
+                    unitInfo = unitInfos.Where(u => u.id.Equals(unitId)).FirstOrDefault();
                 }
                 unitInfo.scCnt++;
+                int tchCnt = (schTmidDic.ContainsKey(shortCode)) ? schTmidDic[shortCode].Count : 0;
                 unitInfo.tchCnt += tchCnt;
                 if (showList)
                 {
-                    AreaSchoolInfo sch = new AreaSchoolInfo() { id = schId, name = schNameDic[schId], tchCnt = tchCnt };
+                    AreaSchoolInfo sch = new AreaSchoolInfo() { id = shortCode, name = schName, tchCnt = tchCnt };
                     unitInfo.lists.Add(sch);
                 }
             }
-            if (!string.IsNullOrWhiteSpace(type))
-            {
-                unitInfos = unitInfos.Where(u => u.id.Equals(type)).ToList();
-            }
 
             return Ok(new { state = 200, data = unitInfos });
-
         }
 
         //由地理資訊取得TMID或學校核心邏輯
-        private async Task<(List<AreaInfo>,string)> GetDataByGeo (string type, string output, bool showList, string countryId = "", string provinceId = "", string cityId = "")
+        /// <summary>由地理資訊取得TMID或學校核心邏輯</summary>
+        /// <param name="type">地理資訊取得對象:tmid、school</param>
+        /// <param name="output">輸出:tmid、school</param>
+        /// <param name="showList">輸出項lists是否要有值</param>
+        /// <param name="countryId"></param>
+        /// <param name="provinceId"></param>
+        /// <param name="cityId"></param>
+        /// <param name="hasMail">醍魔豆帳號是否有Email</param>
+        /// <returns></returns>
+        private async Task<(List<AreaInfo>,string)> GetDataByGeo (string type, string output, bool showList, string countryId = "", string provinceId = "", string cityId = "", bool hasMail = false)
         {
             var cosmosClientCsv2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
             var cosmosClientCsv2Cn = _azureCosmos.GetCosmosClient(name: "CoreServiceV2CnRead");
@@ -685,6 +653,12 @@ namespace TEAMModelBI.Controllers.BICommon
                     }
                     sqlWhere += $" AND ({tmpSql}) ";
                 }
+                //有Email篩選
+                if (hasMail)
+                {
+                    string tmpSql = "IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)";
+                    sqlWhere += $" AND ({tmpSql}) ";
+                }
                 if (!string.IsNullOrWhiteSpace(sqlWhere))
                 {
                     Regex regex = new Regex("^[a-zA-Z0-9]{2}$");
@@ -849,6 +823,12 @@ namespace TEAMModelBI.Controllers.BICommon
                 List<string> schIds = new List<string>(); //要取得的學校ID
                 //取得ID資訊
                 sqlWhere = $" ((NOT IS_NULL(c.schoolCode) AND c.schoolCode != '') OR (NOT IS_NULL(c.schoolCodeW) AND c.schoolCodeW != ''))";
+                //有Email篩選
+                if (hasMail)
+                {
+                    string tmpSql = "IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)";
+                    sqlWhere += $" AND ({tmpSql}) ";
+                }
                 if (!string.IsNullOrWhiteSpace(sqlWhere))
                 {
                     string sqlTmidEx = $"SELECT * FROM c WHERE {sqlWhere}";
@@ -1022,7 +1002,7 @@ namespace TEAMModelBI.Controllers.BICommon
                 //地理資訊 (base-ex)
                 bool useGeoFlg = (target.geo != null && (!string.IsNullOrWhiteSpace(target.geo.countryId) || !string.IsNullOrWhiteSpace(target.geo.provinceId) || !string.IsNullOrWhiteSpace(target.geo.cityId))) ? true : false;
                 List<string> passTmidGeo = new List<string>();
-                var (geoInfos, _) = await GetDataByGeo("tmid", "tmid", true, target.geo.countryId, target.geo.provinceId, target.geo.cityId);
+                var (geoInfos, _) = await GetDataByGeo("tmid", "tmid", true, target.geo.countryId, target.geo.provinceId, target.geo.cityId, target.hasMail);
                 foreach(var geoInfo in geoInfos)
                 {
                     if (!passTmidGeo.Contains(geoInfo.id)) passTmidGeo.Add(geoInfo.id);
@@ -1299,6 +1279,14 @@ namespace TEAMModelBI.Controllers.BICommon
             //取得TMID資料
             List<IdInfo> tmidInfos = new List<IdInfo>();
             string sqlBaseInfo = $"SELECT c.id, c.name, c.mail, c.mobile FROM c WHERE ARRAY_CONTAINS({JsonSerializer.Serialize(tmids)}, c.id)";
+            if(type.Equals("mail")) //發送類型 mail:郵件
+            {
+                sqlBaseInfo += $" AND (IS_DEFINED(c.mail) AND NOT IS_NULL(c.mail)) ";
+            }
+            else if(type.Equals("sms")) //發送類型 sms:簡訊
+            {
+                sqlBaseInfo += $" AND (IS_DEFINED(c.mobile) AND NOT IS_NULL(c.mobile)) ";
+            }
             await foreach (var item in cosmosClientCsv2
                 .GetContainer("Core", "ID2")
                 .GetItemQueryIteratorSql<JsonElement>(queryText: sqlBaseInfo, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("base-ex") }))
@@ -1600,6 +1588,7 @@ namespace TEAMModelBI.Controllers.BICommon
             public StartEnd point { get; set; }
             public List<string> school { get; set; }
             public List<string> tmid { get; set; }
+            public bool hasMail { get; set; } = false;
             public record StartEnd
             {
                 public long start { get; set; }