123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912 |
- using Azure.Cosmos;
- using Azure.Messaging.ServiceBus;
- using HTEXLib.COMM.Helpers;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- namespace TEAMModelOS.SDK.Models.Service
- {
- public class LessonService
- {
- public static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1).ToLocalTime();
- public static Dictionary<string, object> GetLessonCond(JsonElement request)
- {
- Dictionary<string, object> dict = new Dictionary<string, object>();
- if (request.TryGetProperty("tmdid", out JsonElement tmdid) && !string.IsNullOrWhiteSpace($"{tmdid}"))
- {
- dict.Add("tmdid", tmdid);
- }
- if (request.TryGetProperty("courseId", out JsonElement courseId) && !string.IsNullOrWhiteSpace($"{courseId}"))
- {
- dict.Add("courseId", courseId);
- }
- if (request.TryGetProperty("courseIds", out JsonElement courseIds))
- {
- dict.Add("courseId[*]", courseIds);
- }
- if (request.TryGetProperty("periodId", out JsonElement periodId) && !string.IsNullOrWhiteSpace($"{periodId}"))
- {
- dict.Add("periodId", periodId);
- }
- if (request.TryGetProperty("subjectId", out JsonElement subjectId))
- {
- dict.Add("subjectId", subjectId);
- }
- if (request.TryGetProperty("groupIds", out JsonElement groupIds))
- {
- dict.Add("groupIds[*]", groupIds);
- }
- if (request.TryGetProperty("grade", out JsonElement grade))
- {
- dict.Add("grade[*]", grade);
- }
- if (request.TryGetProperty("category", out JsonElement category))
- {
- dict.Add("category[*]", category);
- }
- if (request.TryGetProperty("doubleGreen", out JsonElement doubleGreen) && doubleGreen.GetBoolean())
- {
- dict.Add(">=.tScore", 70);
- dict.Add(">=.pScore", 70);
- }
- if (request.TryGetProperty("quality", out JsonElement quality) && quality.GetBoolean())
- {
- dict.Add(">=.discuss", 1);
- }
- if (request.TryGetProperty("excellent", out JsonElement excellent) && excellent.GetBoolean())
- {
- dict.Add(">=.excellent", 1);
- }
- if (request.TryGetProperty("name", out JsonElement name) && !string.IsNullOrWhiteSpace($"{name}"))
- {
- dict.Add("$.name", name);
- }
- if (request.TryGetProperty("today", out JsonElement today) && today.GetBoolean())
- {
- DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
- DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(1);
- double dayOf00_00_00 = (dateTimeA - dateTime1970).TotalMilliseconds;
- double day1Of00_00_00 = (dateTimeB - dateTime1970).TotalMilliseconds;
- dict.Add(">=.startTime", dayOf00_00_00);
- dict.Add("<.startTime", day1Of00_00_00);
- }
- if (request.TryGetProperty("week", out JsonElement week) && week.GetBoolean())
- {
- // DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
- DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(-7);
- double now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- double dayB = (dateTimeB - dateTime1970).TotalMilliseconds;
- dict.Add("<=.startTime", now);
- dict.Add(">=.startTime", dayB);
- }
- if (request.TryGetProperty("expire", out JsonElement expire) && expire.ValueKind.Equals(JsonValueKind.True))
- {
- dict.Add(">.expire", 0);
- }
- if (request.TryGetProperty("is404", out JsonElement is404) && is404.ValueKind.Equals(JsonValueKind.True))
- {
- dict.Add("=.status", 404);
- }
- if (request.TryGetProperty("month", out JsonElement month) && month.GetBoolean())
- {
- //DateTime dateTimeA = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D"));
- DateTime dateTimeB = Convert.ToDateTime(DateTimeOffset.UtcNow.ToString("D")).AddDays(-30);
- double now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- double dayB = (dateTimeB - dateTime1970).TotalMilliseconds;
- dict.Add("<=.startTime", now);
- dict.Add(">=.startTime", dayB);
- }
- if (request.TryGetProperty("stime", out JsonElement stime) && !string.IsNullOrWhiteSpace($"{stime}"))
- {
- dict.Add(">=.startTime", stime);
- }
- if (request.TryGetProperty("etime", out JsonElement etime) && !string.IsNullOrWhiteSpace($"{etime}"))
- {
- dict.Add("<=.startTime", etime);
- }
- if (request.TryGetProperty("conds", out JsonElement conds) && conds.ValueKind.Equals(JsonValueKind.Array))
- {
- List<LessonSettingCond> settingConds = conds.Deserialize<List<LessonSettingCond>>();
- foreach (var item in settingConds)
- {
- dict.TryAdd($"{item.type}.{item.key}", item.val);
- //switch (item.type)
- //{
- // case ">=":
- // dict.TryAdd($">=.{item.key}",item.val);
- // break;
- // case "<=":
- // dict.TryAdd($"<=.{item.key}", item.val);
- // break;
- //}
- }
- }
- return dict;
- }
- public static async void DoLessonStudentRecord(DingDing _dingding, SnowflakeId snowflakeId, LessonRecord lessonRecord, string scope, CosmosClient client, string school, string tmdid,
- Teacher teacher, NotificationService _notificationService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, IConfiguration _configuration, LessonBase lessonBase)
- {
- try
- {
- int year = DateTimeOffset.UtcNow.Year;
- var clientSummaryList = lessonBase.report.clientSummaryList.Where(x => x.groupTaskCompleteCount != 0 || x.groupScore != 0 || x.score != 0 || x.tnteractScore != 0 || x.taskCompleteCount != 0);
- IEnumerable<LessonStudent> students = new List<LessonStudent>();
- if (clientSummaryList.Any())
- {
- students = lessonBase.student.Where(x => clientSummaryList.Select(x => x.seatID).Contains(x.seatID));
- }
- var stuids = students.Where(x => x.type == 2);
- if (stuids.Any())
- {
- stuids.ToList().ForEach(x => {
- x.school = string.IsNullOrWhiteSpace(x.school) ? school : x.school;
- });
- }
- var groups = stuids.Where(z => !string.IsNullOrWhiteSpace(z.school)).GroupBy(x => x.school).Select(y => new { code = y.Key, list = y.ToList() });
- List<StudentScoreRecord> lessonStudentRecords = new List<StudentScoreRecord>();
- foreach (var group in groups)
- {
- 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}";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentScoreRecord>(queryText: stusql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StudentScoreRecord") }))
- {
- lessonStudentRecords.Add(item);
- }
- }
- var tmdids = students.Where(x => x.type == 1);
- if (tmdids.Any())
- {
- string tmdsql = $"select value(c) from c where c.tmdid in({string.Join(",", tmdids.Select(x => $"'{x}'"))}) and c.year={year}";
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIterator<StudentScoreRecord>(queryText: tmdsql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StudentScoreRecord") }))
- {
- lessonStudentRecords.Add(item);
- }
- }
- List<Task<ItemResponse<StudentScoreRecord>>> records = new List<Task<ItemResponse<StudentScoreRecord>>>();
- stuids.ToList().ForEach(x => {
- var record = lessonStudentRecords.Find(l => l.stuid.Equals(x.id) && l.code.Equals($"StudentScoreRecord") && l.school.Equals(x.school));
- ClientSummaryList clientSummaryList = lessonBase.report.clientSummaryList.Find(c => c.seatID == x.seatID);
- if (record != null)
- {
- if (clientSummaryList != null)
- {
- var hasrecord= record.lessonRecords.Find(x => x.lessonId.Equals(lessonRecord.id));
- if (hasrecord != null)
- {
- hasrecord.gscore = clientSummaryList.groupScore;
- hasrecord.pscore = clientSummaryList.score;
- hasrecord.tscore = clientSummaryList.tnteractScore;
- hasrecord.tmdid = teacher.id;
- hasrecord.school = school;
- hasrecord.scope = lessonRecord.scope;
- hasrecord.lessonId = lessonRecord.id;
- hasrecord.courseId = lessonRecord.courseId;
- hasrecord.periodId = lessonRecord.periodId;
- hasrecord.subjectId = lessonRecord.subjectId;
- hasrecord.time = lessonRecord.startTime;
- }
- else {
- record.lessonRecords.Add(
- new StudentLessonRecord
- {
- gscore = clientSummaryList.groupScore,
- pscore = clientSummaryList.score,
- tscore = clientSummaryList.tnteractScore,
- tmdid = teacher.id,
- school = school,
- scope = lessonRecord.scope,
- lessonId = lessonRecord.id,
- courseId = lessonRecord.courseId,
- periodId = lessonRecord.periodId,
- subjectId = lessonRecord.subjectId,
- time = lessonRecord.startTime
- }
- );
- }
- }
- }
- else
- {
- record = new StudentScoreRecord
- {
- userType = Constant.ScopeStudent,
- id = $"{snowflakeId.NextId()}",
- year = year,
- stuid = x.id,
- school = x.school,
- code = $"StudentScoreRecord",
- pk = "StudentScoreRecord",
- ttl = -1,
- lessonRecords = new List<StudentLessonRecord> { new StudentLessonRecord
- {
- gscore = clientSummaryList.groupScore,
- pscore = clientSummaryList.score,
- tscore = clientSummaryList.tnteractScore,
- tmdid = teacher.id,
- school = school,
- scope = lessonRecord.scope,
- lessonId = lessonRecord.id,
- courseId = lessonRecord.courseId,
- periodId = lessonRecord.periodId,
- subjectId = lessonRecord.subjectId,
- time= lessonRecord.startTime
- }}
- };
- }
- record.userType = Constant.ScopeStudent;
- record.gscore = record.lessonRecords.Select(x => x.gscore).Sum();
- record.pscore = record.lessonRecords.Select(x => x.pscore).Sum();
- record.tscore = record.lessonRecords.Select(x => x.tscore).Sum();
- records.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(record, partitionKey: new PartitionKey(record.code)));
- });
- tmdids.ToList().ForEach(x => {
- var record = lessonStudentRecords.Find(l => l.tmdid.Equals(x.id) && l.code.Equals($"StudentScoreRecord"));
- ClientSummaryList clientSummaryList = lessonBase.report.clientSummaryList.Find(c => c.seatID == x.seatID);
- if (record != null)
- {
- if (clientSummaryList != null)
- {
- var hasrecord = record.lessonRecords.Find(x => x.lessonId.Equals(lessonRecord.id));
- if (hasrecord != null)
- {
- hasrecord.gscore = clientSummaryList.groupScore;
- hasrecord.pscore = clientSummaryList.score;
- hasrecord.tscore = clientSummaryList.tnteractScore;
- hasrecord.tmdid = teacher.id;
- hasrecord.school = school;
- hasrecord.scope = lessonRecord.scope;
- hasrecord.lessonId = lessonRecord.id;
- hasrecord.courseId = lessonRecord.courseId;
- hasrecord.periodId = lessonRecord.periodId;
- hasrecord.subjectId = lessonRecord.subjectId;
- hasrecord.time = lessonRecord.startTime;
- }
- else
- {
- record.lessonRecords.Add(
- new StudentLessonRecord
- {
- gscore = clientSummaryList.groupScore,
- pscore = clientSummaryList.score,
- tscore = clientSummaryList.tnteractScore,
- tmdid = teacher.id,
- school = school,
- scope = lessonRecord.scope,
- lessonId = lessonRecord.id,
- courseId = lessonRecord.courseId,
- periodId = lessonRecord.periodId,
- subjectId = lessonRecord.subjectId,
- time = lessonRecord.startTime
- }
- );
- }
- }
- }
- else
- {
- record = new StudentScoreRecord
- {
- userType = Constant.ScopeTmdUser,
- id = $"{snowflakeId.NextId()}",
- code = $"StudentScoreRecord",
- pk = "StudentScoreRecord",
- ttl = -1,
- year = year,
- tmdid = x.id,
- lessonRecords = new List<StudentLessonRecord>
- {
- new StudentLessonRecord
- {
- gscore = clientSummaryList.groupScore,
- pscore = clientSummaryList.score,
- tscore = clientSummaryList.tnteractScore,
- tmdid = teacher.id,
- school = school,
- scope = lessonRecord.scope,
- lessonId = lessonRecord.id,
- courseId = lessonRecord.courseId,
- periodId = lessonRecord.periodId,
- subjectId = lessonRecord.subjectId,
- time=lessonRecord.startTime
- }
- }
- };
- }
- record.userType = Constant.ScopeStudent;
- record.gscore = record.lessonRecords.Select(x => x.gscore).Sum();
- record.pscore = record.lessonRecords.Select(x => x.pscore).Sum();
- record.tscore = record.lessonRecords.Select(x => x.tscore).Sum();
- records.Add(client.GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(record, partitionKey: new PartitionKey(record.code)));
- });
- if (records.Any())
- {
- await Task.WhenAll(records);
- }
- }
- catch (Exception ex)
- {
- await _dingding.SendBotMsg($"学生个人课例统计信息异常,{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- public static async void DoAutoDeleteSchoolLessonRecord(LessonRecord lessonRecord, string scope, CosmosClient client, string school, string tmdid,
- Teacher teacher, NotificationService _notificationService, AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, IConfiguration _configuration)
- {
- if (lessonRecord.scope.Equals("school"))
- {
- SchoolSetting setting = null;
- Azure.Response schoolSetting = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(school, new PartitionKey("SchoolSetting"));
- School schoolBase = await client.GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<School>(school, new PartitionKey("Base"));
- if (schoolSetting.Status == 200)
- {
- setting = JsonDocument.Parse(schoolSetting.Content).RootElement.Deserialize<SchoolSetting>();
- if (setting.lessonSetting != null)
- {
- if (setting.lessonSetting.openAutoClean != 0 && setting.lessonSetting.openAutoClean != 1)
- {
- setting.lessonSetting.openAutoClean = 0;
- setting.lessonSetting.expireDays = Constant.school_lesson_expire;
- }
- }
- else
- {
- setting.lessonSetting = new LessonSetting() { openAutoClean = 0, expireDays = Constant.school_lesson_expire };
- }
- }
- else
- {
- setting = new SchoolSetting() { lessonSetting = new LessonSetting { openAutoClean = 0, expireDays = Constant.school_lesson_expire } };
- }
- int school_lesson_expire = 0;
- bool save = true;
- List<string> msg = new List<string>();
- if (setting.lessonSetting.openAutoClean == 1)
- {
- if (setting.lessonSetting.conds.IsEmpty())
- {
- save = false;
- }
- else
- {
- school_lesson_expire = setting.lessonSetting.expireDays;
- foreach (var item in setting.lessonSetting.conds)
- {
- switch (item.type)
- {
- case ">=":
- switch (item.key)
- {
- case "attendRate":
- if (!(lessonRecord.attendRate >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.attendRate}{item.type}{item.val}");
- }
- break;
- case "groupCount":
- if (!(lessonRecord.groupCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.groupCount}{item.type}{item.val}");
- }
- break;
- case "totalPoint":
- if (!(lessonRecord.totalPoint >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.totalPoint}{item.type}{item.val}");
- }
- break;
- case "collateTaskCount":
- if (!(lessonRecord.collateTaskCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.collateTaskCount}{item.type}{item.val}");
- }
- break;
- case "collateCount":
- if (!(lessonRecord.collateCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.collateCount}{item.type}{item.val}");
- }
- break;
- case "pushCount":
- if (!(lessonRecord.pushCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.pushCount}{item.type}{item.val}");
- }
- break;
- case "totalInteractPoint":
- if (!(lessonRecord.totalInteractPoint >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.totalInteractPoint}{item.type}{item.val}");
- }
- break;
- case "interactionCount":
- if (!(lessonRecord.interactionCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.interactionCount}{item.type}{item.val}");
- }
- break;
- case "clientInteractionCount":
- if (!(lessonRecord.clientInteractionCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.clientInteractionCount}{item.type}{item.val}");
- }
- break;
- case "examQuizCount":
- if (!(lessonRecord.examQuizCount >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.examQuizCount}{item.type}{item.val}");
- }
- break;
- case "examPointRate":
- if (!(lessonRecord.examPointRate >= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.examPointRate}{item.type}{item.val}");
- }
- break;
- }
- break;
- case "<=":
- switch (item.key)
- {
- case "attendRate":
- if (!(lessonRecord.attendRate <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.attendRate}{item.type}{item.val}");
- }
- break;
- case "groupCount":
- if (!(lessonRecord.groupCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.groupCount}{item.type}{item.val}");
- }
- break;
- case "totalPoint":
- if (!(lessonRecord.totalPoint <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.totalPoint}{item.type}{item.val}");
- }
- break;
- case "collateTaskCount":
- if (!(lessonRecord.collateTaskCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.collateTaskCount}{item.type}{item.val}");
- }
- break;
- case "collateCount":
- if (!(lessonRecord.collateCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.collateCount}{item.type}{item.val}");
- }
- break;
- case "pushCount":
- if (!(lessonRecord.pushCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.pushCount}{item.type}{item.val}");
- }
- break;
- case "totalInteractPoint":
- if (!(lessonRecord.totalInteractPoint <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.totalInteractPoint}{item.type}{item.val}");
- }
- break;
- case "interactionCount":
- if (!(lessonRecord.interactionCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.interactionCount}{item.type}{item.val}");
- }
- break;
- case "clientInteractionCount":
- if (!(lessonRecord.clientInteractionCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.clientInteractionCount}{item.type}{item.val}");
- }
- break;
- case "examQuizCount":
- if (!(lessonRecord.examQuizCount <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.examQuizCount}{item.type}{item.val}");
- }
- break;
- case "examPointRate":
- if (!(lessonRecord.examPointRate <= item.val))
- {
- save = false;
- msg.Add($"{item.key}:{lessonRecord.examPointRate}{item.type}{item.val}");
- }
- break;
- }
- break;
- }
- }
- }
- }
- else
- {
- save = false;
- school_lesson_expire = Constant.school_lesson_expire;
- }
- if (!save && school_lesson_expire > 0)
- {
- // 1-时间戳,7-时间戳
- Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
- //暂定7天
- var now = DateTimeOffset.UtcNow;
- //剩余3天的通知
- //var day3= now.AddDays(school_lesson_expire - 3).ToUnixTimeMilliseconds();
- //result.Add(3, day3);
- //剩余1天的通知
- var day1 = now.AddDays(school_lesson_expire - (school_lesson_expire - 1)).ToUnixTimeMilliseconds();
- result.Add(1, new ExpireTag { expire = day1, tag = "notification" });
- //到期通知
- //不到五点上传的课例,七天之后直接删除。
- int addSecond = 0;
- if (now.Hour > 5)
- {
- // 到凌晨00点还差 (24 - now.Hour) *60 * 60 分钟,再加天数;
- addSecond = school_lesson_expire * 86400 + (24 - now.Hour) * 3600 - (now.Hour * 3600);
- //再加 00到05小时内的 随机秒数
- Random rand = new Random();
- int randInt = rand.Next(0, 18000);
- addSecond += randInt;
- }
- else
- {
- addSecond = school_lesson_expire * 24 * 60 * 60;
- }
- lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
- result.Add(school_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
- // result.Add(school_lesson_expire, lessonRecord.expire);
- string biz = "expire";
- Notification notification = new Notification
- {
- hubName = "hita",
- type = "msg",
- from = $"ies5:{Environment.GetEnvironmentVariable("Option:Location")}:private",
- to = new List<string> { tmdid },
- label = $"{biz}_lessonRecord",
- body = new
- {
- location = $"{Environment.GetEnvironmentVariable("Option:Location")}",
- biz = biz,
- tmdid = tmdid,
- tmdname = teacher.name,
- scope = scope,
- school = school,
- schoolName = schoolBase.name,
- sid = lessonRecord.id,
- sname = lessonRecord.name,
- stime = lessonRecord.startTime,
- expire = lessonRecord.expire,
- status = 1,
- //day = school_lesson_expire,
- time = now
- }.ToJsonString(),
- expires = DateTimeOffset.UtcNow.AddDays(7).ToUnixTimeSeconds()
- };
- var url = _configuration.GetValue<string>("HaBookAuth:CoreService:sendnotification");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = $"{Environment.GetEnvironmentVariable("Option:Location")}";
- await _notificationService.SendNotification(clientID, clientSecret, location, url, notification); //站内发送消息
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- if (records.Count <= 0)
- {
- foreach (var item in result)
- {
- string PartitionKey = string.Format("{0}{1}{2}", lessonRecord.code, "-", $"expire-{item.Key}");
- //课堂的id ,
- //课堂的通知时间类型progress, 默认就会发送一条,到期前一天发送一条,最后已到期发送一条。
- var message = new ServiceBusMessage(new
- {
- id = lessonRecord.id,
- progress = item.Key,
- code = lessonRecord.code,
- scope = lessonRecord.scope,
- school = lessonRecord.school,
- opt = "delete",
- expire = lessonRecord.expire,
- tmdid = tmdid,
- tmdname = teacher.name,
- name = lessonRecord.name,
- startTime = lessonRecord.startTime,
- tag = item.Value.tag
- }.ToJsonString());
- message.ApplicationProperties.Add("name", "LessonRecordExpire");
- long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), message, DateTimeOffset.FromUnixTimeMilliseconds(item.Value.expire));
- ChangeRecord changeRecord = new ChangeRecord
- {
- RowKey = lessonRecord.id,
- PartitionKey = PartitionKey,
- sequenceNumber = start,
- msgId = message.MessageId
- };
- await table.Save<ChangeRecord>(changeRecord);
- }
- }
- }
- else
- {
- if (lessonRecord.expire > 0)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("ChangeRecord");
- List<ChangeRecord> records = await table.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", lessonRecord.id } });
- foreach (var record in records)
- {
- try
- {
- await table.DeleteSingle<ChangeRecord>(record.PartitionKey, record.RowKey);
- await _serviceBus.GetServiceBusClient().CancelMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), record.sequenceNumber);
- }
- catch (Exception)
- {
- continue;
- }
- }
- }
- lessonRecord.save = 1;
- lessonRecord.expire = -1;
- }
- }
- }
- public record ExpireTag
- {
- public long expire { get; set; }
- public string tag { get; set; }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="client"></param>
- /// <param name="_dingDing"></param>
- /// <param name="data"></param>
- /// <returns></returns>
- public static LessonDis DisLessonCount(LessonRecord oldRecord, LessonRecord newRecord, LessonDis lessonDis)
- {
- //创建课堂的情况
- if (oldRecord == null && newRecord != null)
- {
- lessonDis.record = 1;
- }
- //删除数据的情况
- //不再对LessonCount进行减
- else if (oldRecord != null && newRecord == null)
- {
- /*lessonDis.record = -1;
- //P分数量加减
- if (oldRecord.pScore >= 70)
- {
- lessonDis.disPCount = -1;
- }
- //T分数量加减
- if (oldRecord.tScore >= 70)
- {
- lessonDis.disTCount = -1;
- }
- if (oldRecord.tScore >= 70 && oldRecord.pScore >= 70)
- {
- lessonDis.disTCount = -1;
- }*/
- }
- //无效操作
- else if (oldRecord == null && newRecord == null)
- {
- }
- //前后操作都有值,则表示更新
- else
- {
- //P分数量加减
- if (oldRecord.pScore >= 70)
- {
- if (newRecord.pScore < 70)
- {
- lessonDis.disPCount = -1;
- }
- }
- else
- {
- if (newRecord.pScore >= 70)
- {
- lessonDis.disPCount = 1;
- }
- }
- //T分数量加减
- if (oldRecord.tScore >= 70)
- {
- if (newRecord.tScore < 70)
- {
- lessonDis.disTCount = -1;
- }
- }
- else
- {
- if (newRecord.tScore >= 70)
- {
- lessonDis.disTCount = 1;
- }
- }
- //双绿灯数量
- if (oldRecord.tScore >= 70 && oldRecord.pScore >= 70)
- {
- if (newRecord.tScore < 70 || newRecord.pScore < 70)
- {
- lessonDis.disDCount = -1;
- }
- }
- else
- {
- if (newRecord.tScore >= 70 && newRecord.pScore >= 70)
- {
- lessonDis.disDCount = 1;
- }
- }
- }
- return lessonDis;
- }
- public static LessonDis DisLessonCount_2(LessonRecord oldRecord, LessonRecord newRecord, LessonDis lessonDis)
- {
- //创建课堂的情况
- if (oldRecord == null && newRecord != null)
- {
- lessonDis.record = 1;
- //P分数量加减
- if (newRecord.pScore >= 70)
- {
- lessonDis.disPCount = 1;
- }
- //T分数量加减
- if (newRecord.tScore >= 70)
- {
- lessonDis.disTCount = 1;
- }
- //双绿灯数量
- if (newRecord.tScore >= 70 && newRecord.pScore >= 70)
- {
- lessonDis.disDCount = 1;
- }
- }
- return lessonDis;
- }
- public static async Task FixLessonCount(CosmosClient client, DingDing _dingDing, LessonRecord record, LessonRecord oldRecord, LessonDis lessonDis)
- {
- LessonRecord data = null;
- try
- {
- if (record != null && oldRecord == null)
- {
- data = record;
- }
- if (record == null && oldRecord != null)
- {
- data = oldRecord;
- }
- if (record != null && oldRecord != null)
- {
- data = record;
- }
- int day = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).DayOfYear;
- int year = DateTimeOffset.FromUnixTimeMilliseconds(data.startTime).Year;
- int days = DateTimeHelper.getDays(year);
- //int years = DateTimeOffset.UtcNow.DayOfYear;
- string tbname = string.Empty;
- string code = string.Empty;
- if (data.scope != null && data.scope.Equals("school"))
- {
- if (string.IsNullOrEmpty(data.periodId))
- {
- code = $"LessonCount-{data.school}-{year}";
- tbname = "School";
- }
- else
- {
- code = $"LessonCount-{data.school}-{year}-{data.periodId}";
- tbname = "School";
- }
- }
- else
- {
- code = $"LessonCount-{year}";
- tbname = "Teacher";
- }
- var response = await client.GetContainer(Constant.TEAMModelOS, tbname).ReadItemStreamAsync(data.tmdid.ToString(), new PartitionKey(code));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- LessonCount count = json.ToObject<LessonCount>();
- count.tCount[day - 1] += lessonDis.disTCount;
- count.pCount[day - 1] += lessonDis.disPCount;
- count.ptCount[day - 1] += lessonDis.disDCount;
- count.beginCount[day - 1] += lessonDis.record;
- await client.GetContainer("TEAMModelOS", tbname).ReplaceItemAsync(count, count.id, new PartitionKey(code));
- }
- else
- {
- LessonCount count = new()
- {
- id = data.tmdid,
- code = code,
- ttl = -1
- };
- double[] da = new double[days];
- List<double> list = new(da);
- List<double> listT = new(da);
- List<double> listP = new(da);
- List<double> listPT = new(da);
- list[day - 1] += lessonDis.record;
- listT[day - 1] += lessonDis.disTCount;
- listP[day - 1] += lessonDis.disPCount;
- listPT[day - 1] += lessonDis.disDCount;
- count.beginCount.AddRange(list);
- count.tCount.AddRange(listT);
- count.pCount.AddRange(listP);
- count.ptCount.AddRange(listPT);
- //count.courseIds.Add(data.courseId);
- await client.GetContainer("TEAMModelOS", tbname).CreateItemAsync(count, new PartitionKey(code));
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-LessonCount-FixLessonCount\n{ex.Message}\n{ex.StackTrace}{data.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
|