CrazyIter_Bin 2 年之前
父节点
当前提交
75a39bd617
共有 1 个文件被更改,包括 155 次插入53 次删除
  1. 155 53
      TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

+ 155 - 53
TEAMModelOS.FunctionV4/ServiceBus/ActiveTaskTopic.cs

@@ -49,7 +49,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
 {
     public class ActiveTaskTopic
     {
- 
+
         private readonly int psize = 20;
         private readonly AzureCosmosFactory _azureCosmos;
         private readonly DingDing _dingDing;
@@ -62,7 +62,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         private readonly IConverter _converter;
         private readonly SnowflakeId _snowflakeId;
         private readonly HttpTrigger _httpTrigger;
-        public ActiveTaskTopic(HttpTrigger httpTrigger,SnowflakeId snowflakeId, IConverter converter, CoreAPIHttpService coreAPIHttpService,
+        public ActiveTaskTopic(HttpTrigger httpTrigger, SnowflakeId snowflakeId, IConverter converter, CoreAPIHttpService coreAPIHttpService,
             AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis,
             AzureServiceBusFactory serviceBus, IOptionsSnapshot<Option> option,
              IConfiguration configuration)
@@ -77,7 +77,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             _coreAPIHttpService = coreAPIHttpService;
             _converter = converter;
             _snowflakeId = snowflakeId;
-            _httpTrigger=httpTrigger;
+            _httpTrigger = httpTrigger;
         }
         [Function("Exam")]
         public async Task ExamFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "exam", Connection = "Azure:ServiceBus:ConnectionString")] string msg)
@@ -279,8 +279,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
 
         }
 
-      
-       
+
+
         /// <param name="msg"></param>
         /// <returns></returns>
         [Function("TeacherTrainChange")]
@@ -613,7 +613,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             }
         }
         [Function("GenPdf")]
-        public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%",  Connection = "Azure:ServiceBus:ConnectionString",IsBatched =false)] string msg  )
+        public async Task GenPdfFunc([ServiceBusTrigger("%Azure:ServiceBus:GenPdfQueue%", Connection = "Azure:ServiceBus:ConnectionString", IsBatched = false)] string msg)
         {
             //https://github.com/aafgani/AzFuncWithServiceBus/blob/a0da42f59b5fc45655b73b85bae932e84520db70/ServiceBusTriggerFunction/host.json
             //  messageHandlerOptions 设置
@@ -632,18 +632,19 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             }
         }
 
