LessonRecordController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using DocumentFormat.OpenXml.Drawing.Charts;
  2. using HTEX.Lib.ETL.Lesson;
  3. using MathNet.Numerics.Distributions;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Azure.Cosmos;
  6. using StackExchange.Redis;
  7. using System.Text.Json;
  8. using System.Xml;
  9. using TEAMModelOS.SDK;
  10. using TEAMModelOS.SDK.DI;
  11. using TEAMModelOS.SDK.Extension;
  12. using TEAMModelOS.SDK.Helper.Common.FileHelper;
  13. using TEAMModelOS.SDK.Models;
  14. using TEAMModelOS.SDK.Models.Cosmos.Common;
  15. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  16. namespace HTEX.DataETL.Controllers
  17. {
  18. [ApiController]
  19. [Route("lesson-record")]
  20. public class LessonRecordController : ControllerBase
  21. {
  22. private readonly ILogger<LessonRecordController> _logger;
  23. private readonly AzureCosmosFactory _azureCosmos;
  24. private readonly AzureStorageFactory _azureStorage;
  25. private readonly IConfiguration _configuration;
  26. private readonly IWebHostEnvironment _webHostEnvironment;
  27. private readonly DingDing _dingDing;
  28. private readonly AzureRedisFactory _azureRedis;
  29. public LessonRecordController(ILogger<LessonRecordController> logger, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage , IConfiguration configuration, IWebHostEnvironment environment,DingDing dingDing,AzureRedisFactory azureRedis )
  30. {
  31. _logger = logger;
  32. _azureCosmos = azureCosmos;
  33. _azureStorage = azureStorage;
  34. _configuration = configuration;
  35. _webHostEnvironment = environment;
  36. _dingDing = dingDing;
  37. _azureRedis = azureRedis;
  38. }
  39. [HttpPost("process-local")]
  40. public async Task<IActionResult> ProcessLocal(JsonElement json)
  41. {
  42. List<StudentLessonData> studentLessonDatas = new List<StudentLessonData>();
  43. string? id = json.GetProperty("id").GetString();
  44. if (!string.IsNullOrWhiteSpace(id))
  45. {
  46. string? lessonPath = _configuration.GetValue<string>("LessonPath");
  47. string? path = $"{lessonPath}\\locals\\{id}";
  48. var files = FileHelper.ListAllFiles(path);
  49. // var sampleJson =System.IO. File.ReadAllTextAsync(path);
  50. LessonBase? lessonBase = null;
  51. List<LocalStudent> localStudents = new List<LocalStudent>();
  52. List<TaskData> taskDatas = new List<TaskData>();
  53. List<SmartRatingData> smartRatingDatas = new List<SmartRatingData>();
  54. List<IRSData> irsDatas = new List<IRSData>();
  55. List<CoworkData> coworkDatas = new List<CoworkData>();
  56. List<ExamData> examDatas = new List<ExamData>();
  57. TimeLineData? timeLineData = null;
  58. foreach (var item in files)
  59. {
  60. if (item.Contains("IES\\base.json"))
  61. {
  62. string jsons = await System.IO.File.ReadAllTextAsync(item);
  63. jsons = jsons.Replace("\"Uncall\"", "0").Replace("Uncall", "0");
  64. lessonBase = jsons.ToObject<LessonBase>();
  65. var data = LessonETLService.GetBaseData(lessonBase);
  66. localStudents = data.studentLessonDatas;
  67. }
  68. if (item.Contains("IES\\TimeLine.json"))
  69. {
  70. string jsons = await System.IO.File.ReadAllTextAsync(item);
  71. timeLineData = jsons.ToObject<TimeLineData>();
  72. }
  73. if (item.Contains("IES\\Task.json"))
  74. {
  75. string jsons = await System.IO.File.ReadAllTextAsync(item);
  76. taskDatas = jsons.ToObject<List<TaskData>>();
  77. }
  78. if (item.Contains("IES\\SmartRating.json"))
  79. {
  80. string jsons = await System.IO.File.ReadAllTextAsync(item);
  81. smartRatingDatas = jsons.ToObject<List<SmartRatingData>>();
  82. }
  83. if (item.Contains("IES\\IRS.json"))
  84. {
  85. string jsons = await System.IO.File.ReadAllTextAsync(item);
  86. irsDatas = jsons.ToObject<List<IRSData>>();
  87. }
  88. if (item.Contains("IES\\Cowork.json"))
  89. {
  90. string jsons = await System.IO.File.ReadAllTextAsync(item);
  91. coworkDatas = jsons.ToObject<List<CoworkData>>();
  92. }
  93. try
  94. {
  95. if (item.Contains($"\\{id}\\Exam\\") && item.EndsWith("Exam.json"))
  96. {
  97. string examsFile = item;
  98. if (examsFile.EndsWith("Exam.json"))
  99. {
  100. ExamData? examData = null;
  101. string jsons = await System.IO.File.ReadAllTextAsync(item);
  102. jsons = jsons.Replace("\"publish\": \"0\"", "\"publish\": 0").Replace("\"publish\": \"1\"", "\"publish\": 1");
  103. examData = jsons.ToObject<ExamData>();
  104. if (examData != null && examData.exam.papers.IsNotEmpty())
  105. {
  106. string paperId = examData.exam.papers.First().id;
  107. string paperPath = $"{path}\\ExamPaper\\{paperId}\\index.json";
  108. string jsonp = await System.IO.File.ReadAllTextAsync(paperPath);
  109. LessonPaper lessonPaper = jsonp.ToObject<LessonPaper>();
  110. examData.paper = lessonPaper;
  111. examDatas.Add(examData);
  112. }
  113. }
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.LogError(ex, ex.Message);
  119. }
  120. }
  121. if (lessonBase!=null && timeLineData!=null)
  122. {
  123. studentLessonDatas = localStudents.ToJsonString().ToObject<List<StudentLessonData>>();
  124. studentLessonDatas = LessonETLService.GetBaseInfo(lessonBase!, studentLessonDatas, id);
  125. studentLessonDatas = LessonETLService.GetIRSData(lessonBase, timeLineData, irsDatas, studentLessonDatas, examDatas, id);
  126. studentLessonDatas = LessonETLService.GetCoworkData(lessonBase, timeLineData, coworkDatas, studentLessonDatas, id);
  127. studentLessonDatas = LessonETLService.GetExamData(lessonBase, timeLineData, examDatas, studentLessonDatas, Constant.objectiveTypes, id);
  128. studentLessonDatas = LessonETLService.GetSmartRatingData(lessonBase, timeLineData, smartRatingDatas, studentLessonDatas, id);
  129. studentLessonDatas = LessonETLService.GetTaskData(lessonBase, timeLineData, taskDatas, studentLessonDatas, id);
  130. var pickupData = LessonETLService.GetPickupData(lessonBase, timeLineData, studentLessonDatas, id);
  131. studentLessonDatas= pickupData.studentLessonDatas;
  132. await System.IO.File.WriteAllTextAsync(Path.Combine(path, $"student-analysis.json"), studentLessonDatas.ToJsonString());
  133. string jsons = await System.IO.File.ReadAllTextAsync($"{lessonPath}\\analysis\\analysis.json");
  134. LessonDataAnalysisCluster lessonDataAnalysis = jsons.ToObject<LessonDataAnalysisCluster>();
  135. var lessonItems = LessonETLService.ProcessStudentDataV2(studentLessonDatas, lessonDataAnalysis);
  136. XmlDocument xmlDocument = new XmlDocument();
  137. var runtimePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  138. xmlDocument.Load($"{runtimePath}\\summary.xml");
  139. await LessonETLService.ExportToExcelLocal(lessonItems, $"{path}\\analysis.xlsx", xmlDocument);
  140. }
  141. }
  142. return Ok();
  143. }
  144. /// <summary>
  145. ///
  146. /// </summary>
  147. /// <param name="json"></param>
  148. /// <returns></returns>
  149. //[HttpPost("process-fix-history-students")]
  150. //public async Task<IActionResult> ProcessFixHistoryStudents(JsonElement json)
  151. //{
  152. // string? lessonBasePath = _configuration.GetValue<string>("LessonPath");
  153. // string studentsPath = $"{lessonBasePath}\\students";
  154. // List<string> studentsPs = FileHelper.ListAllFiles(studentsPath);
  155. // string? pathLessons = $"{lessonBasePath}\\lessons";
  156. // List<string> filesLessons = FileHelper.ListAllFiles(pathLessons, "-local.json");
  157. // int index = 0;
  158. // foreach (var stu in studentsPs)
  159. // {
  160. // string stujson = await System.IO.File.ReadAllTextAsync(stu);
  161. // var studentSemester = stujson.ToObject<StudentSemesterRecord>();
  162. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(studentSemester, new PartitionKey(studentSemester.code));
  163. // index++;
  164. // }
  165. // return Ok();
  166. //}
  167. /// <summary>
  168. ///
  169. /// </summary>
  170. /// <param name="json"></param>
  171. /// <returns></returns>
  172. [HttpPost("process-history-students")]
  173. public async Task<IActionResult> ProcessHistoryStudents(JsonElement json)
  174. {
  175. string? lessonBasePath = _configuration.GetValue<string>("LessonPath");
  176. string? pathLessons = $"{lessonBasePath}\\lessons";
  177. string? pathAnalysis = $"{lessonBasePath}\\analysis";
  178. string jsons = await System.IO.File.ReadAllTextAsync($"{pathAnalysis}\\analysis.json");
  179. LessonDataAnalysisCluster lessonDataAnalysis = jsons.ToObject<LessonDataAnalysisCluster>();
  180. List<string> filesLessons = FileHelper.ListAllFiles(pathLessons, "-local.json");
  181. var runtimePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  182. XmlDocument xmlDocument = new XmlDocument();
  183. xmlDocument.Load($"{runtimePath}\\summary.xml");
  184. List<StudentSemesterRecord> students = new List<StudentSemesterRecord>();
  185. List<School> schools = new List<School>();
  186. // await Parallel.ForEachAsync(filesLessons, async (fileLesson, _) =>
  187. List<string> localIds = new List<string>();
  188. foreach (var file in filesLessons)
  189. {
  190. if (file.EndsWith("-local.json"))
  191. {
  192. string lessonId = file.Split("\\").Last().Replace("-local.json", "");
  193. localIds.Add(lessonId);
  194. }
  195. }
  196. long stime = 1690819200000;//2023-08-01 00:00:00
  197. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  198. .GetList<LessonRecord>($"SELECT value c FROM c where c.startTime>{stime} and c.expire<=0 and c.status<>404 and c.duration>300 and c.pk='LessonRecord' ", $"LessonRecord-ydzt");
  199. List<string> ignore = new List<string>() { "PgJump", "PgRcv", "PgAdd" };
  200. int index = 0;
  201. if (resultSchool.list.IsNotEmpty())
  202. {
  203. List<StudentSemesterRecord> studentSemesterRecords= new List<StudentSemesterRecord>();
  204. List<OverallEducation> overallEducations= new List<OverallEducation>();
  205. List<Student> studentsBase = new List<Student>();
  206. await foreach (var item in LessonETLService.GetLessonLocal(resultSchool.list, localIds, _azureStorage, pathLessons))
  207. {
  208. string yearMonthPath = DateTimeOffset.FromUnixTimeMilliseconds(item.lessonRecord.startTime).ToString("yyyyMM");
  209. if (item.lessonBase!=null && item.lessonBase.student!=null)
  210. {
  211. TechCount techCount = new TechCount
  212. {
  213. lessonId=item.lessonRecord?.id,
  214. examCount = item.examDatas.Count,
  215. taskCount = item.taskDatas.Count,
  216. irsCount = item.irsDatas.Count,
  217. coworkCount = item.coworkDatas.Count,
  218. smartRatingCount =item.smartRatingDatas.Count,
  219. timeCount=item.sokratesDatas.Where(x => !ignore.Contains(x.Event) && !x.Event.Contains("End", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Event).Select(x => new CodeLong() { code=x.Key, value= x.ToList().Count }).ToList()
  220. };
  221. await System.IO.File.WriteAllTextAsync($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord.id}-count.json", techCount.ToJsonString());
  222. await System.IO.File.WriteAllTextAsync($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-local.json", item.ToJsonString());
  223. }
  224. else
  225. {
  226. System.IO.File.Delete($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-local.json");
  227. System.IO.File.Delete($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-count.json");
  228. }
  229. await LessonETLService.DoStudentLessonData(Constant.objectiveTypes, _azureStorage, item, _dingDing, _azureCosmos.GetCosmosClient(), "China", _azureRedis, studentSemesterRecords,overallEducations, lessonDataAnalysis, studentsBase, schools);
  230. index++;
  231. }
  232. foreach (var studentSemester in studentSemesterRecords)
  233. {
  234. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(studentSemester, new PartitionKey(studentSemester.code));
  235. }
  236. foreach (var overallEducation in overallEducations)
  237. {
  238. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
  239. string key = $"OverallEducation:{overallEducation.schoolCode}:{overallEducation.periodId}:{overallEducation.year}:{overallEducation.semesterId}:{overallEducation?.classId}";
  240. await _azureRedis.GetRedisClient(8).HashSetAsync(key, overallEducation.studentId, overallEducation.ToJsonString());
  241. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key, new TimeSpan(180 *24, 0, 0));
  242. }
  243. }
  244. return Ok();
  245. }
  246. /// <summary>
  247. /// 课例数据ETL处理过程
  248. /// </summary>
  249. /// <param name="json"></param>
  250. /// <returns></returns>
  251. [HttpPost("process-history")]
  252. public async Task<IActionResult> ProcessHistory(JsonElement json)
  253. {
  254. List<string> localIds = new List<string>();
  255. string? lessonBasePath = _configuration.GetValue<string>("LessonPath");
  256. string? pathLessons = $"{lessonBasePath}\\lessons";
  257. string? pathAnalysis = $"{lessonBasePath}\\analysis";
  258. var filesLessons = FileHelper.ListAllFiles(pathLessons);
  259. foreach (var file in filesLessons)
  260. {
  261. if (file.EndsWith("-local.json"))
  262. {
  263. string lessonId = file.Split("\\").Last().Replace("-local.json", "");
  264. localIds.Add(lessonId);
  265. }
  266. }
  267. bool loadLocal = true;
  268. List<LessonDataAnalysisMonth> lessonDataAnalysisMonths = new List<LessonDataAnalysisMonth>();
  269. var filesAnalysis = FileHelper.ListAllFiles(pathAnalysis);
  270. long stime = 1690819200000;//2023-08-01 00:00:00
  271. foreach (var file in filesAnalysis)
  272. {
  273. //读取每月的数据
  274. if (file.EndsWith("-m-analysis.json"))
  275. {
  276. string jsons = await System.IO.File.ReadAllTextAsync(file);
  277. LessonDataAnalysisMonth lessonDataAnalysis = jsons.ToObject<LessonDataAnalysisMonth>();
  278. lessonDataAnalysisMonths.Add(lessonDataAnalysis);
  279. }
  280. }
  281. if (lessonDataAnalysisMonths.IsNotEmpty())
  282. {
  283. var maxUpdateTime = lessonDataAnalysisMonths.Max(x => x.updateTime);
  284. if (maxUpdateTime>0)
  285. {
  286. //更新周期是一周
  287. if (DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()- maxUpdateTime>604800000)
  288. {
  289. stime=maxUpdateTime;
  290. loadLocal =true;
  291. }
  292. else
  293. {
  294. stime=maxUpdateTime;
  295. loadLocal=false;
  296. }
  297. }
  298. }
  299. HashSet<string> yearMonth = new HashSet<string>();
  300. long newest = 0;
  301. bool force = false;
  302. if ((json.TryGetProperty("force", out JsonElement _force)&& _force.ValueKind.Equals(JsonValueKind.True)))
  303. {
  304. force= _force.GetBoolean();
  305. }
  306. // if (loadLocal ||force)
  307. {
  308. List<LessonRecord> lessonRecords = new List<LessonRecord>();
  309. var resultSchool = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  310. .GetList<LessonRecord>($"SELECT value c FROM c where c.startTime>={stime} and c.expire<=0 and c.status<>404 and c.duration>300 and c.pk='LessonRecord' ", null);
  311. if (resultSchool.list.IsNotEmpty())
  312. {
  313. newest= resultSchool.list.Max(x => x.startTime);
  314. lessonRecords.AddRange(resultSchool.list);
  315. }
  316. else
  317. {
  318. newest=stime;
  319. }
  320. var resultTeacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  321. .GetList<LessonRecord>($"SELECT value c FROM c where c.startTime>={stime} and c.expire<=0 and c.status<>404 and c.duration>300 and c.pk='LessonRecord' ", null);
  322. if (resultTeacher.list.IsNotEmpty())
  323. {
  324. long max = resultTeacher.list.Max(x => x.startTime);
  325. if (max<newest)
  326. {
  327. newest=max;
  328. }
  329. lessonRecords.AddRange(resultTeacher.list);
  330. }
  331. List<string> ignore = new List<string>() { "PgJump", "PgRcv", "PgAdd" };
  332. if (lessonRecords.IsNotEmpty())
  333. {
  334. await foreach (var item in LessonETLService.GetLessonLocal(lessonRecords, localIds, _azureStorage, pathLessons))
  335. {
  336. string yearMonthPath = DateTimeOffset.FromUnixTimeMilliseconds(item.lessonRecord.startTime).ToString("yyyyMM");
  337. if (item.lessonBase!=null && item.lessonBase.student!=null)
  338. {
  339. TechCount techCount = new TechCount
  340. {
  341. lessonId=item.lessonRecord?.id,
  342. examCount = item.examDatas.Count,
  343. taskCount = item.taskDatas.Count,
  344. irsCount = item.irsDatas.Count,
  345. coworkCount = item.coworkDatas.Count,
  346. smartRatingCount =item.smartRatingDatas.Count,
  347. timeCount=item.sokratesDatas.Where(x => !ignore.Contains(x.Event) && !x.Event.Contains("End", StringComparison.OrdinalIgnoreCase)).GroupBy(x => x.Event).Select(x => new CodeLong() { code=x.Key, value= x.ToList().Count }).ToList()
  348. };
  349. await System.IO.File.WriteAllTextAsync($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord.id}-count.json", techCount.ToJsonString());
  350. await System.IO.File.WriteAllTextAsync($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-local.json", item.ToJsonString());
  351. }
  352. else
  353. {
  354. System.IO.File.Delete($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-local.json");
  355. System.IO.File.Delete($"{pathLessons}\\MM{yearMonthPath}\\{item.lessonRecord!.id}-count.json");
  356. }
  357. }
  358. }
  359. List<TechCount> techCounts = new List<TechCount>();
  360. filesLessons = FileHelper.ListAllFiles(pathLessons, "-local.json");
  361. await foreach (var item in LessonETLService.GetTeachCount(lessonRecords, filesLessons, pathLessons, ignore, Constant.objectiveTypes, _azureStorage, force))
  362. {
  363. techCounts.Add(item);
  364. }
  365. await LessonETLService.GenAnalysisData(pathAnalysis, newest, techCounts,_azureStorage);
  366. }
  367. return Ok(new { yearMonth });
  368. }
  369. }
  370. }