BIProdAnalysis.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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", "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. prodAnalysisRow.mission += IotTeachingDatRow.mission;
  168. prodAnalysisRow.missionFin += IotTeachingDatRow.missionFin;
  169. prodAnalysisRow.item += IotTeachingDatRow.item;
  170. prodAnalysisRow.interact += IotTeachingDatRow.interact;
  171. if (addFlg)
  172. {
  173. ProdAnalysisList.Add(prodAnalysisRow);
  174. }
  175. }
  176. }
  177. }
  178. //1.記入IES5 Redis ProdAnalysis:Day
  179. //2.記入IES5 CosmosDB Day
  180. if (ProdAnalysisList.Count > 0)
  181. {
  182. //資料整形
  183. Dictionary<string, Dictionary<string, string>> redisSchFieldDic = new Dictionary<string, Dictionary<string, string>>(); //架構: key => schId => schJsonContent
  184. List<ProdAnalysisCosmos> cosmosSchList = new List<ProdAnalysisCosmos>();
  185. Dictionary <string,ProdAnalysisCosmos> cosmosAllSchSumDayDic = new Dictionary<string, ProdAnalysisCosmos>();
  186. foreach (ProdAnalysis prodAnalysisRow in ProdAnalysisList)
  187. {
  188. //Redis整形
  189. string toolType = prodAnalysisRow.toolType;
  190. string schoolId = prodAnalysisRow.schoolId;
  191. string hkey = $"ProdAnalysis:Day:{toolType}:{y}{m}{d}";
  192. string fieldContent = prodAnalysisRow.ToJsonString();
  193. if (redisSchFieldDic.ContainsKey(hkey)) redisSchFieldDic[hkey].Add(schoolId, fieldContent);
  194. else redisSchFieldDic.Add(hkey, new Dictionary<string, string>() { { schoolId, fieldContent } });
  195. //CosmosDB整形
  196. ProdAnalysisCosmos ProdAnalysisCosmosRow = prodAnalysisRow.ToJsonString().ToObject<ProdAnalysisCosmos>();
  197. ProdAnalysisCosmosRow.date = $"{y}{m}{d}";
  198. ProdAnalysisCosmosRow.year = Convert.ToInt32(y, 10);
  199. ProdAnalysisCosmosRow.month = Convert.ToInt32(m, 10);
  200. ProdAnalysisCosmosRow.day = Convert.ToInt32(d, 10);
  201. DateTimeOffset dateTime = new DateTimeOffset(ProdAnalysisCosmosRow.year, ProdAnalysisCosmosRow.month, ProdAnalysisCosmosRow.day, 0, 0, 0, TimeSpan.Zero);
  202. ProdAnalysisCosmosRow.dateTime = dateTime.ToUnixTimeSeconds();
  203. ProdAnalysisCosmosRow.id = $"{ProdAnalysisCosmosRow.toolType}-{ProdAnalysisCosmosRow.date}-{schoolId}";
  204. ProdAnalysisCosmosRow.dateUnit = "day";
  205. ProdAnalysisCosmosRow.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  206. cosmosSchList.Add(ProdAnalysisCosmosRow);
  207. }
  208. //記入Redis
  209. if (redisSchFieldDic.Count > 0)
  210. {
  211. foreach (KeyValuePair<string, Dictionary<string, string>> hkeyItem in redisSchFieldDic)
  212. {
  213. //記入Redis
  214. string hkey = hkeyItem.Key;
  215. List<HashEntry> hvalList = new List<HashEntry>();
  216. Dictionary<string, string> fieldDic = hkeyItem.Value;
  217. foreach (KeyValuePair<string, string> schItem in fieldDic)
  218. {
  219. string schoolId = schItem.Key;
  220. string fieldContent = schItem.Value;
  221. hvalList.Add(new HashEntry($"{schoolId}", fieldContent));
  222. }
  223. await redisClinet8.HashSetAsync(hkey, hvalList.ToArray());
  224. }
  225. }
  226. //記入CosmosDB
  227. if (cosmosSchList.Count > 0)
  228. {
  229. foreach (ProdAnalysisCosmos cosmosSchRow in cosmosSchList)
  230. {
  231. //各校每日CosmosDB記入
  232. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosSchRow);
  233. //所有學校數值加總 數值生成 cosmosAllSchSumDayDic -> key:toolType val:cosmosAllSchSumDay
  234. string toolType = cosmosSchRow.toolType;
  235. string schoolId = "allschool";
  236. ProdAnalysisCosmos cosmosAllSchSumDay = new ProdAnalysisCosmos();
  237. if (cosmosAllSchSumDayDic.ContainsKey(toolType)) cosmosAllSchSumDay = cosmosAllSchSumDayDic[toolType];
  238. foreach (PropertyInfo propertyInfo in cosmosAllSchSumDay.GetType().GetProperties()) //累加項目
  239. {
  240. if (calPropList.Contains(propertyInfo.Name))
  241. {
  242. var propType = propertyInfo.PropertyType;
  243. var valNow = propertyInfo.GetValue(cosmosAllSchSumDay);
  244. var valTodo = cosmosSchRow.GetType().GetProperty(propertyInfo.Name).GetValue(cosmosSchRow);
  245. if (propType.Equals(typeof(long))) propertyInfo.SetValue(cosmosAllSchSumDay, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  246. else propertyInfo.SetValue(cosmosAllSchSumDay, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  247. }
  248. }
  249. cosmosAllSchSumDay.schoolId = schoolId;
  250. cosmosAllSchSumDay.toolType = cosmosSchRow.toolType;
  251. cosmosAllSchSumDay.date = cosmosSchRow.date;
  252. cosmosAllSchSumDay.id = $"{cosmosAllSchSumDay.toolType}-{cosmosAllSchSumDay.date}-{schoolId}";
  253. cosmosAllSchSumDay.dateUnit = "day";
  254. cosmosAllSchSumDay.year = cosmosSchRow.year;
  255. cosmosAllSchSumDay.month = cosmosSchRow.month;
  256. cosmosAllSchSumDay.day = cosmosSchRow.day;
  257. DateTimeOffset dateTime = new DateTimeOffset(cosmosAllSchSumDay.year, cosmosAllSchSumDay.month, cosmosAllSchSumDay.day, 0, 0, 0, TimeSpan.Zero);
  258. cosmosAllSchSumDay.dateTime = dateTime.ToUnixTimeSeconds();
  259. cosmosAllSchSumDay.deviceList = cosmosAllSchSumDay.deviceList.Union(cosmosSchRow.deviceList).ToList();
  260. cosmosAllSchSumDay.deviceCnt = cosmosAllSchSumDay.deviceList.Count;
  261. cosmosAllSchSumDay.deviceAuthList = cosmosAllSchSumDay.deviceAuthList.Union(cosmosSchRow.deviceAuthList).ToList();
  262. cosmosAllSchSumDay.deviceAuth = cosmosAllSchSumDay.deviceAuthList.Count;
  263. cosmosAllSchSumDay.deviceNoAuthList = cosmosAllSchSumDay.deviceNoAuthList.Union(cosmosSchRow.deviceNoAuthList).ToList();
  264. cosmosAllSchSumDay.deviceNoAuth = cosmosAllSchSumDay.deviceNoAuthList.Count;
  265. cosmosAllSchSumDay.tmidList = cosmosAllSchSumDay.tmidList.Union(cosmosSchRow.tmidList).ToList();
  266. cosmosAllSchSumDay.tmidCnt = cosmosAllSchSumDay.tmidList.Count;
  267. if (cosmosAllSchSumDayDic.ContainsKey(toolType)) cosmosAllSchSumDayDic[toolType] = cosmosAllSchSumDay;
  268. else cosmosAllSchSumDayDic.Add(toolType, cosmosAllSchSumDay);
  269. }
  270. //每日所有學校數據總計CosmosDB記入
  271. foreach (KeyValuePair<string, ProdAnalysisCosmos> schItem in cosmosAllSchSumDayDic)
  272. {
  273. string toolType = schItem.Key;
  274. ProdAnalysisCosmos cosmosAllSchSumDay = schItem.Value;
  275. cosmosAllSchSumDay.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  276. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosAllSchSumDay);
  277. }
  278. }
  279. }
  280. //取 Redis 該月所有 ProdAnalysis:Day
  281. //1.生成 Redis ProdAnalysis:Month
  282. //2.生成 CosmosDB Month
  283. Dictionary<string, Dictionary<string, ProdAnalysis>> ProdAnalysisListMonth = new Dictionary<string, Dictionary<string, ProdAnalysis>>();
  284. Dictionary<string, ProdAnalysisCosmos> cosmosAllSchSumMonthDic = new Dictionary<string, ProdAnalysisCosmos>();
  285. List<ProdAnalysisCosmos> cosmosSchListMonth = new List<ProdAnalysisCosmos>();
  286. string patternD = $"ProdAnalysis:Day:HiT*:{y}{m}*";
  287. List<string> keysDayList = ScanRedisKeysByPattern(_azureRedis, patternD);
  288. if (keysDayList.Count > 0)
  289. {
  290. foreach (string keyDay in keysDayList)
  291. {
  292. string[] keyItemList = keyDay.Split(':'); //ProdAnalysis:Day:HiTeach:20230326
  293. string toolType = keyItemList[2];
  294. string dateStrD = keyItemList[3];
  295. string dateStrD_y = string.Empty;
  296. string dateStrD_m = string.Empty;
  297. string dateStrD_d = string.Empty;
  298. Regex rgx = new Regex(@"[0-9]{8}");
  299. if (rgx.IsMatch(dateStrD))
  300. {
  301. dateStrD_y = dateStrD.Substring(0, 4);
  302. dateStrD_m = dateStrD.Substring(4, 2);
  303. dateStrD_d = dateStrD.Substring(6, 2);
  304. }
  305. string prodAnalMonthKey = $"ProdAnalysis:Month:{toolType}:{dateStrD_y}{dateStrD_m}";
  306. bool ProdAnalysisDayExist = await redisClinet8.KeyExistsAsync(keyDay);
  307. if (ProdAnalysisDayExist && !string.IsNullOrWhiteSpace(dateStrD_y) && !string.IsNullOrWhiteSpace(dateStrD_m) && !string.IsNullOrWhiteSpace(dateStrD_d))
  308. {
  309. HashEntry[] hsetDay = redisClinet8.HashGetAll(keyDay); //某日 ProdAnalysis:Day所有學校的統計項目
  310. foreach (HashEntry hset in hsetDay) {
  311. string keySchId = hset.Name;
  312. string valSchDataJson = hset.Value;
  313. ProdAnalysis SchDataTodo = valSchDataJson.ToObject<ProdAnalysis>();
  314. //Redis Month 資料生成
  315. if (ProdAnalysisListMonth.ContainsKey(prodAnalMonthKey)) //月Dic已有此key => 分校累加
  316. {
  317. if (ProdAnalysisListMonth[$"{prodAnalMonthKey}"].ContainsKey($"{keySchId}"))
  318. {
  319. ProdAnalysis SchDataNow = ProdAnalysisListMonth[$"{prodAnalMonthKey}"][$"{keySchId}"];
  320. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  321. {
  322. if (calPropList.Contains(propertyInfo.Name))
  323. {
  324. var propType = propertyInfo.PropertyType;
  325. var valNow = propertyInfo.GetValue(SchDataNow);
  326. var valTodo = SchDataTodo.GetType().GetProperty(propertyInfo.Name).GetValue(SchDataTodo);
  327. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  328. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  329. }
  330. }
  331. SchDataNow.deviceList = SchDataNow.deviceList.Union(SchDataTodo.deviceList).ToList();
  332. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  333. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(SchDataTodo.deviceAuthList).ToList();
  334. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  335. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(SchDataTodo.deviceNoAuthList).ToList();
  336. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  337. SchDataNow.tmidList = SchDataNow.tmidList.Union(SchDataTodo.tmidList).ToList();
  338. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  339. }
  340. //無此校資料 => 該校資料放入
  341. else
  342. {
  343. ProdAnalysisListMonth[$"{prodAnalMonthKey}"][$"{keySchId}"] = SchDataTodo;
  344. }
  345. }
  346. else //無此月資料 => 所有學校資料放入
  347. {
  348. ProdAnalysisListMonth.Add(prodAnalMonthKey, new Dictionary<string, ProdAnalysis>() { { keySchId, SchDataTodo } });
  349. }
  350. }
  351. }
  352. }
  353. }
  354. if (ProdAnalysisListMonth.Count > 0)
  355. {
  356. foreach (KeyValuePair<string, Dictionary<string, ProdAnalysis>> item in ProdAnalysisListMonth)
  357. {
  358. string monthRedisKey = item.Key;
  359. List<HashEntry> hvalList = new List<HashEntry>();
  360. Dictionary<string, ProdAnalysis> monthRedisSchDIc = item.Value;
  361. foreach (KeyValuePair<string, ProdAnalysis> monthRedisSchItem in monthRedisSchDIc)
  362. {
  363. string monthRedisSchId = monthRedisSchItem.Key;
  364. ProdAnalysis monthRedisSchData = monthRedisSchItem.Value;
  365. //Redis資料製作
  366. hvalList.Add(new HashEntry(monthRedisSchId, monthRedisSchData.ToJsonString()));
  367. //CosmosDB資料製作
  368. ProdAnalysisCosmos cosmosSchRow = monthRedisSchData.ToJsonString().ToObject<ProdAnalysisCosmos>();
  369. cosmosSchRow.date = $"{y}{m}";
  370. cosmosSchRow.year = Convert.ToInt32(y, 10);
  371. cosmosSchRow.month = Convert.ToInt32(m, 10);
  372. DateTimeOffset dateTime = new DateTimeOffset(cosmosSchRow.year, cosmosSchRow.month, 1, 0, 0, 0, TimeSpan.Zero);
  373. cosmosSchRow.dateTime = dateTime.ToUnixTimeSeconds();
  374. cosmosSchRow.id = $"{monthRedisSchData.toolType}-{cosmosSchRow.date}-{monthRedisSchId}";
  375. cosmosSchRow.dateUnit = "month";
  376. cosmosSchRow.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  377. cosmosSchListMonth.Add(cosmosSchRow);
  378. }
  379. //記入Redis
  380. await redisClinet8.HashSetAsync($"{monthRedisKey}", hvalList.ToArray());
  381. }
  382. //記入CosmosDB
  383. if (cosmosSchListMonth.Count > 0)
  384. {
  385. foreach (ProdAnalysisCosmos cosmosSchRow in cosmosSchListMonth)
  386. {
  387. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosSchRow);
  388. //所有學校數值加總 數值生成 cosmosAllSchSumDayDic -> key:toolType val:cosmosAllSchSumDay
  389. string toolType = cosmosSchRow.toolType;
  390. string schoolId = "allschool";
  391. ProdAnalysisCosmos cosmosAllSchSumMonth = new ProdAnalysisCosmos();
  392. if (cosmosAllSchSumMonthDic.ContainsKey(toolType)) cosmosAllSchSumMonth = cosmosAllSchSumMonthDic[toolType];
  393. foreach (PropertyInfo propertyInfo in cosmosAllSchSumMonth.GetType().GetProperties()) //累加項目
  394. {
  395. if (calPropList.Contains(propertyInfo.Name))
  396. {
  397. var propType = propertyInfo.PropertyType;
  398. var valNow = propertyInfo.GetValue(cosmosAllSchSumMonth);
  399. var valTodo = cosmosSchRow.GetType().GetProperty(propertyInfo.Name).GetValue(cosmosSchRow);
  400. if (propType.Equals(typeof(long))) propertyInfo.SetValue(cosmosAllSchSumMonth, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  401. else propertyInfo.SetValue(cosmosAllSchSumMonth, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  402. }
  403. }
  404. cosmosAllSchSumMonth.schoolId = schoolId;
  405. cosmosAllSchSumMonth.toolType = cosmosSchRow.toolType;
  406. cosmosAllSchSumMonth.date = cosmosSchRow.date;
  407. cosmosAllSchSumMonth.id = $"{cosmosAllSchSumMonth.toolType}-{cosmosAllSchSumMonth.date}-{schoolId}";
  408. cosmosAllSchSumMonth.dateUnit = "month";
  409. cosmosAllSchSumMonth.year = cosmosSchRow.year;
  410. cosmosAllSchSumMonth.month = cosmosSchRow.month;
  411. DateTimeOffset dateTime = new DateTimeOffset(cosmosAllSchSumMonth.year, cosmosAllSchSumMonth.month, 1, 0, 0, 0, TimeSpan.Zero);
  412. cosmosAllSchSumMonth.dateTime = dateTime.ToUnixTimeSeconds();
  413. cosmosAllSchSumMonth.deviceList = cosmosAllSchSumMonth.deviceList.Union(cosmosSchRow.deviceList).ToList();
  414. cosmosAllSchSumMonth.deviceCnt = cosmosAllSchSumMonth.deviceList.Count;
  415. cosmosAllSchSumMonth.deviceAuthList = cosmosAllSchSumMonth.deviceAuthList.Union(cosmosSchRow.deviceAuthList).ToList();
  416. cosmosAllSchSumMonth.deviceAuth = cosmosAllSchSumMonth.deviceAuthList.Count;
  417. cosmosAllSchSumMonth.deviceNoAuthList = cosmosAllSchSumMonth.deviceNoAuthList.Union(cosmosSchRow.deviceNoAuthList).ToList();
  418. cosmosAllSchSumMonth.deviceNoAuth = cosmosAllSchSumMonth.deviceNoAuthList.Count;
  419. cosmosAllSchSumMonth.tmidList = cosmosAllSchSumMonth.tmidList.Union(cosmosSchRow.tmidList).ToList();
  420. cosmosAllSchSumMonth.tmidCnt = cosmosAllSchSumMonth.tmidList.Count;
  421. if (cosmosAllSchSumMonthDic.ContainsKey(toolType)) cosmosAllSchSumMonthDic[toolType] = cosmosAllSchSumMonth;
  422. else cosmosAllSchSumMonthDic.Add(toolType, cosmosAllSchSumMonth);
  423. }
  424. //每月所有學校數據總計CosmosDB記入
  425. foreach (KeyValuePair<string, ProdAnalysisCosmos> schItem in cosmosAllSchSumMonthDic)
  426. {
  427. string toolType = schItem.Key;
  428. ProdAnalysisCosmos cosmosAllSchSumMonth = schItem.Value;
  429. cosmosAllSchSumMonth.createDate = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  430. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(cosmosAllSchSumMonth);
  431. }
  432. }
  433. }
  434. //取該年所有 CosmosDB 該年所有月份 生成CosmosDB年資料
  435. Dictionary<string, Dictionary<string, ProdAnalysisCosmos>> ProdAnalysisListYear = new Dictionary<string, Dictionary<string, ProdAnalysisCosmos>>();
  436. var query = $"SELECT * FROM c WHERE c.year = {y} AND c.dateUnit = 'month' AND c.schoolId != 'allschool'";
  437. await foreach (var itemcr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("ProdAnalysis") }))
  438. {
  439. var json = await JsonDocument.ParseAsync(itemcr.ContentStream);
  440. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  441. {
  442. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  443. {
  444. ProdAnalysisCosmos SchDataTodo = obj.ToObject<ProdAnalysisCosmos>();
  445. string toolType = SchDataTodo.toolType;
  446. string schId = SchDataTodo.schoolId;
  447. //年Dic已有此key => 分校累加
  448. if (ProdAnalysisListYear.ContainsKey(toolType))
  449. {
  450. if (ProdAnalysisListYear[$"{toolType}"].ContainsKey($"{schId}"))
  451. {
  452. ProdAnalysisCosmos SchDataNow = ProdAnalysisListYear[$"{toolType}"][$"{schId}"];
  453. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  454. {
  455. if (calPropList.Contains(propertyInfo.Name))
  456. {
  457. var propType = propertyInfo.PropertyType;
  458. var valNow = propertyInfo.GetValue(SchDataNow);
  459. var valTodo = SchDataTodo.GetType().GetProperty(propertyInfo.Name).GetValue(SchDataTodo);
  460. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  461. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  462. }
  463. }
  464. SchDataNow.deviceList = SchDataNow.deviceList.Union(SchDataTodo.deviceList).ToList();
  465. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  466. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(SchDataTodo.deviceAuthList).ToList();
  467. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  468. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(SchDataTodo.deviceNoAuthList).ToList();
  469. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  470. SchDataNow.tmidList = SchDataNow.tmidList.Union(SchDataTodo.tmidList).ToList();
  471. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  472. }
  473. //無此校資料 => 該校資料放入
  474. else
  475. {
  476. ProdAnalysisCosmos SchDataNow = SchDataTodo;
  477. SchDataNow.date = $"{y}";
  478. SchDataNow.year = Convert.ToInt32(y, 10);
  479. SchDataNow.month = 0;
  480. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  481. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  482. SchDataNow.id = $"{toolType}-{y}-{schId}";
  483. SchDataNow.dateUnit = "year";
  484. ProdAnalysisListYear[$"{toolType}"][$"{schId}"] = SchDataNow;
  485. }
  486. }
  487. //無此年資料 => 所有學校資料放入
  488. else
  489. {
  490. ProdAnalysisCosmos SchDataNow = SchDataTodo;
  491. SchDataNow.date = $"{y}";
  492. SchDataNow.year = Convert.ToInt32(y, 10);
  493. SchDataNow.month = 0;
  494. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  495. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  496. SchDataNow.id = $"{toolType}-{y}-{schId}";
  497. SchDataNow.dateUnit = "year";
  498. ProdAnalysisListYear.Add(toolType, new Dictionary<string, ProdAnalysisCosmos>() { { schId, SchDataNow } });
  499. }
  500. }
  501. }
  502. }
  503. if (ProdAnalysisListYear.Count > 0)
  504. {
  505. foreach (KeyValuePair<string, Dictionary<string, ProdAnalysisCosmos>> item in ProdAnalysisListYear)
  506. {
  507. string toolType = item.Key;
  508. ProdAnalysisCosmos SchDataNow = new ProdAnalysisCosmos(); //當年某產品所有學校總和
  509. Dictionary<string, ProdAnalysisCosmos> yearCosmosSchDIc = item.Value;
  510. foreach (KeyValuePair<string, ProdAnalysisCosmos> yearCosmosSchItem in yearCosmosSchDIc)
  511. {
  512. string schId = yearCosmosSchItem.Key;
  513. ProdAnalysisCosmos yearCosmosSchData = yearCosmosSchItem.Value;
  514. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(yearCosmosSchData);
  515. //每年所有學校數據總計CosmosDB記入
  516. foreach (PropertyInfo propertyInfo in SchDataNow.GetType().GetProperties())
  517. {
  518. if (calPropList.Contains(propertyInfo.Name))
  519. {
  520. var propType = propertyInfo.PropertyType;
  521. var valNow = propertyInfo.GetValue(SchDataNow);
  522. var valTodo = yearCosmosSchData.GetType().GetProperty(propertyInfo.Name).GetValue(yearCosmosSchData);
  523. if (propType.Equals(typeof(long))) propertyInfo.SetValue(SchDataNow, Convert.ToInt64(valNow.ToString(), 10) + Convert.ToInt64(valTodo.ToString(), 10));
  524. else propertyInfo.SetValue(SchDataNow, Convert.ToInt32(valNow.ToString(), 10) + Convert.ToInt32(valTodo.ToString(), 10));
  525. }
  526. }
  527. SchDataNow.schoolId = "allschool";
  528. SchDataNow.toolType = yearCosmosSchData.toolType;
  529. SchDataNow.date = yearCosmosSchData.date;
  530. SchDataNow.id = $"{yearCosmosSchData.toolType}-{yearCosmosSchData.date}-allschool";
  531. SchDataNow.dateUnit = "year";
  532. SchDataNow.year = yearCosmosSchData.year;
  533. SchDataNow.month = 0;
  534. DateTimeOffset dateTime = new DateTimeOffset(SchDataNow.year, 1, 1, 0, 0, 0, TimeSpan.Zero);
  535. SchDataNow.dateTime = dateTime.ToUnixTimeSeconds();
  536. SchDataNow.deviceList = SchDataNow.deviceList.Union(yearCosmosSchData.deviceList).ToList();
  537. SchDataNow.deviceCnt = SchDataNow.deviceList.Count;
  538. SchDataNow.deviceAuthList = SchDataNow.deviceAuthList.Union(yearCosmosSchData.deviceAuthList).ToList();
  539. SchDataNow.deviceAuth = SchDataNow.deviceAuthList.Count;
  540. SchDataNow.deviceNoAuthList = SchDataNow.deviceNoAuthList.Union(yearCosmosSchData.deviceNoAuthList).ToList();
  541. SchDataNow.deviceNoAuth = SchDataNow.deviceNoAuthList.Count;
  542. SchDataNow.tmidList = SchDataNow.tmidList.Union(yearCosmosSchData.tmidList).ToList();
  543. SchDataNow.tmidCnt = SchDataNow.tmidList.Count;
  544. }
  545. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ProdAnalysisCosmos>(SchDataNow);
  546. }
  547. }
  548. //虛擬學校創建
  549. if (crtVirtualSchoolId.Count > 0)
  550. {
  551. //取得IES5 school Base
  552. string schIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  553. string schBaseQueryText = $"SELECT c.id FROM c where ARRAY_CONTAINS({schIdListStr}, c.id, true)";
  554. await foreach (var itemsr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: schBaseQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  555. {
  556. using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
  557. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  558. {
  559. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  560. {
  561. string existSchid = obj.GetProperty("id").GetString();
  562. if (crtVirtualSchoolId.Contains(existSchid))
  563. {
  564. crtVirtualSchoolId.Remove(existSchid);
  565. }
  566. }
  567. }
  568. }
  569. //取得IES5 school VirtualBase
  570. schIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  571. schBaseQueryText = $"SELECT c.id FROM c where ARRAY_CONTAINS({schIdListStr}, c.id, true)";
  572. await foreach (var itemsr in _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: schBaseQueryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"VirtualBase") }))
  573. {
  574. using var json = await JsonDocument.ParseAsync(itemsr.ContentStream);
  575. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  576. {
  577. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  578. {
  579. string existSchid = obj.GetProperty("id").GetString();
  580. if (crtVirtualSchoolId.Contains(existSchid))
  581. {
  582. crtVirtualSchoolId.Remove(existSchid);
  583. }
  584. }
  585. }
  586. }
  587. //VirtualBase school 建立
  588. if(crtVirtualSchoolId.Count > 0)
  589. {
  590. //取得CSV1 schoolcode,存在者建立IES5 VirtualBase school
  591. List<School> crtVSchoolList = new List<School>();
  592. string csv1SchIdListStr = JsonConvert.SerializeObject(crtVirtualSchoolId);
  593. 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)";
  594. await foreach (var item in _azureCosmosClientCsv1.GetContainer("Core", "SchoolCode").GetItemQueryStreamIterator(queryText: schCsv1QueryText, requestOptions: null ))
  595. {
  596. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  597. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  598. {
  599. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  600. {
  601. School crtVSchool = new School();
  602. crtVSchool.code = "VirtualBase";
  603. crtVSchool.id = obj.GetProperty("shortCode").GetString();
  604. crtVSchool.pk = "School";
  605. crtVSchool.schoolCode = obj.GetProperty("shortCode").GetString();
  606. crtVSchool.name = obj.GetProperty("name").GetString();
  607. crtVSchool.region = (obj.TryGetProperty("countryName", out JsonElement countryNameJ)) ? Convert.ToString(countryNameJ) : null;
  608. crtVSchool.province = (obj.TryGetProperty("provinceName", out JsonElement provinceNameJ)) ? Convert.ToString(provinceNameJ) : null;
  609. crtVSchool.city = (obj.TryGetProperty("cityName", out JsonElement cityNameJ)) ? Convert.ToString(cityNameJ) : null;
  610. crtVSchool.dist = (obj.TryGetProperty("distName", out JsonElement distNameJ)) ? Convert.ToString(distNameJ) : null;
  611. crtVSchool.address = (obj.TryGetProperty("address", out JsonElement addressJ)) ? Convert.ToString(addressJ) : null;
  612. crtVSchool.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  613. await _azureCosmosClient.GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<School>(crtVSchool);
  614. }
  615. }
  616. }
  617. }
  618. }
  619. }
  620. catch (Exception ex)
  621. {
  622. _ = _dingDing.SendBotMsg($"BI,{Environment.GetEnvironmentVariable("Option:Location")},BICreatDailyAnalData() IOT產品分析資料生成錯誤\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.成都开发測試群組);
  623. }
  624. }
  625. /// <summary>
  626. /// 取得Redis(8)符合搜尋模式的key
  627. /// </summary>
  628. /// <param name="pattern"></param>
  629. /// <returns></returns>
  630. public static List<string> ScanRedisKeysByPattern(AzureRedisFactory _azureRedis, string pattern)
  631. {
  632. var redisClinet8 = _azureRedis.GetRedisClient(8);
  633. var keys = new HashSet<RedisKey>();
  634. int nextCursor = 0;
  635. do
  636. {
  637. RedisResult redisResult = redisClinet8.Execute("SCAN", nextCursor.ToString(), "MATCH", pattern, "COUNT", "1000");
  638. var innerResult = (RedisResult[])redisResult;
  639. nextCursor = int.Parse((string)innerResult[0]);
  640. List<RedisKey> resultLines = ((RedisKey[])innerResult[1]).ToList();
  641. keys.UnionWith(resultLines);
  642. }
  643. while (nextCursor != 0);
  644. List<string> result = new List<string>();
  645. if (keys.Count > 0)
  646. {
  647. foreach (RedisKey key in keys)
  648. {
  649. result.Add(key.ToString());
  650. }
  651. }
  652. return result;
  653. }
  654. }
  655. }