LessonService.cs 46 KB

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