LessonService.cs 48 KB

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