BIProdAnalysis.cs 44 KB

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