LessonService.cs 49 KB

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