-     
-       
-        private async Task GenArtStudentPdf(JsonElement json , string msg) {
+
+
+        private async Task GenArtStudentPdf(JsonElement json, string msg)
+        {
             try
-            {  
+            {
                 json.TryGetProperty("studentIds", out JsonElement _studentIds);
                 json.TryGetProperty("artId", out JsonElement _artId);
                 json.TryGetProperty("schoolCode", out JsonElement _schoolId);
                 json.TryGetProperty("headLang", out JsonElement headLang);
-                List<string> studentIds= _studentIds.ToObject<List<string>>();
-                 string _schoolCode=$"{_schoolId}";
-                (List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults) = await ArtService.GenStuArtPDF(studentIds,$"{_artId}",   $"{_schoolId}", $"{headLang}", _azureCosmos, _coreAPIHttpService, _dingDing);
+                List<string> studentIds = _studentIds.ToObject<List<string>>();
+                string _schoolCode = $"{_schoolId}";
+                (List<ArtStudentPdf> studentPdfs, List<StudentArtResult> artResults) = await ArtService.GenStuArtPDF(studentIds, $"{_artId}", $"{_schoolId}", $"{headLang}", _azureCosmos, _coreAPIHttpService, _dingDing);
                 foreach (var artResult in artResults)
                 {
                     if (artResult.pdf == null || string.IsNullOrWhiteSpace(artResult.pdf.blob) || string.IsNullOrWhiteSpace(artResult.pdf.url))
@@ -657,13 +658,14 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                             prime = false,//此处的作用是判断是否已经生成OK.
                         };
                     }
-                    else {
+                    else
+                    {
                         artResult.pdf.prime = false;//此处的作用是判断是否已经生成OK.
                     }
                     await _azureRedis.GetRedisClient(8).HashSetAsync($"ArtPDF:{_artId}", artResult.studentId, artResult.ToJsonString());
                 }
                 //2个小时。
-                await _azureRedis.GetRedisClient(8).KeyExpireAsync($"ArtPDF:{_artId}",new TimeSpan(2,0,0));
+                await _azureRedis.GetRedisClient(8).KeyExpireAsync($"ArtPDF:{_artId}", new TimeSpan(2, 0, 0));
                 List<Task<string>> uploads = new List<Task<string>>();
                 studentPdfs.ForEach(x => {
                     x.blob = $"art/{x.artId}/report/{x.studentId}.json";
@@ -678,7 +680,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                     var s = _azureStorage.GetBlobSAS($"{_schoolCode}", x.blob, BlobSasPermissions.Read);
                     s = $"{HttpUtility.UrlEncode($"{s}", Encoding.UTF8)}";
                     string url = $"{atrUrl}?url={s}&pdfpath={x.artId}/report/{x.studentId}";
-                    urls.Add(url); 
+                    urls.Add(url);
                 });
                 string env = "release";
                 if (Environment.GetEnvironmentVariable("Option:Location").Contains("Test", StringComparison.CurrentCultureIgnoreCase) ||
@@ -690,7 +692,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 {
                     var screenshot = new ScreenshotDto
                     {
-                        msgId=Guid.NewGuid().ToString(),
+                        msgId = Guid.NewGuid().ToString(),
                         width = 1080,
                         height = 1920,
                         urls = urls,
@@ -703,7 +705,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                     var message = new ServiceBusMessage(screenshot.ToJsonString());
                     await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", message);
                 }
-                else {
+                else
+                {
                     int pages = (urls.Count + psize) / psize;
                     for (int i = 0; i < pages; i++)
                     {
@@ -720,7 +723,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                             pagesize = 5,
                             env = env
                         };
-                        var message= new ServiceBusMessage(screenshot.ToJsonString());
+                        var message = new ServiceBusMessage(screenshot.ToJsonString());
                         await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", message);
                     }
                 }
@@ -730,7 +733,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 await _dingDing.SendBotMsg($"{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
             }
         }
-        private async Task GenOfflineRecordPdf(JsonElement element,string msg) {
+        private async Task GenOfflineRecordPdf(JsonElement element, string msg)
+        {
             try
             {
                 var client = _azureCosmos.GetCosmosClient();
@@ -952,7 +956,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
         }
         //更新學校產品一覽表
         //處理內容:取得所有序號購買紀錄,服務週期、硬體購買紀錄後,更新ProductSum
-       [Function("Product")]
+        [Function("Product")]
         public async Task ProductFunc([ServiceBusTrigger("%Azure:ServiceBus:ActiveTask%", "product", Connection = "Azure:ServiceBus:ConnectionString")] string msg, ILogger log)
         {
             try
@@ -1134,7 +1138,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 var result = await BatchCopyFileService.CopyFile(_dingDing, _azureStorage, bIBatchCopyFile);
                 if (result == 200)
                 {
-                  
+
 
                 }
             }
@@ -1205,9 +1209,9 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
             {
                 return;
             }
-            if (!string.IsNullOrWhiteSpace(school)&& school.Equals("habook"))
+            if (!string.IsNullOrWhiteSpace(school) && school.Equals("habook"))
             {
-               await _dingDing.SendBotMsg($"研发学校课堂记录事件触发:\n{msg}", GroupNames.成都开发測試群組);
+                await _dingDing.SendBotMsg($"研发学校课堂记录事件触发:\n{msg}", GroupNames.成都开发測試群組);
             }
             var client = _azureCosmos.GetCosmosClient();
 
@@ -1307,14 +1311,17 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 break;
                             //更新 基础统计信息
                             case "up-base":
-                              
+
                                 //如果有更新 则去读取/{_lessonId}/IES/base.json
-                                try {
+                                try
+                                {
                                     BlobDownloadResult timelineblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/TimeLine.json").DownloadContentAsync();
                                     TimeLineData timeLineData = timelineblobDownload.Content.ToObjectFromJson<TimeLineData>();
                                     lessonRecord.hitaClientCmpCount = timeLineData.events.Where(z => !string.IsNullOrWhiteSpace(z.WrkCmpSrcType) && z.WrkCmpSrcType.Equals("HitaClientCmp")).Count();
                                     //lessonRecord.collateTaskCount = lessonRecord.hitaClientCmpCount;
-                                } catch (Exception ex ){
+                                }
+                                catch (Exception ex)
+                                {
                                     await _dingDing.SendBotMsg($"TimeLine.json转换异常,{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
                                 }
 
@@ -1323,11 +1330,14 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                     // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 收到更新", GroupNames.醍摩豆服務運維群組);
                                     BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient(blobname).GetBlobClient($"/records/{_lessonId}/IES/base.json").DownloadContentAsync();
                                     //attendState
-                                    string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall","0");
+                                    string basejson = baseblobDownload.Content.ToString().Replace("\"Uncall\"", "0").Replace("Uncall", "0");
                                     LessonBase lessonBase = null;
-                                    try {
+                                    try
+                                    {
                                         lessonBase = basejson.ToObject<LessonBase>();
-                                    } catch (Exception ex ){
+                                    }
+                                    catch (Exception ex)
+                                    {
                                         await _dingDing.SendBotMsg($"base.json转换异常,{ex.Message}{ex.StackTrace}{basejson}", GroupNames.成都开发測試群組);
                                         //lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
                                     }
@@ -1340,7 +1350,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         lessonRecord.attendRate = lessonBase.summary.attendRate;
                                         lessonRecord.groupCount = lessonBase.summary.groupCount;
                                         lessonRecord.collateTaskCount = lessonBase.summary.collateTaskCount;
-                                        lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount+ lessonRecord.hitaClientCmpCount;
+                                        lessonRecord.hitaClientCmpCount = lessonBase.summary.collateTaskCount + lessonRecord.hitaClientCmpCount;
                                         lessonRecord.collateCount = lessonBase.summary.collateCount;
                                         lessonRecord.pushCount = lessonBase.summary.pushCount;
                                         lessonRecord.totalPoint = lessonBase.summary.totalPoint;
@@ -1354,10 +1364,11 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         lessonRecord.learningCategory = lessonBase.summary.learningCategory;
                                         if (lessonRecord.learningCategory == null)
                                         {
-                                            
+
                                             lessonRecord.learningCategory = new LearningCategory();
                                         }
-                                        if (lessonRecord.hitaClientCmpCount > 0) {
+                                        if (lessonRecord.hitaClientCmpCount > 0)
+                                        {
 
                                             lessonRecord.learningCategory.cooperation = 1;
                                         }
@@ -1380,7 +1391,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                 T = 0;
                                             }
                                             else if (lessonRecord.clientInteractionAverge > 0 && lessonRecord.clientInteractionAverge < 2)
-                                           // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
+                                            // else if (lessonRecord.clientInteractionAverge >= 1 && lessonRecord.clientInteractionAverge <= 2)
                                             {
                                                 T = 1;
                                             }
@@ -1445,7 +1456,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                     lessonRecord.upload = 1;
                                     // await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} 更新完成", GroupNames.醍摩豆服務運維群組);
 
-                                    LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration,_coreAPIHttpService,_dingDing, _azureRedis);
+                                    LessonService.DoAutoDeleteSchoolLessonRecord(lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, _coreAPIHttpService, _dingDing, _azureRedis);
                                     long? size = await _azureStorage.GetBlobContainerClient(blobname).GetBlobsSize($"records/{_lessonId}");
                                     Bloblog bloblog = new Bloblog
                                     {
@@ -1460,12 +1471,12 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                         periodId = string.IsNullOrWhiteSpace(lessonRecord.periodId) ? new List<string>() : new List<string> { lessonRecord.periodId },
                                         size = size.HasValue ? size.Value : 0,
                                     };
-                                    await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog); 
+                                    await client.GetContainer(Constant.TEAMModelOS, tbname).UpsertItemAsync(bloblog);
                                     //await _dingDing.SendBotMsg($"{_option.Location},课堂id:{_lessonId} blob刷新完成!", GroupNames.醍摩豆服務運維群組);
-                                    await BlobService.RefreshBlobRoot(new BlobRefreshMessage {  progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration,_azureRedis);
+                                    await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
                                     msgs.Add(update);
 
-                                    DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher,   _serviceBus, _azureStorage, _configuration, lessonBase);
+                                    DoLessonStudentRecord(_dingDing, _snowflakeId, lessonRecord, scope, client, school, tmdid, teacher, _serviceBus, _azureStorage, _configuration, lessonBase);
 
                                 }
                                 catch (Exception ex)
@@ -1475,7 +1486,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                     //}
                                     await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}课程读取base.json,{_lessonId}\n{ex.Message}\n{ex.StackTrace}\n\n{lessonRecord.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
                                 }
-                               // await BIStats.SetTypeAddStats(client, _dingDing,lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
+                                // await BIStats.SetTypeAddStats(client, _dingDing,lessonRecord.school, "Less", 0, 1, lessonRecord.clientInteractionCount);//BI统计增/减量
                                 break;
                             //更新 时间线
                             case "up-TimeLine":
@@ -1540,7 +1551,7 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                     }
                                     await _azureStorage.GetBlobServiceClient().DeleteBlobs(_dingDing, blobname, new List<string> { $"records/{_lessonId}" });
                                     await client.GetContainer(Constant.TEAMModelOS, tbname).DeleteItemStreamAsync(lessonRecord.id, new PartitionKey($"Bloblog-{blobname}"));
-                                    await BlobService.RefreshBlobRoot(new BlobRefreshMessage {   progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
+                                    await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "update", root = "records", name = $"{blobname}" }, _serviceBus, _configuration, _azureRedis);
                                     msgs.Add(update);
                                 }
                                 catch (CosmosException)
@@ -1606,12 +1617,14 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                 if (lessonRecord.groupIds.IsNotEmpty())
                                 {
                                     List<GroupListDto> groups = await GroupListService.GetGroupListByListids(client, _dingDing, lessonRecord.groupIds, lessonRecord.school);
-                                    if ( !string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId)) {
+                                    if (!string.IsNullOrWhiteSpace(lessonRecord.school) && !string.IsNullOrWhiteSpace(lessonRecord.periodId))
+                                    {
                                         HashSet<string> grades = new HashSet<string>();
                                         School schoolObj = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>(lessonRecord.school, new PartitionKey("Base"));
                                         HashSet<int> gd = groups.SelectMany(z => z.grades).ToHashSet();
                                         groups.ForEach(y => {
-                                            if (y.type.Equals("teach")|| y.type.Equals("class")) {
+                                            if (y.type.Equals("teach") || y.type.Equals("class"))
+                                            {
                                                 gd.Add(y.year);
                                             }
                                         });
@@ -1643,15 +1656,103 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                             SchoolTeacher st = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<SchoolTeacher>(lessonRecord.tmdid, new PartitionKey($"Teacher-{schoolInfo.schoolId}"));
                                             blobTotal += st.size;
                                         }
-                                        //剩余空间大于2G 
-                                        if (blobTotal * 1073741824 - blobsize > 2147483648)
+
+                                        //20230208调整之前  if (blobTotal * 1073741824 - blobsize > 2147483648)  //剩余空间大于2G 
+                                        //剩余空间不足,则开启自动清理机制
+                                        if (blobTotal * 1073741824 - blobsize > 0)
                                         {
-                                            //大于2G 不限制
+                                            //大于0则表示空间充足
                                             lessonLimit = -1;
                                         }
+                                        else
+                                        {
+                                            //20230208调整增加逻辑,之前lessonLimit用于处理默认保存50条,现在用于处理标记是否空间不足,不足则标记清理。
+                                            lessonLimit = 0;
+                                        }
                                         if (lessonLimit != -1)
                                         {
+                                            #region 20230208 调整之后
+                                            {
+                                                // 1-时间戳,7-时间戳
+                                                Dictionary<int, ExpireTag> result = new Dictionary<int, ExpireTag>();
+                                                //暂定7天 
+                                                var now = DateTimeOffset.UtcNow;
+                                                //剩余3天的通知
+                                                //var day3= now.AddDays(Constant.private_lesson_expire - 3).ToUnixTimeMilliseconds();
+                                                //result.Add(3, day3);
+                                                //剩余1天的通知
+                                                var day1 = now.AddDays(Constant.private_lesson_expire - (Constant.private_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 = Constant.private_lesson_expire * 86400 + (24 - now.Hour) * 3600;
+                                                    //再加 00到05小时内的 随机秒数
+                                                    Random rand = new Random();
+                                                    int randInt = rand.Next(0, 18000);
+                                                    addSecond += randInt;
+                                                }
+                                                else
+                                                {
+                                                    addSecond = Constant.private_lesson_expire * 24 * 60 * 60;
+                                                }
+                                                //将当前课例标记为  自动清理
 
+
+                                                lessonRecord.expire = now.AddSeconds(addSecond).ToUnixTimeMilliseconds();
+
+                                                result.Add(Constant.private_lesson_expire, new ExpireTag { expire = lessonRecord.expire, tag = "delete" });
+                                                string biz = "expire";
+                                                string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(lessonRecord.expire).ToString("yyyy-MM-dd HH:mm:ss");
+                                                _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = teacher.id, name = teacher.name, code = teacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
+                                                             new Dictionary<string, object> { { "tmdname", teacher.name }, { "tmdid", teacher.name }, { "expireTime", expireTime }, { "lessonId", lessonRecord.id }, { "lessonName", lessonRecord.name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
+                                                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);
+                                                    }
+                                                }
+                                                await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecord, lessonRecord.id, new PartitionKey(lessonRecord.code));
+
+                                            }
+                                            #endregion 20230208 调整之后
+
+                                            #region 20230208 调整之前
+                                            /** 20230208 调整之前
                                             HashSet<string> ids = new HashSet<string>();
                                             //未定义的 以及过期时间小于等于0 的 课例
                                             string private_count_sql = $"select value(c.id) from  c where  ( c.expire<=0 or IS_DEFINED(c.expire) = false  ) and c.tmdid='{tmdid}'  ";
@@ -1767,7 +1868,8 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                                                     await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(lessonRecordExpire, lessonRecordExpire.id, new PartitionKey(lessonRecordExpire.code));
                                                 }
 
-                                            }
+                                            }**/
+                                            #endregion 20230208 调整之前
                                         }
                                         else
                                         {
@@ -1858,14 +1960,14 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                         messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
                         await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
                         await _dingDing.SendBotMsg($"课例:【{lessonRecord.name}】\n课例ID:【{lessonRecord.id}】\n因时间到期,即将被自动删除,到期时间:" +
-                            $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
+                        $"{lessonRecord.expire}\n{lessonRecord.ToJsonString()}", GroupNames.成都开发測試群組);
                     }
                 }
                 string biz = "expire";
                 Teacher targetTeacher = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>($"{tmdid}", new PartitionKey($"Base"));
                 string expireTime = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse($"{expire}")).ToString("yyyy-MM-dd HH:mm:ss");
                 _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "expire-private_lessonRecord", Constant.NotifyType_IES5_Course,
-                             new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid",tmdid}, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName",name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
+                new Dictionary<string, object> { { "tmdname", tmdname }, { "tmdid", tmdid }, { "lessonId", id }, { "expireTime", expireTime }, { "lessonName", name } }, $"{Environment.GetEnvironmentVariable("Option:Location")}", _configuration, _dingDing, "");
             }
             catch (Exception ex)
             {
@@ -2194,16 +2296,16 @@ namespace TEAMModelOS.FunctionV4.ServiceBus
                 //await _dingDing.SendBotMsg($"IES5,{Environment.GetEnvironmentVariable("Option:Location")},Imei AF call\n{msg.ToJsonString()}", GroupNames.成都开发測試群組);
                 using var json = JsonDocument.Parse(msg);
                 if (json.RootElement.TryGetProperty("channel", out JsonElement channel) &&
-                    json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
-                    json.RootElement.TryGetProperty("school", out JsonElement school) &&
-                    json.RootElement.TryGetProperty("stus", out JsonElement stus))
+                json.RootElement.TryGetProperty("userid", out JsonElement userid) &&
+                json.RootElement.TryGetProperty("school", out JsonElement school) &&
+                json.RootElement.TryGetProperty("stus", out JsonElement stus))
                 {
                     var db = _azureCosmos.GetCosmosClient();
                     foreach (var stu in stus.EnumerateArray())
                     {
                         await foreach (Response item in db.GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryStreamIterator(
-                            queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}'",
-                            requestOptions: new() { PartitionKey = new($"Imei") }))
+                        queryText: $"SELECT TOP 1 * FROM c WHERE c.stuid = '{stu.GetString()}'",
+                        requestOptions: new() { PartitionKey = new($"Imei") }))
                         {
                             using var root = await JsonDocument.ParseAsync(item.ContentStream);
                             if (root.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)