BIProdAnalysis.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. using Azure.Cosmos;
  2. using DocumentFormat.OpenXml.Office2010.Excel;
  3. using MathNet.Numerics;
  4. using Microsoft.OData.Edm;
  5. using Newtonsoft.Json;
  6. using OpenXmlPowerTools;
  7. using StackExchange.Redis;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Text.Json;
  14. using System.Text.RegularExpressions;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Extension;
  18. using TEAMModelOS.SDK.Models.Cosmos;
  19. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  20. namespace TEAMModelOS.SDK.Models.Service.BI
  21. {
  22. public static class BIProdAnalysis
  23. {
  24. /// <summary>
  25. /// 取得某日CS IOT 資料並生成IES5各校產品分析統計資料
  26. /// </summary>
  27. /// <param name="_azureRedis"></param>
  28. /// <param name="_dingDing"></param>
  29. /// <param name="y">年</param>
  30. /// <param name="m">月(2位數)</param>
  31. /// <param name="d">日(2位數)</param>
  32. /// <returns></returns>
  33. public static async Task BICreatDailyAnalData(AzureRedisFactory _azureRedis, CosmosClient _azureCosmosClient, CosmosClient _azureCosmosClientCsv1, DingDing _dingDing, string y, string m, string d)
  34. {
  35. try
  36. {
  37. var redisClinet2 = _azureRedis.GetRedisClient(2);
  38. var redisClinet8 = _azureRedis.GetRedisClient(8);
  39. var datetime = DateTimeOffset.UtcNow;
  40. var ynow = datetime.Year;
  41. List<string> calPropList = new List<string>() { "lessonRecord", "useIES", "useIES5Resource", "useWebIrs", "useDeviceIrs", "useHaboard", "useHita", "lessonLengMin", "stuShow", "stuLessonLengMin", "tGreen", "lTypeCoop", "lTypeIact", "lTypeMis", "lTypeTst", "lTypeDif", "lTypeNone", "lessonCnt928", "lessonCntId", "lessonCntDevice", "lessonCntIdDevice", "mission", "missionFin", "item", "interact" }; //要計算的ProdAnalysis欄位列表
  42. //取得CS Redis TeachingData (IOT紀錄只有三個月分)
  43. List<IotTeachingData> IotTeachingDataList = new List<IotTeachingData>();
  44. if (y.Equals(ynow.ToString()))
  45. {
  46. bool TeachingDataExist = await redisClinet2.KeyExistsAsync($"TeachingData:{m}{d}");
  47. if (TeachingDataExist)
  48. {
  49. RedisValue[] TeachingData = redisClinet2.ListRange($"TeachingData:{m}{d}");
  50. foreach (RedisValue tdataRow in TeachingData)
  51. {
  52. string[] tdata = tdataRow.ToString().Split(',');
  53. IotTeachingData IotTeachingData = new IotTeachingData();
  54. IotTeachingData.timestamp = Convert.ToInt64(tdata[0]);
  55. IotTeachingData.deviceId = tdata[1];
  56. IotTeachingData.channel = tdata[2];
  57. IotTeachingData.tmid = tdata[3];
  58. IotTeachingData.schoolId = tdata[4];
  59. IotTeachingData.useIES = tdata[5];
  60. IotTeachingData.useIES5Resource = (!string.IsNullOrWhiteSpace(tdata[6])) ? Convert.ToInt32(tdata[6]) : 0;
  61. IotTeachingData.useWebIrs = tdata[7];
  62. IotTeachingData.useDeviceIrs = tdata[8];
  63. IotTeachingData.useHaboard = tdata[9];
  64. IotTeachingData.useHita = tdata[10];
  65. IotTeachingData.lessonLengMin = (!string.IsNullOrWhiteSpace(tdata[11])) ? Convert.ToInt32(tdata[11]) : 0;
  66. IotTeachingData.stuShow = (!string.IsNullOrWhiteSpace(tdata[12])) ? Convert.ToInt32(tdata[12]) : 0;
  67. IotTeachingData.tPoint = (!string.IsNullOrWhiteSpace(tdata[13])) ? Convert.ToInt32(tdata[13]) : 0;
  68. IotTeachingData.lTypeCoop = tdata[14];
  69. IotTeachingData.lTypeIact = tdata[15];
  70. IotTeachingData.lTypeMis = tdata[16];
  71. IotTeachingData.lTypeTst = tdata[17];
  72. IotTeachingData.lTypeDif = tdata[18];
  73. IotTeachingData.authType = tdata[19];
  74. IotTeachingData.mission = (!string.IsNullOrWhiteSpace(tdata[20])) ? Convert.ToInt32(tdata[20]) : 0;
  75. IotTeachingData.missionFin = (!string.IsNullOrWhiteSpace(tdata[21])) ? Convert.ToInt32(tdata[21]) : 0;
  76. IotTeachingData.item = (!string.IsNullOrWhiteSpace(tdata[22])) ? Convert.ToInt32(tdata[22]) : 0;
  77. IotTeachingData.interact = (!string.IsNullOrWhiteSpace(tdata[23])) ? Convert.ToInt32(tdata[23]) : 0;
  78. IotTeachingData.ip = (tdata.Length > 24) ? tdata[24] : "";
  79. IotTeachingData.version = (tdata.Length > 25) ? tdata[25] : "";
  80. IotTeachingDataList.Add(IotTeachingData);
  81. }
  82. }
  83. }
  84. //生成各校每日產品分析數據
  85. //1.生成 Redis ProdAnalysis:Month
  86. //2.生成 CosmosDB Month
  87. //3.生成 CosmosDB 系統所有學校數值加總
  88. List<string> crtVirtualSchoolId = new List<string>(); //虛擬學校創建ID列表
  89. List<ProdAnalysis> ProdAnalysisList = new List<ProdAnalysis>();
  90. if (IotTeachingDataList.Count > 0)
  91. {
  92. foreach (IotTeachingData IotTeachingDatRow in IotTeachingDataList)
  93. {
  94. string schoolId = (!string.IsNullOrWhiteSpace(IotTeachingDatRow.schoolId)) ? IotTeachingDatRow.schoolId.ToLower() : "noschoolid"; //noschoolid:無任何學校ID
  95. if(!schoolId.Equals("noschoolid") && !schoolId.Equals("allschool") && !crtVirtualSchoolId.Contains(schoolId))
  96. {
  97. crtVirtualSchoolId.Add(schoolId);
  98. }
  99. string toolType = string.Empty;
  100. if (!string.IsNullOrWhiteSpace(IotTeachingDatRow.deviceId))
  101. {
  102. if (IotTeachingDatRow.deviceId.Contains("HiTeachCC-")) toolType = "HiTeachCC";
  103. else if (IotTeachingDatRow.deviceId.Contains("HiTeach-")) toolType = "HiTeach";
  104. else if (IotTeachingDatRow.deviceId.Contains("HiTA-")) toolType = "HiTA";
  105. }
  106. //學校數據生成
  107. if (!string.IsNullOrWhiteSpace(schoolId) && !string.IsNullOrWhiteSpace(toolType))
  108. {
  109. bool addFlg = false;
  110. ProdAnalysis prodAnalysisRow = ProdAnalysisList.Where(s => s.schoolId.Equals(schoolId) && s.toolType.Equals(toolType)).FirstOrDefault();
  111. //無此校數據=>創建
  112. if (prodAnalysisRow == null)
  113. {
  114. prodAnalysisRow = new ProdAnalysis();
  115. prodAnalysisRow.schoolId = schoolId;
  116. prodAnalysisRow.toolType = toolType;
  117. addFlg = true;
  118. }
  119. //欄位加總
  120. if (!string.IsNullOrWhiteSpace(IotTeachingDatRow.deviceId) && !prodAnalysisRow.deviceList.Contains(IotTeachingDatRow.deviceId))
  121. {
  122. prodAnalysisRow.deviceList.Add(IotTeachingDatRow.deviceId);
  123. }
  124. prodAnalysisRow.deviceCnt = prodAnalysisRow.deviceList.Count;
  125. switch (IotTeachingDatRow.authType)
  126. {
  127. case "0": //928授權
  128. if (!prodAnalysisRow.deviceNoAuthList.Contains(IotTeachingDatRow.deviceId)) prodAnalysisRow.deviceNoAuthList.Add(IotTeachingDatRow.deviceId);
  129. prodAnalysisRow.lessonCnt928++;
  130. break;
  131. case "1": //ID授權
  132. if (!prodAnalysisRow.deviceNoAuthList.Contains(IotTeachingDatRow.deviceId)) prodAnalysisRow.deviceNoAuthList.Add(IotTeachingDatRow.deviceId);
  133. prodAnalysisRow.lessonCntId++;
  134. break;
  135. case "2": //機器授權
  136. if (!prodAnalysisRow.deviceAuthList.Contains(IotTeachingDatRow.deviceId)) prodAnalysisRow.deviceAuthList.Add(IotTeachingDatRow.deviceId);
  137. prodAnalysisRow.lessonCntDevice++;
  138. break;
  139. case "3": //ID+機器授權
  140. if (!prodAnalysisRow.deviceAuthList.Contains(IotTeachingDatRow.deviceId)) prodAnalysisRow.deviceAuthList.Add(IotTeachingDatRow.deviceId);
  141. prodAnalysisRow.lessonCntIdDevice++;
  142. break;
  143. }
  144. prodAnalysisRow.deviceNoAuth = prodAnalysisRow.deviceNoAuthList.Count;
  145. prodAnalysisRow.deviceAuth = prodAnalysisRow.deviceAuthList.Count;
  146. if (!string.IsNullOrWhiteSpace(IotTeachingDatRow.tmid) && !prodAnalysisRow.tmidList.Contains(IotTeachingDatRow.tmid))
  147. {
  148. prodAnalysisRow.tmidList.Add(IotTeachingDatRow.tmid);
  149. }
  150. prodAnalysisRow.tmidCnt = prodAnalysisRow.tmidList.Count;
  151. prodAnalysisRow.lessonRecord++;
  152. if (IotTeachingDatRow.useIES.Equals("1")) prodAnalysisRow.useIES++;
  153. prodAnalysisRow.useIES5Resource += IotTeachingDatRow.useIES5Resource;
  154. if (IotTeachingDatRow.useWebIrs.Equals("1")) prodAnalysisRow.useWebIrs++;
  155. if (IotTeachingDatRow.useDeviceIrs.Equals("1")) prodAnalysisRow.useDeviceIrs++;
  156. if (IotTeachingDatRow.useHaboard.Equals("1")) prodAnalysisRow.useHaboard++;
  157. if (IotTeachingDatRow.useHita.Equals("1")) prodAnalysisRow.useHita++;
  158. prodAnalysisRow.lessonLengMin += IotTeachingDatRow.lessonLengMin;
  159. prodAnalysisRow.stuShow += IotTeachingDatRow.stuShow;
  160. prodAnalysisRow.stuLessonLengMin += IotTeachingDatRow.lessonLengMin * IotTeachingDatRow.stuShow;
  161. if (IotTeachingDatRow.tPoint >= 70) prodAnalysisRow.tGreen++;
  162. if (IotTeachingDatRow.lTypeCoop.Equals("1")) prodAnalysisRow.lTypeCoop++;
  163. if (IotTeachingDatRow.lTypeIact.Equals("1")) prodAnalysisRow.lTypeIact++;
  164. if (IotTeachingDatRow.lTypeMis.Equals("1")) prodAnalysisRow.lTypeMis++;
  165. if (IotTeachingDatRow.lTypeTst.Equals("1")) prodAnalysisRow.lTypeTst++;
  166. if (IotTeachingDatRow.lTypeDif.Equals("1")) prodAnalysisRow.lTypeDif++;
  167. if (IotTeachingDatRow.lTypeCoop.Equals("0") && IotTeachingDatRow.lTypeIact.Equals("0") && IotTeachingDatRow.lTypeMis.Equals("0") && IotTeachingDatRow.lTypeTst.Equals("0") && IotTeachingDatRow.lTypeDif.Equals("0")) prodAnalysisRow.lTypeNone++;
  168. prodAnalysisRow.mission += IotTeachingDatRow.mission;
  169. prodAnalysisRow.missionFin += IotTeachingDatRow.missionFin;
  170. prodAnalysisRow.item += IotTeachingDatRow.item;
  171. prodAnalysisRow.interact += IotTeachingDatRow.interact;
  172. if (addFlg)
  173. {
  174. ProdAnalysisList.Add(prodAnalysisRow);
  175. }
  176. }
  177. }
  178. }
  179. //1.記入IES5 Redis ProdAnalysis:Day
  180. //2.記入IES5 CosmosDB Day
  181. if (ProdAnalysisList.Count > 0)
  182. {
  183. //資料整形
  184. Dictionary<string, Dictionary<string, string>> redisSchFieldDic = new Dictionary<string, Dictionary<string, string>>(); //架構: key => schId => schJsonContent
  185. List<ProdAnalysisCosmos> cosmosSchList = new List<ProdAnalysisCosmos>();
  186. Dictionary <string,ProdAnalysisCosmos> cosmosAllSchSumDayDic = new Dictionary<string, ProdAnalysisCosmos>();
  187. foreach (ProdAnalysis prodAnalysisRow in ProdAnalysisList)
  188. {
  189. //Redis整形
  190. string toolType = prodAnalysisRow.toolType;
  191. string schoolId = prodAnalysisRow.schoolId;
  192. string hkey = $"ProdAnalysis:Day:{toolType}:{y}{m}{d}";
  193. string fieldContent = prodAnalysisRow.ToJsonString();
  194. if (redisSchFieldDic.ContainsKey(hkey)) redisSchFieldDic[hkey].Add(schoolId, fieldContent);
  195. else redisSchFieldDic.Add(hkey, new Dictionary<string, string>() { { schoolId, fieldContent } });
  196. //CosmosDB整形
  197. ProdAnalysisCosmos ProdAnalysisCosmosRow = prodAnalysisRow.ToJsonString().ToObject<ProdAnalysisCosmos>();
  198. ProdAnalysisCosmosRow.date = $"{y}{m}{d}";
  199. ProdAnalysisCosmosRow.year = Convert.ToInt32(y, 10);
  200. ProdAnalysisCosmosRow.month = Convert.ToInt32(m, 10);
  201. ProdAnalysisCosmosRow.day = Convert.ToInt32(d, 10);
  202. DateTimeOffset dateTime = new DateTimeOffset(ProdAnalysisCosmosRow.year, ProdAnalysisCosmosRow.month, ProdAnalysisCosmosRow.day, 0, 0, 0, TimeSpan.Zero);
  203. ProdAnalysisCosmosRow.dateTime = dateTime.ToUnixTimeSeconds();
  204. ProdAnalysisCosmosRow.id = $"{ProdAnalysisCosmosRow.toolType}-{ProdAnalysisCosmosRow.date}-{schoolId}";
  205. ProdAnalysisCosmosRow.dateUnit = "day";
  206. ProdAnalysisCosmosRow.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  207. cosmosSchList.Add(ProdAnalysisCosmosRow);
  208. }
  209. //記入Redis
  210. if (redisSchFieldDic.Count > 0)
  211. {
  212. foreach (KeyValuePair<string, Dictionary<string, string>> hkeyItem in redisSchFieldDic)
  213. {
  214. //記入Redis
  215. string hkey = hkeyItem.Key;
  216. List<HashEntry> hvalList = new List<HashEntry>();
  217. Dictionary<string, string> fieldDic = hkeyItem.Value;
  218. foreach (KeyValuePair<string, string> schItem in fieldDic)
  219. {
  220. string schoolId = schItem.Key;
  221. string fieldContent = schItem.Value;
  222. hvalList.Add(new HashEntry($"{schoolId}", fieldContent));
  223. }
  224. await redisClinet8.HashSetAsync(hkey, hvalList.ToArray());
  225. }
  226. }
  227. //記入CosmosDB
  228. if (cosmosSchList.Count > 0)
  229. {
  230. foreach (ProdAnalysisCosmos cosmosSchRow in cosmosSchList)
  231. {
  232. //各校每日CosmosDB記入
  233. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosSchRow);
  234. //所有學校數值加總 數值生成 cosmosAllSchSumDayDic -> key:toolType val:cosmosAllSchSumDay
  235. string toolType = cosmosSchRow.toolType;
  236. string schoolId = "allschool";
  237. ProdAnalysisCosmos cosmosAllSchSumDay = new ProdAnalysisCosmos();
  238. if (cosmosAllSchSumDayDic.ContainsKey(toolType)) cosmosAllSchSumDay = cosmosAllSchSumDayDic[toolType];
  239. foreach (PropertyInfo propertyInfo in cosmosAllSchSumDay.GetType().GetProperties()) //累加項目
  240. {
  241. if (calPropList.Contains(propertyInfo.Name))
  242. {
  243. var propType = propertyInfo.PropertyType;
  244. var valNow = propertyInfo.GetValue(cosmosAllSchSumDay);
  245. var valTodo = cosmosSchRow.GetType().GetProperty(propertyInfo.Name).GetValue(cosmosSchRow);
  246. if (propType.Equals(typeof(long))) propertyInfo.SetValue(cosmosAllSchSumDay, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  247. else propertyInfo.SetValue(cosmosAllSchSumDay, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  248. }
  249. }
  250. cosmosAllSchSumDay.schoolId = schoolId;
  251. cosmosAllSchSumDay.toolType = cosmosSchRow.toolType;
  252. cosmosAllSchSumDay.date = cosmosSchRow.date;
  253. cosmosAllSchSumDay.id = $"{cosmosAllSchSumDay.toolType}-{cosmosAllSchSumDay.date}-{schoolId}";
  254. cosmosAllSchSumDay.dateUnit = "day";
  255. cosmosAllSchSumDay.year = cosmosSchRow.year;
  256. cosmosAllSchSumDay.month = cosmosSchRow.month;
  257. cosmosAllSchSumDay.day = cosmosSchRow.day;
  258. DateTimeOffset dateTime = new DateTimeOffset(cosmosAllSchSumDay.year, cosmosAllSchSumDay.month, cosmosAllSchSumDay.day, 0, 0, 0, TimeSpan.Zero);
  259. cosmosAllSchSumDay.dateTime = dateTime.ToUnixTimeSeconds();
  260. cosmosAllSchSumDay.deviceList = cosmosAllSchSumDay.deviceList.Union(cosmosSchRow.deviceList).ToList();
  261. cosmosAllSchSumDay.deviceCnt = cosmosAllSchSumDay.deviceList.Count;
  262. cosmosAllSchSumDay.deviceAuthList = cosmosAllSchSumDay.deviceAuthList.Union(cosmosSchRow.deviceAuthList).ToList();
  263. cosmosAllSchSumDay.deviceAuth = cosmosAllSchSumDay.deviceAuthList.Count;
  264. cosmosAllSchSumDay.deviceNoAuthList = cosmosAllSchSumDay.deviceNoAuthList.Union(cosmosSchRow.deviceNoAuthList).ToList();
  265. cosmosAllSchSumDay.deviceNoAuth = cosmosAllSchSumDay.deviceNoAuthList.Count;
  266. cosmosAllSchSumDay.tmidList = cosmosAllSchSumDay.tmidList.Union(cosmosSchRow.tmidList).ToList();
  267. cosmosAllSchSumDay.tmidCnt = cosmosAllSchSumDay.tmidList.Count;
  268. if (cosmosAllSchSumDayDic.ContainsKey(toolType)) cosmosAllSchSumDayDic[toolType] = cosmosAllSchSumDay;
  269. else cosmosAllSchSumDayDic.Add(toolType, cosmosAllSchSumDay);
  270. }
  271. //每日所有學校數據總計CosmosDB記入
  272. foreach (KeyValuePair<string, ProdAnalysisCosmos> schItem in cosmosAllSchSumDayDic)
  273. {
  274. string toolType = schItem.Key;
  275. ProdAnalysisCosmos cosmosAllSchSumDay = schItem.Value;
  276. cosmosAllSchSumDay.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  277. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosAllSchSumDay);
  278. }
  279. }
  280. }
  281. //取 Redis 該月所有 ProdAnalysis:Day
  282. //1.生成 Redis ProdAnalysis:Month
  283. //2.生成 CosmosDB Month
  284. Dictionary<string, Dictionary<string, ProdAnalysis>> ProdAnalysisListMonth = new Dictionary<string, Dictionary<string, ProdAnalysis>>();
  285. Dictionary<string, ProdAnalysisCosmos> cosmosAllSchSumMonthDic = new Dictionary<string, ProdAnalysisCosmos>();
  286. List<ProdAnalysisCosmos> cosmosSchListMonth = new List<ProdAnalysisCosmos>();
  287. string patternD = $"ProdAnalysis:Day:HiT*:{y}{m}*";
  288. List<string> keysDayList = ScanRedisKeysByPattern(_azureRedis, patternD);
  289. if (keysDayList.Count > 0)
  290. {
  291. foreach (string keyDay in keysDayList)
  292. {
  293. string[] keyItemList = keyDay.Split(':'); //ProdAnalysis:Day:HiTeach:20230326
  294. string toolType = keyItemList[2];
  295. string dateStrD = keyItemList[3];
  296. string dateStrD_y = string.Empty;
  297. string dateStrD_m = string.Empty;
  298. string dateStrD_d = string.Empty;
  299. Regex rgx = new Regex(@"[0-9]{8}");
  300. if (rgx.IsMatch(dateStrD))
  301. {
  302. dateStrD_y = dateStrD.Substring(0, 4);
  303. dateStrD_m = dateStrD.Substring(4, 2);
  304. dateStrD_d = dateStrD.Substring(6, 2);
  305. }
  306. string prodAnalMonthKey = $"ProdAnalysis:Month:{toolType}:{dateStrD_y}{dateStrD_m}";
  307. bool ProdAnalysisDayExist = await redisClinet8.KeyExistsAsync(keyDay);
  308. if (ProdAnalysisDayExist && !string.IsNullOrWhiteSpace(dateStrD_y) && !string.IsNullOrWhiteSpace(dateStrD_m) && !string.IsNullOrWhiteSpace(dateStrD_d))
  309. {
  310. HashEntry[] hsetDay = redisClinet8.HashGetAll(keyDay); //某日 ProdAnalysis:Day所有學校的統計項目
  311. foreach (HashEntry hset in hsetDay) {
  312. string keySchId = hset.Name;
  313. string valSchDataJson = hset.Value;
  314. ProdAnalysis SchDataTodo = valSchDataJson.ToObject<ProdAnalysis>();
  315. //Redis Month 資料生成
  316. if (ProdAnalysisListMonth.ContainsKey(prodAnalMonthKey)) //月Dic已有此key => 分校累加
  317. {
  318. if (ProdAnalysisListMonth[$"{prodAnalMonthKey}"].ContainsKey($"{keySchId}"))
  319. {
  320. ProdAnalysis SchDataNow = ProdAnalysisListMonth[$"{prodAnalMonthKey}"][$"{keySchId}"];
  321. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  322. {
  323. if (calPropList.Contains(propertyInfo.Name))
  324. {
  325. var propType = propertyInfo.PropertyType;
  326. var valNow = propertyInfo.GetValue(SchDataNow);
  327. var valTodo = SchDataTodo.GetType().GetProperty(propertyInfo.Name).GetValue(SchDataTodo);
  328. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  329. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  330. }
  331. }
  332. SchDataNow.deviceList = SchDataNow.deviceList.Union(SchDataTodo.deviceList).ToList();
  333. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  334. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(SchDataTodo.deviceAuthList).ToList();
  335. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  336. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(SchDataTodo.deviceNoAuthList).ToList();
  337. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  338. SchDataNow.tmidList = SchDataNow.tmidList.Union(SchDataTodo.tmidList).ToList();
  339. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  340. }
  341. //無此校資料 => 該校資料放入
  342. else
  343. {
  344. ProdAnalysisListMonth[$"{prodAnalMonthKey}"][$"{keySchId}"] = SchDataTodo;
  345. }
  346. }
  347. else //無此月資料 => 所有學校資料放入
  348. {
  349. ProdAnalysisListMonth.Add(prodAnalMonthKey, new Dictionary<string, ProdAnalysis>() { { keySchId, SchDataTodo } });
  350. }
  351. }
  352. }
  353. }
  354. }
  355. if (ProdAnalysisListMonth.Count > 0)
  356. {
  357. foreach (KeyValuePair<string, Dictionary<string, ProdAnalysis>> item in ProdAnalysisListMonth)
  358. {
  359. string monthRedisKey = item.Key;
  360. List<HashEntry> hvalList = new List<HashEntry>();
  361. Dictionary<string, ProdAnalysis> monthRedisSchDIc = item.Value;
  362. foreach (KeyValuePair<string, ProdAnalysis> monthRedisSchItem in monthRedisSchDIc)
  363. {
  364. string monthRedisSchId = monthRedisSchItem.Key;
  365. ProdAnalysis monthRedisSchData = monthRedisSchItem.Value;
  366. //Redis資料製作
  367. hvalList.Add(new HashEntry(monthRedisSchId, monthRedisSchData.ToJsonString()));
  368. //CosmosDB資料製作
  369. ProdAnalysisCosmos cosmosSchRow = monthRedisSchData.ToJsonString().ToObject<ProdAnalysisCosmos>();
  370. cosmosSchRow.date = $"{y}{m}";
  371. cosmosSchRow.year = Convert.ToInt32(y, 10);
  372. cosmosSchRow.month = Convert.ToInt32(m, 10);
  373. DateTimeOffset dateTime = new DateTimeOffset(cosmosSchRow.year, cosmosSchRow.month, 1, 0, 0, 0, TimeSpan.Zero);
  374. cosmosSchRow.dateTime = dateTime.ToUnixTimeSeconds();
  375. cosmosSchRow.id = $"{monthRedisSchData.toolType}-{cosmosSchRow.date}-{monthRedisSchId}";
  376. cosmosSchRow.dateUnit = "month";
  377. cosmosSchRow.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  378. cosmosSchListMonth.Add(cosmosSchRow);
  379. }
  380. //記入Redis
  381. await redisClinet8.HashSetAsync($"{monthRedisKey}", hvalList.ToArray());
  382. }
  383. //記入CosmosDB
  384. if (cosmosSchListMonth.Count > 0)
  385. {
  386. foreach (ProdAnalysisCosmos cosmosSchRow in cosmosSchListMonth)
  387. {
  388. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosSchRow);
  389. //所有學校數值加總 數值生成 cosmosAllSchSumDayDic -> key:toolType val:cosmosAllSchSumDay
  390. string toolType = cosmosSchRow.toolType;
  391. string schoolId = "allschool";
  392. ProdAnalysisCosmos cosmosAllSchSumMonth = new ProdAnalysisCosmos();
  393. if (cosmosAllSchSumMonthDic.ContainsKey(toolType)) cosmosAllSchSumMonth = cosmosAllSchSumMonthDic[toolType];
  394. foreach (PropertyInfo propertyInfo in cosmosAllSchSumMonth.GetType().GetProperties()) //累加項目
  395. {
  396. if (calPropList.Contains(propertyInfo.Name))
  397. {
  398. var propType = propertyInfo.PropertyType;
  399. var valNow = propertyInfo.GetValue(cosmosAllSchSumMonth);
  400. var valTodo = cosmosSchRow.GetType().GetProperty(propertyInfo.Name).GetValue(cosmosSchRow);
  401. if (propType.Equals(typeof(long))) propertyInfo.SetValue(cosmosAllSchSumMonth, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  402. else propertyInfo.SetValue(cosmosAllSchSumMonth, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  403. }
  404. }
  405. cosmosAllSchSumMonth.schoolId = schoolId;
  406. cosmosAllSchSumMonth.toolType = cosmosSchRow.toolType;
  407. cosmosAllSchSumMonth.date = cosmosSchRow.date;
  408. cosmosAllSchSumMonth.id = $"{cosmosAllSchSumMonth.toolType}-{cosmosAllSchSumMonth.date}-{schoolId}";
  409. cosmosAllSchSumMonth.dateUnit = "month";
  410. cosmosAllSchSumMonth.year = cosmosSchRow.year;
  411. cosmosAllSchSumMonth.month = cosmosSchRow.month;
  412. DateTimeOffset dateTime = new DateTimeOffset(cosmosAllSchSumMonth.year, cosmosAllSchSumMonth.month, 1, 0, 0, 0, TimeSpan.Zero);
  413. cosmosAllSchSumMonth.dateTime = dateTime.ToUnixTimeSeconds();
  414. cosmosAllSchSumMonth.deviceList = cosmosAllSchSumMonth.deviceList.Union(cosmosSchRow.deviceList).ToList();
  415. cosmosAllSchSumMonth.deviceCnt = cosmosAllSchSumMonth.deviceList.Count;
  416. cosmosAllSchSumMonth.deviceAuthList = cosmosAllSchSumMonth.deviceAuthList.Union(cosmosSchRow.deviceAuthList).ToList();
  417. cosmosAllSchSumMonth.deviceAuth = cosmosAllSchSumMonth.deviceAuthList.Count;
  418. cosmosAllSchSumMonth.deviceNoAuthList = cosmosAllSchSumMonth.deviceNoAuthList.Union(cosmosSchRow.deviceNoAuthList).ToList();
  419. cosmosAllSchSumMonth.deviceNoAuth = cosmosAllSchSumMonth.deviceNoAuthList.Count;
  420. cosmosAllSchSumMonth.tmidList = cosmosAllSchSumMonth.tmidList.Union(cosmosSchRow.tmidList).ToList();
  421. cosmosAllSchSumMonth.tmidCnt = cosmosAllSchSumMonth.tmidList.Count;
  422. if (cosmosAllSchSumMonthDic.ContainsKey(toolType)) cosmosAllSchSumMonthDic[toolType] = cosmosAllSchSumMonth;
  423. else cosmosAllSchSumMonthDic.Add(toolType, cosmosAllSchSumMonth);
  424. }
  425. //每月所有學校數據總計CosmosDB記入
  426. foreach (KeyValuePair<string, ProdAnalysisCosmos> schItem in cosmosAllSchSumMonthDic)
  427. {
  428. string toolType = schItem.Key;
  429. ProdAnalysisCosmos cosmosAllSchSumMonth = schItem.Value;
  430. cosmosAllSchSumMonth.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  431. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosAllSchSumMonth);
  432. }
  433. }
  434. }
  435. //取該年所有 CosmosDB 該年所有月份 生成CosmosDB年資料
  436. Dictionary<string, Dictionary<string, ProdAnalysisCosmos>> ProdAnalysisListYear = new Dictionary<string, Dictionary<string, ProdAnalysisCosmos>>();
  437. var query = $"SELECT * FROM c WHERE c.year = {y} AND c.dateUnit = 'month' AND c.schoolId != 'allschool'";
  438. await foreach (var itemcr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("ProdAnalysis") }))
  439. {
  440. var json = await JsonDocument.ParseAsync(itemcr.ContentStream);
  441. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  442. {
  443. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  444. {
  445. ProdAnalysisCosmos SchDataTodo = obj.ToObject<ProdAnalysisCosmos>();
  446. string toolType = SchDataTodo.toolType;
  447. string schId = SchDataTodo.schoolId;
  448. //年Dic已有此key => 分校累加
  449. if (ProdAnalysisListYear.ContainsKey(toolType))
  450. {
  451. if (ProdAnalysisListYear[$"{toolType}"].ContainsKey($"{schId}"))
  452. {
  453. ProdAnalysisCosmos SchDataNow = ProdAnalysisListYear[$"{toolType}"][$"{schId}"];
  454. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  455. {
  456. if (calPropList.Contains(propertyInfo.Name))
  457. {
  458. var propType = propertyInfo.PropertyType;
  459. var valNow = propertyInfo.GetValue(SchDataNow);
  460. var valTodo = SchDataTodo.GetType().GetProperty(propertyInfo.Name).GetValue(SchDataTodo);
  461. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  462. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  463. }
  464. }
  465. SchDataNow.deviceList = SchDataNow.deviceList.Union(SchDataTodo.deviceList).ToList();
  466. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  467. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(SchDataTodo.deviceAuthList).ToList();
  468. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  469. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(SchDataTodo.deviceNoAuthList).ToList();
  470. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  471. SchDataNow.tmidList = SchDataNow.tmidList.Union(SchDataTodo.tmidList).ToList();
  472. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  473. }
  474. //無此校資料 => 該校資料放入
  475. else
  476. {
  477. ProdAnalysisCosmos SchDataNow = SchDataTodo;
  478. SchDataNow.date = $"{y}";
  479. SchDataNow.year = Convert.ToInt32(y, 10);
  480. SchDataNow.month = 0;
  481. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  482. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  483. SchDataNow.id = $"{toolType}-{y}-{schId}";
  484. SchDataNow.dateUnit = "year";
  485. ProdAnalysisListYear[$"{toolType}"][$"{schId}"] = SchDataNow;
  486. }
  487. }
  488. //無此年資料 => 所有學校資料放入
  489. else
  490. {
  491. ProdAnalysisCosmos SchDataNow = SchDataTodo;
  492. SchDataNow.date = $"{y}";
  493. SchDataNow.year = Convert.ToInt32(y, 10);
  494. SchDataNow.month = 0;
  495. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  496. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  497. SchDataNow.id = $"{toolType}-{y}-{schId}";
  498. SchDataNow.dateUnit = "year";
  499. ProdAnalysisListYear.Add(toolType, new Dictionary<string, ProdAnalysisCosmos>() { { schId, SchDataNow } });
  500. }
  501. }
  502. }
  503. }
  504. if (ProdAnalysisListYear.Count > 0)
  505. {
  506. foreach (KeyValuePair<string, Dictionary<string, ProdAnalysisCosmos>> item in ProdAnalysisListYear)
  507. {
  508. string toolType = item.Key;
  509. ProdAnalysisCosmos SchDataNow = new ProdAnalysisCosmos(); //當年某產品所有學校總和
  510. Dictionary<string, ProdAnalysisCosmos> yearCosmosSchDIc = item.Value;
  511. foreach (KeyValuePair<string, ProdAnalysisCosmos> yearCosmosSchItem in yearCosmosSchDIc)
  512. {
  513. string schId = yearCosmosSchItem.Key;
  514. ProdAnalysisCosmos yearCosmosSchData = yearCosmosSchItem.Value;
  515. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(yearCosmosSchData);
  516. //每年所有學校數據總計CosmosDB記入
  517. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  518. {
  519. if (calPropList.Contains(propertyInfo.Name))
  520. {
  521. var propType = propertyInfo.PropertyType;
  522. var valNow = propertyInfo.GetValue(SchDataNow);
  523. var valTodo = yearCosmosSchData.GetType().GetProperty(propertyInfo.Name).GetValue(yearCosmosSchData);
  524. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  525. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  526. }
  527. }
  528. SchDataNow.schoolId = "allschool";
  529. SchDataNow.toolType = yearCosmosSchData.toolType;
  530. SchDataNow.date = yearCosmosSchData.date;
  531. SchDataNow.id = $"{yearCosmosSchData.toolType}-{yearCosmosSchData.date}-allschool";
  532. SchDataNow.dateUnit = "year";
  533. SchDataNow.year = yearCosmosSchData.year;
  534. SchDataNow.month = 0;
  535. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  536. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  537. SchDataNow.deviceList = SchDataNow.deviceList.Union(yearCosmosSchData.deviceList).ToList();
  538. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  539. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(yearCosmosSchData.deviceAuthList).ToList();
  540. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  541. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(yearCosmosSchData.deviceNoAuthList).ToList();
  542. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  543. SchDataNow.tmidList = SchDataNow.tmidList.Union(yearCosmosSchData.tmidList).ToList();
  544. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  545. }
  546. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(SchDataNow);
  547. }
  548. }
  549. //虛擬學校創建
  550. if (crtVirtualSchoolId.Count > 0)
  551. {
  552. //取得IES5 school Base
  553. string schIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  554. string schBaseQueryText = $"SELECT c.id FROM c where ARRAY_CONTAINS({schIdListStr}, c.id, true)";
  555. await foreach (var itemsr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: schBaseQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  556. {
  557. using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
  558. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  559. {
  560. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  561. {
  562. string existSchid = obj.GetProperty("id").GetString();
  563. if (crtVirtualSchoolId.Contains(existSchid))
  564. {
  565. crtVirtualSchoolId.Remove(existSchid);
  566. }
  567. }
  568. }
  569. }
  570. //取得IES5 school VirtualBase
  571. schIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  572. schBaseQueryText = $"SELECT c.id FROM c where ARRAY_CONTAINS({schIdListStr}, c.id, true)";
  573. await foreach (var itemsr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: schBaseQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"VirtualBase") }))
  574. {
  575. using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
  576. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  577. {
  578. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  579. {
  580. string existSchid = obj.GetProperty("id").GetString();
  581. if (crtVirtualSchoolId.Contains(existSchid))
  582. {
  583. crtVirtualSchoolId.Remove(existSchid);
  584. }
  585. }
  586. }
  587. }
  588. //VirtualBase school 建立
  589. if(crtVirtualSchoolId.Count > 0)
  590. {
  591. //取得CSV1 schoolcode,存在者建立IES5 VirtualBase school
  592. List<School> crtVSchoolList = new List<School>();
  593. string csv1SchIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  594. string schCsv1QueryText = $"SELECT c.shortCode, c.name, c.countryName, c.provinceName, c.cityName, c.distName, c.address FROM c where ARRAY_CONTAINS({csv1SchIdListStr}, c.shortCode, true)";
  595. await foreach (var item in _azureCosmosClientCsv1.GetContainer("Core", "SchoolCode").GetItemQueryStreamIterator(queryText: schCsv1QueryText, requestOptions: null ))
  596. {
  597. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  598. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  599. {
  600. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  601. {
  602. VirtualBase crtVSchool = new VirtualBase();
  603. crtVSchool.code = "VirtualBase";
  604. crtVSchool.id = obj.GetProperty("shortCode").GetString();
  605. crtVSchool.pk = "School";
  606. crtVSchool.schoolCode = obj.GetProperty("shortCode").GetString();
  607. crtVSchool.name = obj.GetProperty("name").GetString();
  608. crtVSchool.region = (obj.TryGetProperty("countryName", out JsonElement countryNameJ)) ? Convert.ToString(countryNameJ) : null;
  609. crtVSchool.province = (obj.TryGetProperty("provinceName", out JsonElement provinceNameJ)) ? Convert.ToString(provinceNameJ) : null;
  610. crtVSchool.city = (obj.TryGetProperty("cityName", out JsonElement cityNameJ)) ? Convert.ToString(cityNameJ) : null;
  611. crtVSchool.dist = (obj.TryGetProperty("distName", out JsonElement distNameJ)) ? Convert.ToString(distNameJ) : null;
  612. crtVSchool.address = (obj.TryGetProperty("address", out JsonElement addressJ)) ? Convert.ToString(addressJ) : null;
  613. crtVSchool.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  614. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<VirtualBase>(crtVSchool);
  615. }
  616. }
  617. }
  618. }
  619. }
  620. }
  621. catch (Exception ex)
  622. {
  623. _ = _dingDing.SendBotMsg($"BI,{Environment.GetEnvironmentVariable("Option:Location")},BICreatDailyAnalData() IOT產品分析資料生成錯誤\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  624. }
  625. }
  626. /// <summary>
  627. /// 取得Redis(8)符合搜尋模式的key
  628. /// </summary>
  629. /// <param name="pattern"></param>
  630. /// <returns></returns>
  631. public static List<string> ScanRedisKeysByPattern(AzureRedisFactory _azureRedis, string pattern)
  632. {
  633. var redisClinet8 = _azureRedis.GetRedisClient(8);
  634. var keys = new HashSet<RedisKey>();
  635. int nextCursor = 0;
  636. do
  637. {
  638. RedisResult redisResult = redisClinet8.Execute("SCAN", nextCursor.ToString(), "MATCH", pattern, "COUNT", "1000");
  639. var innerResult = (RedisResult[])redisResult;
  640. nextCursor = int.Parse((string)innerResult[0]);
  641. List<RedisKey> resultLines = ((RedisKey[])innerResult[1]).ToList();
  642. keys.UnionWith(resultLines);
  643. }
  644. while (nextCursor != 0);
  645. List<string> result = new List<string>();
  646. if (keys.Count > 0)
  647. {
  648. foreach (RedisKey key in keys)
  649. {
  650. result.Add(key.ToString());
  651. }
  652. }
  653. return result;
  654. }
  655. }
  656. }