LessonService.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. using Azure.Core;
  2. using Azure.Cosmos;
  3. using Azure.Messaging.ServiceBus;
  4. using DocumentFormat.OpenXml.Drawing.Charts;
  5. using DocumentFormat.OpenXml.VariantTypes;
  6. using HTEXLib.COMM.Helpers;
  7. using MathNet.Numerics.Distributions;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.Hosting;
  10. using OpenXmlPowerTools;
  11. using StackExchange.Redis;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Text.Json;
  17. using System.Threading.Tasks;
  18. using TEAMModelOS.SDK.DI;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
  21. using TEAMModelOS.SDK.Models.Cosmos.Common;
  22. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  23. using TEAMModelOS.SDK.Services;
  24. namespace TEAMModelOS.SDK.Models.Service
  25. {
  26. public class LessonService
  27. {
  28. public static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1).ToLocalTime();
  29. public static Dictionary<string, object> GetLessonCond(JsonElement request)
  30. {
  31. Dictionary<string, object> dict = new Dictionary<string, object>();
  32. if (request.TryGetProperty("tmdid", out JsonElement tmdid))
  33. {
  34. if (tmdid.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrWhiteSpace($"{tmdid}"))
  35. {
  36. dict.Add("tmdid", tmdid);
  37. }
  38. else if(tmdid.ValueKind.Equals(JsonValueKind.Array)) {
  39. dict.Add("tmdid", tmdid);
  40. }
  41. }
  42. if (request.TryGetProperty("courseId", out JsonElement courseId) && !string.IsNullOrWhiteSpace($"{courseId}"))
  43. {
  44. dict.Add("courseId", courseId);
  45. }
  46. if (request.TryGetProperty("courseIds", out JsonElement courseIds))
  47. {
  48. dict.Add("courseId[*]", courseIds);
  49. }
  50. if (request.TryGetProperty("periodId", out JsonElement periodId) && !string.IsNullOrWhiteSpace($"{periodId}"))
  51. {
  52. dict.Add("periodId", periodId);
  53. }
  54. if (request.TryGetProperty("subjectId", out JsonElement subjectId))
  55. {
  56. dict.Add("subjectId", subjectId);
  57. }
  58. if (request.TryGetProperty("groupIds", out JsonElement groupIds))
  59. {
  60. dict.Add("groupIds[*]", groupIds);
  61. }
  62. if (request.TryGetProperty("grade", out JsonElement grade))
  63. {
  64. dict.Add("grade[*]", grade);
  65. }
  66. if (request.TryGetProperty("category", out JsonElement category))
  67. {
  68. dict.Add("category[*]", category);
  69. }
  70. if (request.TryGetProperty("doubleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
  71. {
  72. dict.Add("=.tLevel", 2);
  73. dict.Add("=.pLevel", 2);
  74. //dict.Add(">=.tScore", 70);
  75. //dict.Add(">=.pScore", 70);
  76. }
  77. if (request.TryGetProperty("doubleRed", out JsonElement doubleRed) && doubleRed.GetBoolean())
  78. {
  79. dict.Add("=.tLevel", 0);
  80. dict.Add("=.pLevel", 0);
  81. //dict.Add(">=.tScore", 70);
  82. //dict.Add(">=.pScore", 70);
  83. }
  84. if (request.TryGetProperty("quality", out JsonElement quality) && quality.GetBoolean())
  85. {
  86. dict.Add(">=.discuss", 1);
  87. }
  88. if (request.TryGetProperty("excellent", out JsonElement excellent) && excellent.GetBoolean())
  89. {
  90. dict.Add(">=.excellent", 1);
  91. }
  92. if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
  93. {
  94. dict.Add("$.name", name);
  95. }
  96. if (request.TryGetProperty("today", out JsonElement today) && today.GetBoolean())
  97. {
  98. DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
  99. DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(1);
  100. double dayOf00_00_00 = (dateTimeA - dateTime1970).TotalMilliseconds;
  101. double day1Of00_00_00 = (dateTimeB - dateTime1970).TotalMilliseconds;
  102. dict.Add(">=.startTime", dayOf00_00_00);
  103. dict.Add("<.startTime", day1Of00_00_00);
  104. }
  105. if (request.TryGetProperty("week", out JsonElement week) && week.GetBoolean())
  106. {
  107. // DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
  108. DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(-7);
  109. double now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  110. double dayB = (dateTimeB - dateTime1970).TotalMilliseconds;
  111. dict.Add("<=.startTime", now);
  112. dict.Add(">=.startTime", dayB);
  113. }
  114. //查询即将到期的且没有被清理的。
  115. if (request.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
  116. {
  117. dict.Add(">.expire", 0);
  118. dict.Add("!=.status", 404);
  119. }
  120. //查询已经清理的
  121. if (request.TryGetProperty("is404", out JsonElement is404) && is404.ValueKind.Equals(JsonValueKind.True))
  122. {
  123. dict.Add("=.status", 404);
  124. }
  125. //只查有效的
  126. if (request.TryGetProperty("isOk", out JsonElement isOk) && isOk.ValueKind.Equals(JsonValueKind.True))
  127. {
  128. dict.Add("<=.expire", 0);
  129. dict.Add("!=.status", 404);
  130. }
  131. if (request.TryGetProperty("month", out JsonElement month) && month.GetBoolean())
  132. {
  133. //DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
  134. DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(-30);
  135. double now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  136. double dayB = (dateTimeB - dateTime1970).TotalMilliseconds;
  137. dict.Add("<=.startTime", now);
  138. dict.Add(">=.startTime", dayB);
  139. }
  140. if (request.TryGetProperty("stime", out JsonElement stime) && !string.IsNullOrWhiteSpace($"{stime}"))
  141. {
  142. dict.Add(">=.startTime", stime);
  143. }
  144. if (request.TryGetProperty("etime", out JsonElement etime) && !string.IsNullOrWhiteSpace($"{etime}"))
  145. {
  146. dict.Add("<=.startTime", etime);
  147. }
  148. if (request.TryGetProperty("conds", out JsonElement conds) && conds.ValueKind.Equals(JsonValueKind.Array))
  149. {
  150. List<LessonSettingCond> settingConds = conds.Deserialize<List<LessonSettingCond>>();
  151. foreach (var item in settingConds)
  152. {
  153. dict.TryAdd($"{item.type}.{item.key}", item.val);
  154. //switch (item.type)
  155. //{
  156. // case ">=":
  157. // dict.TryAdd($">=.{item.key}",item.val);
  158. // break;
  159. // case "<=":
  160. // dict.TryAdd($"<=.{item.key}", item.val);
  161. // break;
  162. //}
  163. }
  164. }
  165. return dict;
  166. }
  167. public static async void DoLessonStudentRecord(DingDing _dingding, SnowflakeId snowflakeId, LessonRecord lessonRecord, string scope, CosmosClient client, string school, string tmdid,
  168. Teacher teacher, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, IConfiguration _configuration, LessonBase lessonBase,AzureRedisFactory _azureRedis)
  169. {
  170. try
  171. {
  172. int year = DateTimeOffset.UtcNow.Year;
  173. string hs = lessonBase?.report?.clientSummaryList.ToJsonString();
  174. var clientSummaryList = lessonBase?.report?.clientSummaryList?.Where(x => x.groupTaskCompleteCount != 0 || x.groupScore != 0 || x.score != 0 || x.tnteractScore != 0 || x.taskCompleteCount != 0);
  175. IEnumerable<LessonStudent> students = new List<LessonStudent>();
  176. if (clientSummaryList.Any())
  177. {
  178. var ids = clientSummaryList.Select(x => x.seatID);
  179. students = lessonBase.student.Where(x => ids.Contains(x.seatID));
  180. }
  181. List<Student> studentsBase = new List<Student>();
  182. var stuids = students.Where(x => x.type == 2);
  183. if (stuids.Any())
  184. {
  185. stuids.ToList().ForEach(x => {
  186. x.school = string.IsNullOrWhiteSpace(x.school) ? school : x.school;
  187. });
  188. var result= await client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>($"select value c from c where c.id in ({string.Join(",",stuids.Select(d=>$"'{d.id}'"))})", $"Base-{school}");
  189. if (result.list.Any()) {
  190. studentsBase = result.list;
  191. }
  192. }
  193. var groups = stuids.Where(z => !string.IsNullOrWhiteSpace(z.school)).GroupBy(x => x.school).Select(y => new { code = y.Key, list = y.ToList() });
  194. List<StudentScoreRecord> lessonStudentRecords = new List<StudentScoreRecord>();
  195. foreach (var group in groups)
  196. {
  197. string stusql = $"select value(c) from c where c.stuid in({string.Join(",", group.list.Select(x => $"'{x.id}'"))}) and c.school='{group.code}' and c.year={year}";
  198. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentScoreRecord>(queryText: stusql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StudentScoreRecord") }))
  199. {
  200. lessonStudentRecords.Add(item);
  201. }
  202. }
  203. var tmdids = students.Where(x => x.type == 1);
  204. if (tmdids.Any())
  205. {
  206. string tmdsql = $"select value(c) from c where c.tmdid in({string.Join(",", tmdids.Select(x => $"'{x}'"))}) and c.year={year}";
  207. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentScoreRecord>(queryText: tmdsql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StudentScoreRecord") }))
  208. {
  209. lessonStudentRecords.Add(item);
  210. }
  211. }
  212. School schoolBase = null;
  213. Period period = null;
  214. (Semester currSemester, int studyYear, DateTimeOffset date, DateTimeOffset nextSemester) dataSemester = new(null,-1, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) ;
  215. if (!string.IsNullOrWhiteSpace(school)) {
  216. schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  217. period = schoolBase.period.Find(x => x.id.Equals($"{lessonRecord.periodId}"));
  218. dataSemester= SchoolService.GetSemester(period);
  219. }
  220. List <Task<ItemResponse<StudentScoreRecord>>> records = new List<Task<ItemResponse<StudentScoreRecord>>>();
  221. HashSet <OverallEducation> overallEducations = new HashSet<OverallEducation>();
  222. stuids.ToList().ForEach(async x => {
  223. var record = lessonStudentRecords.Find(l => l.stuid.Equals(x.id) && l.code.Equals($"StudentScoreRecord") && l.school.Equals(x.school));
  224. ClientSummaryList clientSummaryList = lessonBase.report.clientSummaryList.Find(c => c.seatID == x.seatID);
  225. if (record != null)
  226. {
  227. if (clientSummaryList != null)
  228. {
  229. var hasrecord= record.lessonRecords.Find(x => x.lessonId.Equals(lessonRecord.id));
  230. if (hasrecord != null)
  231. {
  232. hasrecord.gscore = clientSummaryList.groupScore;
  233. hasrecord.pscore = clientSummaryList.score;
  234. hasrecord.tscore = clientSummaryList.tnteractScore;
  235. hasrecord.tmdid = teacher.id;
  236. hasrecord.school = school;
  237. hasrecord.scope = lessonRecord.scope;
  238. hasrecord.lessonId = lessonRecord.id;
  239. hasrecord.courseId = lessonRecord.courseId;
  240. hasrecord.periodId = lessonRecord.periodId;
  241. hasrecord.subjectId = lessonRecord.subjectId;
  242. hasrecord.time = lessonRecord.startTime;
  243. }
  244. else {
  245. record.lessonRecords.Add(
  246. new StudentLessonRecord
  247. {
  248. gscore = clientSummaryList.groupScore,
  249. pscore = clientSummaryList.score,
  250. tscore = clientSummaryList.tnteractScore,
  251. tmdid = teacher.id,
  252. school = school,
  253. scope = lessonRecord.scope,
  254. lessonId = lessonRecord.id,
  255. courseId = lessonRecord.courseId,
  256. periodId = lessonRecord.periodId,
  257. subjectId = lessonRecord.subjectId,
  258. time = lessonRecord.startTime
  259. }
  260. );
  261. }
  262. }
  263. }
  264. else
  265. {
  266. record = new StudentScoreRecord
  267. {
  268. userType = Constant.ScopeStudent,
  269. id = $"{snowflakeId.NextId()}",
  270. year = year,
  271. stuid = x.id,
  272. school = x.school,
  273. code = $"StudentScoreRecord",
  274. pk = "StudentScoreRecord",
  275. ttl = -1,
  276. lessonRecords = new List<StudentLessonRecord> { new StudentLessonRecord
  277. {
  278. gscore = clientSummaryList.groupScore,
  279. pscore = clientSummaryList.score,
  280. tscore = clientSummaryList.tnteractScore,
  281. tmdid = teacher.id,
  282. school = school,
  283. scope = lessonRecord.scope,
  284. lessonId = lessonRecord.id,
  285. courseId = lessonRecord.courseId,
  286. periodId = lessonRecord.periodId,
  287. subjectId = lessonRecord.subjectId,
  288. time= lessonRecord.startTime
  289. }}
  290. };
  291. }
  292. record.userType = Constant.ScopeStudent;
  293. record.gscore = record.lessonRecords.Select(x => x.gscore).Sum();
  294. record.pscore = record.lessonRecords.Select(x => x.pscore).Sum();
  295. record.tscore = record.lessonRecords.Select(x => x.tscore).Sum();
  296. if (dataSemester.currSemester != null && (clientSummaryList.groupScore>0 || clientSummaryList.score > 0 || clientSummaryList.tnteractScore > 0)) {
  297. string oid = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{record.stuid}";
  298. string ocode = $"OverallEducation-{school}";
  299. var student= studentsBase.Find(stu => stu.id.Equals(x.id));
  300. Azure.Response response = await client.GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemStreamAsync(oid, new PartitionKey(ocode));
  301. OverallEducation overallEducation = null;
  302. if (response.Status != 200) {
  303. overallEducation = new OverallEducation
  304. {
  305. id =oid,
  306. code = $"OverallEducation-{school}",
  307. pk = "OverallEducation",
  308. ttl = -1,
  309. name = x.name,
  310. classId = student?.classId,
  311. schoolCode = $"{school}",
  312. semesterId = dataSemester.currSemester.id,
  313. year = dataSemester.studyYear,
  314. periodId = $"{period.id}",
  315. stuYear = student.year,
  316. studentId = x.id,
  317. lessonScore= new List<StudentLessonRecord> { new StudentLessonRecord
  318. {
  319. gscore = clientSummaryList.groupScore,
  320. pscore = clientSummaryList.score,
  321. tscore = clientSummaryList.tnteractScore,
  322. tmdid = teacher.id,
  323. school = school,
  324. scope = lessonRecord.scope,
  325. lessonId = lessonRecord.id,
  326. courseId = lessonRecord.courseId,
  327. periodId = lessonRecord.periodId,
  328. subjectId = lessonRecord.subjectId,
  329. time= lessonRecord.startTime
  330. }}
  331. };
  332. }
  333. else {
  334. overallEducation=JsonDocument.Parse(response.Content).RootElement.ToObject<OverallEducation>();
  335. var hasrecord = overallEducation.lessonScore.Find(x => x.lessonId.Equals(lessonRecord.id));
  336. if (hasrecord != null)
  337. {
  338. hasrecord.gscore = clientSummaryList.groupScore;
  339. hasrecord.pscore = clientSummaryList.score;
  340. hasrecord.tscore = clientSummaryList.tnteractScore;
  341. hasrecord.tmdid = teacher.id;
  342. hasrecord.school = school;
  343. hasrecord.scope = lessonRecord.scope;
  344. hasrecord.lessonId = lessonRecord.id;
  345. hasrecord.courseId = lessonRecord.courseId;
  346. hasrecord.periodId = lessonRecord.periodId;
  347. hasrecord.subjectId = lessonRecord.subjectId;
  348. hasrecord.time = lessonRecord.startTime;
  349. }
  350. else
  351. {
  352. overallEducation.lessonScore.Add(
  353. new StudentLessonRecord
  354. {
  355. gscore = clientSummaryList.groupScore,
  356. pscore = clientSummaryList.score,
  357. tscore = clientSummaryList.tnteractScore,
  358. tmdid = teacher.id,
  359. school = school,
  360. scope = lessonRecord.scope,
  361. lessonId = lessonRecord.id,
  362. courseId = lessonRecord.courseId,
  363. periodId = lessonRecord.periodId,
  364. subjectId = lessonRecord.subjectId,
  365. time = lessonRecord.startTime
  366. }
  367. );
  368. }
  369. }
  370. overallEducations.Add(overallEducation);
  371. }
  372. records.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(record, partitionKey: new PartitionKey(record.code)));
  373. });
  374. tmdids.ToList().ForEach(x => {
  375. var record = lessonStudentRecords.Find(l => l.tmdid.Equals(x.id) && l.code.Equals($"StudentScoreRecord"));
  376. ClientSummaryList clientSummaryList = lessonBase.report.clientSummaryList.Find(c => c.seatID == x.seatID);
  377. if (record != null)
  378. {
  379. if (clientSummaryList != null)
  380. {
  381. var hasrecord = record.lessonRecords.Find(x => x.lessonId.Equals(lessonRecord.id));
  382. if (hasrecord != null)
  383. {
  384. hasrecord.gscore = clientSummaryList.groupScore;
  385. hasrecord.pscore = clientSummaryList.score;
  386. hasrecord.tscore = clientSummaryList.tnteractScore;
  387. hasrecord.tmdid = teacher.id;
  388. hasrecord.school = school;
  389. hasrecord.scope = lessonRecord.scope;
  390. hasrecord.lessonId = lessonRecord.id;
  391. hasrecord.courseId = lessonRecord.courseId;
  392. hasrecord.periodId = lessonRecord.periodId;
  393. hasrecord.subjectId = lessonRecord.subjectId;
  394. hasrecord.time = lessonRecord.startTime;
  395. }
  396. else
  397. {
  398. record.lessonRecords.Add(
  399. new StudentLessonRecord
  400. {
  401. gscore = clientSummaryList.groupScore,
  402. pscore = clientSummaryList.score,
  403. tscore = clientSummaryList.tnteractScore,
  404. tmdid = teacher.id,
  405. school = school,
  406. scope = lessonRecord.scope,
  407. lessonId = lessonRecord.id,
  408. courseId = lessonRecord.courseId,
  409. periodId = lessonRecord.periodId,
  410. subjectId = lessonRecord.subjectId,
  411. time = lessonRecord.startTime
  412. }
  413. );
  414. }
  415. }
  416. }
  417. else
  418. {
  419. record = new StudentScoreRecord
  420. {
  421. userType = Constant.ScopeTmdUser,
  422. id = $"{snowflakeId.NextId()}",
  423. code = $"StudentScoreRecord",
  424. pk = "StudentScoreRecord",
  425. ttl = -1,
  426. year = year,
  427. tmdid = x.id,
  428. lessonRecords = new List<StudentLessonRecord>
  429. {
  430. new StudentLessonRecord
  431. {
  432. gscore = clientSummaryList.groupScore,
  433. pscore = clientSummaryList.score,
  434. tscore = clientSummaryList.tnteractScore,
  435. tmdid = teacher.id,
  436. school = school,
  437. scope = lessonRecord.scope,
  438. lessonId = lessonRecord.id,
  439. courseId = lessonRecord.courseId,
  440. periodId = lessonRecord.periodId,
  441. subjectId = lessonRecord.subjectId,
  442. time=lessonRecord.startTime
  443. }
  444. }
  445. };
  446. }
  447. record.userType = Constant.ScopeStudent;
  448. record.gscore = record.lessonRecords.Select(x => x.gscore).Sum();
  449. record.pscore = record.lessonRecords.Select(x => x.pscore).Sum();
  450. record.tscore = record.lessonRecords.Select(x => x.tscore).Sum();
  451. records.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(record, partitionKey: new PartitionKey(record.code)));
  452. });
  453. if (records.Any())
  454. {
  455. await Task.WhenAll(records);
  456. }
  457. if (overallEducations.Any())
  458. {
  459. foreach (var item in overallEducations) {
  460. await client.GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(item, partitionKey: new PartitionKey(item.code));
  461. string key = $"OverallEducation:{item.schoolCode}:{item.periodId}:{item.year}:{item.semesterId}:{item.classId}";
  462. await _azureRedis.GetRedisClient(8).HashSetAsync(key, item.studentId, item.ToJsonString());
  463. await _azureRedis.GetRedisClient(8).KeyExpireAsync(key,new TimeSpan(180 *24 ,0,0));
  464. }
  465. }
  466. }
  467. catch (Exception ex)
  468. {
  469. await _dingding.SendBotMsg($"学生个人课例统计信息异常,{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  470. }
  471. }
  472. public static async void DoAutoDeleteSchoolLessonRecord(LessonRecord lessonRecord, string scope, CosmosClient client, string school, string tmdid,
  473. Teacher teacher, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, IConfiguration _configuration, CoreAPIHttpService _coreAPIHttpService,DingDing _dingDing,AzureRedisFactory _azureRedis)
  474. {
  475. if (lessonRecord.scope.Equals("school"))
  476. {
  477. SchoolSetting setting = null;
  478. Azure.Response schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
  479. School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
  480. if (schoolSetting.Status == 200)
  481. {
  482. setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
  483. if (setting.lessonSetting != null)
  484. {
  485. //两种状态都不属于,则默认未开启。
  486. if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
  487. {
  488. setting.lessonSetting.openAutoClean = 0;
  489. setting.lessonSetting.expireDays = Constant.school_lesson_expire;
  490. }
  491. else {
  492. //属于 要么开启1,要么关闭0
  493. }
  494. }
  495. else
  496. {
  497. setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
  498. }
  499. }
  500. else
  501. {
  502. setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
  503. }
  504. int school_lesson_expire = 0;
  505. bool save = true;
  506. List<string> msg = new List<string>();
  507. if (setting.lessonSetting.openAutoClean == 1)
  508. {
  509. if (setting.lessonSetting.conds.IsEmpty())
  510. {
  511. save = false;
  512. }
  513. else
  514. {
  515. school_lesson_expire = setting.lessonSetting.expireDays;
  516. foreach (var item in setting.lessonSetting.conds)
  517. {
  518. switch (item.type)
  519. {
  520. case ">=":
  521. switch (item.key)
  522. {
  523. case "attendRate":
  524. if (!(lessonRecord.attendRate >= item.val))
  525. {
  526. save = false;
  527. msg.Add($"{item.key}:{lessonRecord.attendRate}{item.type}{item.val}");
  528. }
  529. break;
  530. case "groupCount":
  531. if (!(lessonRecord.groupCount >= item.val))
  532. {
  533. save = false;
  534. msg.Add($"{item.key}:{lessonRecord.groupCount}{item.type}{item.val}");
  535. }
  536. break;
  537. case "totalPoint":
  538. if (!(lessonRecord.totalPoint >= item.val))
  539. {
  540. save = false;
  541. msg.Add($"{item.key}:{lessonRecord.totalPoint}{item.type}{item.val}");
  542. }
  543. break;
  544. case "collateTaskCount":
  545. if (!(lessonRecord.collateTaskCount >= item.val))
  546. {
  547. save = false;
  548. msg.Add($"{item.key}:{lessonRecord.collateTaskCount}{item.type}{item.val}");
  549. }
  550. break;
  551. case "collateCount":
  552. if (!(lessonRecord.collateCount >= item.val))
  553. {
  554. save = false;
  555. msg.Add($"{item.key}:{lessonRecord.collateCount}{item.type}{item.val}");
  556. }
  557. break;
  558. case "pushCount":
  559. if (!(lessonRecord.pushCount >= item.val))
  560. {
  561. save = false;
  562. msg.Add($"{item.key}:{lessonRecord.pushCount}{item.type}{item.val}");
  563. }
  564. break;
  565. case "totalInteractPoint":
  566. if (!(lessonRecord.totalInteractPoint >= item.val))
  567. {
  568. save = false;
  569. msg.Add($"{item.key}:{lessonRecord.totalInteractPoint}{item.type}{item.val}");
  570. }
  571. break;
  572. case "interactionCount":
  573. if (!(lessonRecord.interactionCount >= item.val))
  574. {
  575. save = false;
  576. msg.Add($"{item.key}:{lessonRecord.interactionCount}{item.type}{item.val}");
  577. }
  578. break;
  579. case "clientInteractionCount":
  580. if (!(lessonRecord.clientInteractionCount >= item.val))
  581. {
  582. save = false;
  583. msg.Add($"{item.key}:{lessonRecord.clientInteractionCount}{item.type}{item.val}");
  584. }
  585. break;
  586. case "examQuizCount":
  587. if (!(lessonRecord.examQuizCount >= item.val))
  588. {
  589. save = false;
  590. msg.Add($"{item.key}:{lessonRecord.examQuizCount}{item.type}{item.val}");
  591. }
  592. break;
  593. case "examPointRate":
  594. if (!(lessonRecord.examPointRate >= item.val))
  595. {
  596. save = false;
  597. msg.Add($"{item.key}:{lessonRecord.examPointRate}{item.type}{item.val}");
  598. }
  599. break;
  600. }
  601. break;
  602. case "<=":
  603. switch (item.key)
  604. {
  605. case "attendRate":
  606. if (!(lessonRecord.attendRate <= item.val))
  607. {
  608. save = false;
  609. msg.Add($"{item.key}:{lessonRecord.attendRate}{item.type}{item.val}");
  610. }
  611. break;
  612. case "groupCount":
  613. if (!(lessonRecord.groupCount <= item.val))
  614. {
  615. save = false;
  616. msg.Add($"{item.key}:{lessonRecord.groupCount}{item.type}{item.val}");
  617. }
  618. break;
  619. case "totalPoint":
  620. if (!(lessonRecord.totalPoint <= item.val))
  621. {
  622. save = false;
  623. msg.Add($"{item.key}:{lessonRecord.totalPoint}{item.type}{item.val}");
  624. }
  625. break;
  626. case "collateTaskCount":
  627. if (!(lessonRecord.collateTaskCount <= item.val))
  628. {
  629. save = false;
  630. msg.Add($"{item.key}:{lessonRecord.collateTaskCount}{item.type}{item.val}");
  631. }
  632. break;
  633. case "collateCount":
  634. if (!(lessonRecord.collateCount <= item.val))
  635. {
  636. save = false;
  637. msg.Add($"{item.key}:{lessonRecord.collateCount}{item.type}{item.val}");
  638. }
  639. break;
  640. case "pushCount":
  641. if (!(lessonRecord.pushCount <= item.val))
  642. {
  643. save = false;
  644. msg.Add($"{item.key}:{lessonRecord.pushCount}{item.type}{item.val}");
  645. }
  646. break;
  647. case "totalInteractPoint":
  648. if (!(lessonRecord.totalInteractPoint <= item.val))
  649. {
  650. save = false;
  651. msg.Add($"{item.key}:{lessonRecord.totalInteractPoint}{item.type}{item.val}");
  652. }
  653. break;
  654. case "interactionCount":
  655. if (!(lessonRecord.interactionCount <= item.val))
  656. {
  657. save = false;
  658. msg.Add($"{item.key}:{lessonRecord.interactionCount}{item.type}{item.val}");
  659. }
  660. break;
  661. case "clientInteractionCount":
  662. if (!(lessonRecord.clientInteractionCount <= item.val))
  663. {
  664. save = false;
  665. msg.Add($"{item.key}:{lessonRecord.clientInteractionCount}{item.type}{item.val}");
  666. }
  667. break;
  668. case "examQuizCount":
  669. if (!(lessonRecord.examQuizCount <= item.val))
  670. {
  671. save = false;
  672. msg.Add($"{item.key}:{lessonRecord.examQuizCount}{item.type}{item.val}");
  673. }
  674. break;
  675. case "examPointRate":
  676. if (!(lessonRecord.examPointRate <= item.val))
  677. {
  678. save = false;
  679. msg.Add($"{item.key}:{lessonRecord.examPointRate}{item.type}{item.val}");
  680. }
  681. break;
  682. }
  683. break;
  684. }
  685. }
  686. }
  687. }
  688. /* 注释start 2023.3.22,该段逻辑在开课的时候已经处理,详见ActiveTaskTopic. LessonRecordEvent create ,无论有没有开启setting.lessonSetting.openAutoClean 自动删除策略,只要空间不足都会对课例进行自动清理管理。
  689. else
  690. {
  691. ///未设置openAutoClean=1时,则检查学校使用空间是否充足。
  692. double usize = 0;
  693. int tsize = schoolBase.tsize;
  694. //schoolBase.tsize
  695. //計算學校或個人的使用空間
  696. RedisValue redisValue = _azureRedis.GetRedisClient(8).HashGet($"Blob:Record", $"{schoolBase.id}");
  697. if (redisValue.HasValue && long.TryParse(redisValue.ToString(), out var bsize))
  698. {
  699. usize = Math.Round(bsize / 1073741824.0 - (tsize), 2, MidpointRounding.AwayFromZero); //1073741824 1G
  700. }
  701. else //如果檢測不到緩存,觸發刷新計算空間
  702. {
  703. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{schoolBase.id}" }, _serviceBus, _configuration, _azureRedis);
  704. }
  705. ///空间充足的情况保存。
  706. if (schoolBase.size - usize > 0)
  707. {
  708. save = true;
  709. }
  710. else {
  711. save = false;
  712. school_lesson_expire = Constant.school_lesson_expire;
  713. }
  714. } 注释end 2023.3.22,该段逻辑在开课的时候已经处理,详见ActiveTaskTopic. LessonRecordEvent create ,无论有没有开启setting.lessonSetting.openAutoClean 自动删除策略,只要空间不足都会对课例进行自动清理管理。
  715. */
  716. if (!save && school_lesson_expire > 0)
  717. {
  718. // 1-时间戳,7-时间戳
  719. Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
  720. //暂定7天
  721. var now = DateTimeOffset.UtcNow;
  722. //剩余3天的通知
  723. //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
  724. //result.Add(3, day3);
  725. //剩余1天的通知
  726. var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
  727. result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
  728. //到期通知
  729. //不到五点上传的课例,七天之后直接删除。
  730. int addSecond = 0;
  731. if (now.Hour > 5)
  732. {
  733. // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
  734. addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
  735. //再加 00到05小时内的 随机秒数
  736. Random rand = new Random();
  737. int randInt = rand.Next(0, 18000);
  738. addSecond += randInt;
  739. }
  740. else
  741. {
  742. addSecond = school_lesson_expire * 24 * 60 * 60;
  743. }
  744. lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
  745. result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
  746. // result.Add(school_lesson_expire, lessonRecord.expire);
  747. string biz = "expire";
  748. string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
  749. Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
  750. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-school_lessonRecord", Constant.NotifyType_IES5_Course,
  751. new Dictionary<string, object> { { "tmdid", teacher.id }, { "tmdname", teacher.name }, { "schoolName", schoolBase.name },
  752. { "schoolId", $"{school}" },{ "lessonId",lessonRecord.id }, { "expireTime", expireTime },{ "lessonName",lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
  753. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  754. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  755. if (records.Count <= 0)
  756. {
  757. foreach (var item in result)
  758. {
  759. string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
  760. //课堂的id ,
  761. //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
  762. var message = new ServiceBusMessage(new
  763. {
  764. id = lessonRecord.id,
  765. progress = item.Key,
  766. code = lessonRecord.code,
  767. scope = lessonRecord.scope,
  768. school = lessonRecord.school,
  769. opt = "delete",
  770. expire = lessonRecord.expire,
  771. tmdid = tmdid,
  772. tmdname = teacher.name,
  773. name = lessonRecord.name,
  774. startTime = lessonRecord.startTime,
  775. tag = item.Value.tag
  776. }.ToJsonString());
  777. message.ApplicationProperties.Add("name", "LessonRecordExpire");
  778. long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
  779. ChangeRecord changeRecord = new ChangeRecord
  780. {
  781. RowKey = lessonRecord.id,
  782. PartitionKey = PartitionKey,
  783. sequenceNumber = start,
  784. msgId = message.MessageId
  785. };
  786. await table.Save<ChangeRecord>(changeRecord);
  787. }
  788. }
  789. }
  790. else
  791. {
  792. if (lessonRecord.expire > 0)
  793. {
  794. var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
  795. List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
  796. foreach (var record in records)
  797. {
  798. try
  799. {
  800. await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
  801. await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
  802. }
  803. catch (Exception)
  804. {
  805. continue;
  806. }
  807. }
  808. }
  809. lessonRecord.save = 1;
  810. lessonRecord.expire = -1;
  811. }
  812. }
  813. }
  814. public record ExpireTag
  815. {
  816. public long expire { get; set; }
  817. public string tag { get; set; }
  818. }
  819. /// <summary>
  820. ///
  821. /// </summary>
  822. /// <param name="client"></param>
  823. /// <param name="_dingDing"></param>
  824. /// <param name="data"></param>
  825. /// <returns></returns>
  826. public static LessonDis DisLessonCount(LessonRecord oldRecord, LessonRecord newRecord, LessonDis lessonDis)
  827. {
  828. //创建课堂的情况
  829. if (oldRecord == null && newRecord != null)
  830. {
  831. lessonDis.record = 1;
  832. }
  833. //删除数据的情况
  834. //不再对LessonCount进行减
  835. else if (oldRecord != null && newRecord == null)
  836. {
  837. /*lessonDis.record = -1;
  838. //P分数量加减
  839. if (oldRecord.pScore >= 70)
  840. {
  841. lessonDis.disPCount = -1;
  842. }
  843. //T分数量加减
  844. if (oldRecord.tScore >= 70)
  845. {
  846. lessonDis.disTCount = -1;
  847. }
  848. if (oldRecord.tScore >= 70 && oldRecord.pScore >= 70)
  849. {
  850. lessonDis.disTCount = -1;
  851. }*/
  852. }
  853. //无效操作
  854. else if (oldRecord == null && newRecord == null)
  855. {
  856. }
  857. //前后操作都有值,则表示更新
  858. else
  859. {
  860. //P分数量加减
  861. if (oldRecord.pScore >= 70)
  862. {
  863. if (newRecord.pScore < 70)
  864. {
  865. lessonDis.disPCount = -1;
  866. }
  867. }
  868. else
  869. {
  870. if (newRecord.pScore >= 70)
  871. {
  872. lessonDis.disPCount = 1;
  873. }
  874. }
  875. //T分数量加减
  876. if (oldRecord.tScore >= 70)
  877. {
  878. if (newRecord.tScore < 70)
  879. {
  880. lessonDis.disTCount = -1;
  881. }
  882. }
  883. else
  884. {
  885. if (newRecord.tScore >= 70)
  886. {
  887. lessonDis.disTCount = 1;
  888. }
  889. }
  890. //双绿灯数量
  891. if (oldRecord.tScore >= 70 && oldRecord.pScore >= 70)
  892. {
  893. if (newRecord.tScore < 70 || newRecord.pScore < 70)
  894. {
  895. lessonDis.disDCount = -1;
  896. }
  897. }
  898. else
  899. {
  900. if (newRecord.tScore >= 70 && newRecord.pScore >= 70)
  901. {
  902. lessonDis.disDCount = 1;
  903. }
  904. }
  905. }
  906. return lessonDis;
  907. }
  908. public static LessonDis DisLessonCount_2(LessonRecord oldRecord, LessonRecord newRecord, LessonDis lessonDis)
  909. {
  910. //创建课堂的情况
  911. if (oldRecord == null && newRecord != null)
  912. {
  913. lessonDis.record = 1;
  914. //P分数量加减
  915. if (newRecord.pScore >= 70)
  916. {
  917. lessonDis.disPCount = 1;
  918. }
  919. //T分数量加减
  920. if (newRecord.tScore >= 70)
  921. {
  922. lessonDis.disTCount = 1;
  923. }
  924. //双绿灯数量
  925. if (newRecord.tScore >= 70 && newRecord.pScore >= 70)
  926. {
  927. lessonDis.disDCount = 1;
  928. }
  929. }
  930. return lessonDis;
  931. }
  932. public static async Task FixLessonCount(CosmosClient client, DingDing _dingDing, LessonRecord record, LessonRecord oldRecord, LessonDis lessonDis)
  933. {
  934. LessonRecord data = null;
  935. try
  936. {
  937. if (record != null && oldRecord == null)
  938. {
  939. data = record;
  940. }
  941. if (record == null && oldRecord != null)
  942. {
  943. data = oldRecord;
  944. }
  945. if (record != null && oldRecord != null)
  946. {
  947. data = record;
  948. }
  949. int day = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).DayOfYear;
  950. int year = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).Year;
  951. int days = DateTimeHelper.getDays(year);
  952. //int years = DateTimeOffset.UtcNow.DayOfYear;
  953. string tbname = string.Empty;
  954. string code = string.Empty;
  955. if (data.groupIds.Any()) {
  956. if (data.scope != null && data.scope.Equals("school"))
  957. {
  958. if (string.IsNullOrEmpty(data.periodId))
  959. {
  960. code = $"LessonCount-{data.school}-{year}";
  961. tbname = "School";
  962. }
  963. else
  964. {
  965. code = $"LessonCount-{data.school}-{year}-{data.periodId}";
  966. tbname = "School";
  967. }
  968. }
  969. else
  970. {
  971. code = $"LessonCount-{year}";
  972. tbname = "Teacher";
  973. }
  974. var response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(data.tmdid.ToString(), new PartitionKey(code));
  975. if (response.Status == 200)
  976. {
  977. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  978. LessonCount count = json.ToObject<LessonCount>();
  979. count.tCount[day - 1] += lessonDis.disTCount;
  980. count.pCount[day - 1] += lessonDis.disPCount;
  981. count.ptCount[day - 1] += lessonDis.disDCount;
  982. count.beginCount[day - 1] += lessonDis.record;
  983. await client.GetContainer("TEAMModelOS", tbname).ReplaceItemAsync(count, count.id, new PartitionKey(code));
  984. }
  985. else
  986. {
  987. LessonCount count = new()
  988. {
  989. id = data.tmdid,
  990. code = code,
  991. ttl = -1
  992. };
  993. double[] da = new double[days];
  994. List<double> list = new(da);
  995. List<double> listT = new(da);
  996. List<double> listP = new(da);
  997. List<double> listPT = new(da);
  998. list[day - 1] += lessonDis.record;
  999. listT[day - 1] += lessonDis.disTCount;
  1000. listP[day - 1] += lessonDis.disPCount;
  1001. listPT[day - 1] += lessonDis.disDCount;
  1002. count.beginCount.AddRange(list);
  1003. count.tCount.AddRange(listT);
  1004. count.pCount.AddRange(listP);
  1005. count.ptCount.AddRange(listPT);
  1006. //count.courseIds.Add(data.courseId);
  1007. await client.GetContainer("TEAMModelOS", tbname).CreateItemAsync(count, new PartitionKey(code));
  1008. }
  1009. }
  1010. }
  1011. catch (Exception ex)
  1012. {
  1013. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-LessonCount-FixLessonCount\n{ex.Message}\n{ex.StackTrace}{data.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1014. }
  1015. }
  1016. }
  1017. }