LessonRecordController.cs 25 KB

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