CrazyIter_Bin 2 роки тому
батько
коміт
a2c2cfe7ea

+ 226 - 0
TEAMModelOS.SDK/Models/Service/FixDataService.cs

@@ -15,11 +15,237 @@ using TEAMModelOS.SDK.Models.Cosmos.Common;
 using System.Dynamic;
 using Newtonsoft.Json;
 using TEAMModelOS.Models;
+using Azure.Storage.Blobs.Models;
+using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
+using DinkToPdf.Contracts;
 
 namespace TEAMModelOS.SDK.Models.Service
 {
     public static class FixDataService
     {
+
+        public static async Task GenOfflineRecordPdf(AzureCosmosFactory _azureCosmos,DingDing _dingDing , AzureStorageFactory _azureStorage,CoreAPIHttpService _coreAPIHttpService, IConverter _converter, JsonElement element, string msg)
+        {
+            try
+            {
+                var client = _azureCosmos.GetCosmosClient();
+                /*                var jsonMsg = JsonDocument.Parse(msg);
+                                jsonMsg.RootElement.TryGetProperty("id", out JsonElement id);
+                                //jsonMsg.RootElement.TryGetProperty("code", out JsonElement code);*/
+
+                element.TryGetProperty("id", out JsonElement ids);
+                List<string> tIds = ids.ToObject<List<string>>();
+                element.TryGetProperty("school", out JsonElement _code);
+                string code = "";
+                element.TryGetProperty("Key", out JsonElement key);
+                if (string.IsNullOrWhiteSpace($"{_code}"))
+                {
+                    code = $"{key}";
+                }
+                else
+                {
+                    code = $"{_code}";
+                }
+                if (string.IsNullOrWhiteSpace(code))
+                {
+                    await _dingDing.SendBotMsg($"校本研修生成PDF时,学校id为空\n{msg}", GroupNames.成都开发測試群組);
+                    return;
+
+                }
+                string sname = string.Empty;
+                string areaId = string.Empty;
+                School school = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{code}", new PartitionKey("Base"));
+                sname = school.name;
+                areaId = school.areaId;
+                //var scquery = $"SELECT c.name,c.areaId from c where c.id = '{code}'";
+                //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryStreamIterator(queryText: scquery, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
+                //{
+
+                //    using var json = await JsonDocument.ParseAsync(item.ContentStream);
+                //    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
+                //    {
+                //        var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
+                //        while (accounts.MoveNext())
+                //        {
+                //            JsonElement account = accounts.Current;
+                //            sname = account.GetProperty("name").ToString();
+                //            areaId = account.GetProperty("areaId").ToString();
+                //        }
+                //    }
+                //}
+                if (string.IsNullOrWhiteSpace(areaId))
+                {
+                    await _dingDing.SendBotMsg($"校本研修生成PDF时,区级id为空\n{msg}", GroupNames.成都开发測試群組);
+                    return;
+                }
+                if (!tIds.Any())
+                {
+                    return;
+                }
+                var blobclient = _azureStorage.GetBlobContainerClient($"teammodelos");
+                //查询当前学校所有的校本研修活动
+                List<Study> studies = new();
+                var query = $"select value(c) FROM c join b in c.teacIds where b in ({string.Join(",", tIds.Select(o => $"'{o}'"))}) and (c.status<>404 or IS_DEFINED(c.status) = false)";
+                await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Study-{code}") }))
+                {
+                    studies.Add(item);
+                }
+                //List<string> tcs = new();
+                //foreach (var item in studies)
+                //{
+                //    foreach (var td in item.tchLists)
+                //    {
+                //        if (!tcs.Contains(td))
+                //        {
+                //            tcs.Add(td);
+                //        }
+                //    }
+                //}
+                HashSet<string> tcs = studies.SelectMany(x => x.tchLists).Where(y => !string.IsNullOrWhiteSpace(y)).ToHashSet();
+                (List<RMember> tchList, List<RGroupList> classInfos) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, tcs.ToList(), code, null);
+                foreach (string id in tIds)
+                {
+                    StringBuilder stringBuilder = new StringBuilder();
+                    string cname = string.Empty;
+                    string gname = string.Empty;
+                    if (tchList.Exists(c => c.id == id))
+                    {
+                        gname = tchList.Where(c => c.id == id).FirstOrDefault().groupName;
+                        cname = tchList.Where(c => c.id == id).FirstOrDefault().name;
+                    }
+                    List<string> details = new();
+                    foreach (Study study in studies)
+                    {
+                        if (!study.teacIds.Contains(id))
+                        {
+                            continue;
+                        }
+                        var sresponse = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemStreamAsync(study.id, new PartitionKey($"StudyRecord-{id}"));
+                        if (sresponse.Status == 200)
+                        {
+                            var json = await JsonDocument.ParseAsync(sresponse.ContentStream);
+                            StudyRecord record = json.ToObject<StudyRecord>();
+                            if (record.status == 1)
+                            {
+                                var start = DateTimeHelper.FromUnixTimestamp(study.startTime).ToString("yyyy/MM/dd");
+                                var end = DateTimeHelper.FromUnixTimestamp(study.endTime).ToString("yyyy/MM/dd");
+                                string tname = string.Empty;
+                                List<string> setName = new();
+                                foreach (string setting in study.settings)
+                                {
+                                    if (setting.Equals("sign"))
+                                    {
+                                        setName.Add("扫码签到");
+                                    }
+                                    else if (setting.Equals("hw"))
+                                    {
+                                        setName.Add("作业提交");
+                                    }
+                                    else if (setting.Equals("survey"))
+                                    {
+                                        setName.Add("问卷反馈");
+                                    }
+                                    else if (setting.Equals("exam"))
+                                    {
+                                        setName.Add("评测活动");
+                                    }
+                                }
+                                switch (study.type)
+                                {
+                                    case 1:
+                                        tname = "信息化教学案例展示与分享";
+                                        break;
+                                    case 2:
+                                        tname = "专家专题培训";
+                                        break;
+                                    case 3:
+                                        tname = "同课同构";
+                                        break;
+                                    case 4:
+                                        tname = "同课异构";
+                                        break;
+                                    case 5:
+                                        tname = "校本2.0培训";
+                                        break;
+                                    case 6:
+                                        tname = "自定义活动";
+                                        break;
+                                };
+                                stringBuilder.Append($@"<tr>
+                                                        <td> {study.topic} </td>
+                                                        <td> {tname} </td >
+                                                        <td> {study.hour} </td >
+                                                        <td> {study.hour} </td >
+                                                        <td> {start} 到 {end} </td>
+                                                        <td>{study.desc}</td>
+                                                        <td> {string.Join("、", setName.Select(x => $"{x}\n"))} </td>
+                                                        <td> 已完成 </td >
+                                                    </tr> ");
+                            }
+                            else
+                            {
+                                continue;
+                            }
+                        }
+                        else
+                        {
+                            continue;
+                        }
+                    }
+                    string url = await StudyService.GenPdf(id, areaId, cname, sname, gname, stringBuilder.ToString(), _converter, _azureStorage, _dingDing);
+                    Azure.Response teacherTrainRes = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemStreamAsync(id, new PartitionKey($"TeacherTrain-{code}"));
+                    if (teacherTrainRes.Status == 200)
+                    {
+                        TeacherTrain teacherTrain = JsonDocument.Parse(teacherTrainRes.Content).RootElement.Deserialize<TeacherTrain>();
+                        try
+                        {
+                            BlobDownloadInfo blobDownload = await blobclient.GetBlobClient(url).DownloadAsync(range: new HttpRange(0, 4 * 1048576), rangeGetContentHash: true);
+                            if (blobDownload.Details.ContentHash != null)
+                            {
+
+                                string hash = Md5Hash.GetbyteToString(blobDownload.Details.ContentHash);
+                                teacherTrain.offlineReport = new Attachment
+                                {
+                                    hash = hash,
+                                    url = url,
+                                    blob = $"{blobclient.Uri}/{url}",
+                                    extension = "pdf",
+                                    name = $"{teacherTrain.nickname}-校本研修汇总报告.pdf",
+                                    type = "doc",
+                                    size = blobDownload.ContentLength
+                                };
+                                await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, id, new PartitionKey($"TeacherTrain-{code}"));
+                            }
+                        }
+                        catch
+                        {
+                        }
+                    }
+                }
+
+
+                /*var query = $"select c.id,c.name,c.type,c.hour,c.startTime,c.endTime,c.presenter,c.topic from c where (c.status<>404 or IS_DEFINED(c.status) = false and array_contains(c.teacIds, '{id}') )";
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryIterator<Study>(queryText: query, requestOptions: new QueryRequestOptions() {PartitionKey = new PartitionKey($"Study-{code}") }))
+                {
+                    studies.Add(item);
+
+                }*/
+                //(List<StuActivity> datas, string continuationToken) = await ActivityStudentService.FindActivity(element, null, null, _azureCosmos, _azureRedis);
+
+                // string blob =  await StudyService.GenPdf(cname,sname,gname,"", _converter);
+
+            }
+            catch (CosmosException ex)
+            {
+                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-ServiceBus,GenPdfFunc()\n{ex.Message}\n{ex.StackTrace}\n\n{msg}", GroupNames.醍摩豆服務運維群組);
+            }
+
+        }
+
         /// <summary>
         /// 修复学生数据
         /// </summary>

+ 20 - 4
TEAMModelOS/Controllers/XTest/FixDataController.cs

@@ -41,6 +41,8 @@ using System.Formats.Asn1;
 using System.Xml.Linq;
 using DocumentFormat.OpenXml.Math;
 using OpenXmlPowerTools;
+using Top.Api;
+using DinkToPdf.Contracts;
 
 namespace TEAMModelOS.Controllers
 {
@@ -59,7 +61,8 @@ namespace TEAMModelOS.Controllers
         private readonly HttpTrigger _httpTrigger;
         private readonly CoreAPIHttpService _coreAPIHttpService;
         private readonly ScsStudyApisService _scsStudyApisService;
-        public FixDataController(IHttpClientFactory httpClient, HttpTrigger httpTrigger, AzureServiceBusFactory serviceBus, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, ScsStudyApisService scsStudyApisService)
+        private readonly IConverter _converter;
+        public FixDataController(IConverter converter,IHttpClientFactory httpClient, HttpTrigger httpTrigger, AzureServiceBusFactory serviceBus, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, ScsStudyApisService scsStudyApisService)
         {
             _azureCosmos = azureCosmos;
             _azureRedis = azureRedis;
@@ -72,6 +75,7 @@ namespace TEAMModelOS.Controllers
             _coreAPIHttpService = coreAPIHttpService;
             _httpClient = httpClient;
             _scsStudyApisService = scsStudyApisService;
+            _converter = converter;
         }
         /// <summary>
         ///
@@ -2763,9 +2767,21 @@ namespace TEAMModelOS.Controllers
 
             foreach (var g in group)
             {
-                var messageBlobPDF = new ServiceBusMessage(new { id = g.ToList().Select(x => x.id).ToHashSet(), school = g.Key, userType = "tmdid" }.ToJsonString());
-                var GenPdfQueue = _configuration.GetValue<string>("Azure:ServiceBus:GenPdfQueue");
-                await _serviceBus.GetServiceBusClient().SendMessageAsync(GenPdfQueue, messageBlobPDF);
+                //var messageBlobPDF = new ServiceBusMessage(new { id = g.ToList().Select(x => x.id).ToHashSet(), school = g.Key, userType = "tmdid", bizType = "OfflineRecord" }.ToJsonString());
+                //var GenPdfQueue = _configuration.GetValue<string>("Azure:ServiceBus:GenPdfQueue");
+                //await _serviceBus.GetServiceBusClient().SendMessageAsync(GenPdfQueue, messageBlobPDF);
+                string msg = new { id = g.ToList().Select(x => x.id).ToHashSet(), school = g.Key, userType = "tmdid", bizType = "OfflineRecord" }.ToJsonString();
+                JsonElement element = msg.ToObject<JsonElement>();
+                // https://dotblogs.com.tw/yc421206/2013/04/25/102300  // C#  原子操作。Interlocked
+                // ConcurrentQueue  http://t.zoukankan.com/hohoa-p-12622459.html
+                switch (true)
+                {
+                    case bool when element.TryGetProperty("bizType", out JsonElement _bizType) && $"{_bizType}".Equals("OfflineRecord"):
+                        //处理教师线下研修报告的生成。
+                        await FixDataService.GenOfflineRecordPdf(_azureCosmos,_dingDing,_azureStorage,_coreAPIHttpService,_converter,element, msg);
+                        break;
+                    
+                }
             }
             return Ok(group);
         }