123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867 |
- using Azure;
- using Azure.Cosmos;
- 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.Models.Cosmos.Common;
- using TEAMModelOS.Models;
- using Azure.Storage.Blobs.Models;
- 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>
- /// <param name="client"></param>
- /// <param name="_dingDing"></param>
- /// <param name="_azureStorage"></param>
- /// <param name="data"></param>
- /// <returns></returns>
- public static async Task<List<Student>> FixStudentInfo(CosmosClient client, DingDing _dingDing, AzureStorageFactory _azureStorage, JsonElement data)
- {
- var code = data.GetProperty("code").GetString();
- var ids = data.GetProperty("ids").ToObject<List<string>>();
- var dict = data.GetProperty("dict").ToObject<Dictionary<string, object>>();
- string queryText = $"SELECT VALUE c FROM c WHERE c.id IN ({string.Join(",", ids.Select(o => $"'{o}'"))})";
- List<Student> students = new List<Student>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Student")
- .GetItemQueryIterator<Student>(
- queryText: queryText,
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{code}") }))
- {
- foreach (var key in dict.Keys)
- {
- switch (key)
- {
- case "classId":
- item.classId = $"{ dict[key]}";
- break;
- case "periodId":
- item.periodId = $"{ dict[key]}";
- break;
- case "schoolId":
- item.schoolId = $"{ dict[key]}";
- break;
- case "year":
- int year = DateTime.Now.Year;
- int.TryParse($"dict[key]", out year);
- item.year = year;
- break;
- default:
- break;
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<Student>(item, item.id, new PartitionKey(item.code));
- students.Add(item);
- }
- }
- return students;
- }
- /// <summary>
- /// 修复内容模块数据
- /// </summary>
- /// <param name="client"></param>
- /// <param name="_dingDing"></param>
- /// <param name="_azureStorage"></param>
- /// <param name="data"></param>
- /// <returns></returns>
- public static async Task FixBlobContent(CosmosClient client, DingDing _dingDing, AzureStorageFactory _azureStorage, JsonElement data)
- {
- if (data.TryGetProperty("doPrivate", out JsonElement _doPrivate) && $"{_doPrivate}".Equals("yes", StringComparison.OrdinalIgnoreCase))
- {
- foreach (var cnt in _azureStorage.GetBlobServiceClient().GetBlobContainers())
- {
- if (cnt.Name.Length == 10 && int.TryParse(cnt.Name, out _))
- {
- await doFixBlob(client, _azureStorage, cnt.Name, "private");
- }
- }
- }
- List<School> schools = new List<School>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(item);
- }
- foreach (var school in schools)
- {
- await doFixBlob(client, _azureStorage, school.id, "school");
- }
- }
- private static async Task doFixBlob(CosmosClient client, AzureStorageFactory _azureStorage, string name, string scope)
- {
- List<string> prefixs = new List<string>() { "audio", "doc", "image", "other", "res", "video" };
- var ContainerClient = _azureStorage.GetBlobContainerClient($"{name}");
- var tb = "Teacher";
- if (scope != "private")
- {
- tb = "School";
- }
- List<string> ids = new List<string>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, tb).GetItemQueryIterator<Bloblog>(queryDefinition: new QueryDefinition("select c.id from c "), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Bloblog-{name}") }))
- {
- ids.Add(item.id);
- }
- await client.GetContainer(Constant.TEAMModelOS, tb).DeleteItemsStreamAsync(ids, $"Bloblog-{name}");
- long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- foreach (var prefix in prefixs)
- {
- if (prefix.Equals("res"))
- {
- List<string> itemres = await ContainerClient.List(prefix);
- if (itemres.IsNotEmpty())
- {
- HashSet<string> set = new HashSet<string>();
- itemres.ForEach(x =>
- {
- var uri = x.Split("/");
- set.Add($"res/{uri[1]}");
- });
- foreach (var item in set)
- {
- var urlsSize = await ContainerClient.GetBlobsSize(item);
- var url = item;
- if (!item.EndsWith(".hte", StringComparison.OrdinalIgnoreCase) && !item.EndsWith(".HTEX", StringComparison.OrdinalIgnoreCase))
- {
- url += ".HTEX";
- }
- Bloblog bloblog = new Bloblog { id = Guid.NewGuid().ToString(), code = $"Bloblog-{name}", pk = "Bloblog", time = now, url = url, size = urlsSize != null && urlsSize.HasValue ? urlsSize.Value : 0, type = prefix };
- await client.GetContainer(Constant.TEAMModelOS, tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code));
- }
- }
- }
- else
- {
- List<string> items = await ContainerClient.List(prefix);
- if (items.IsNotEmpty())
- {
- foreach (var item in items)
- {
- var urlsSize = await ContainerClient.GetBlobsSize(item);
- Bloblog bloblog = new Bloblog { id = Guid.NewGuid().ToString(), code = $"Bloblog-{name}", pk = "Bloblog", time = now, url = item, size = urlsSize != null && urlsSize.HasValue ? urlsSize.Value : 0, type = prefix };
- await client.GetContainer(Constant.TEAMModelOS, tb).UpsertItemAsync(bloblog, new Azure.Cosmos.PartitionKey(bloblog.code));
- }
- }
- }
- }
- }
- /// <summary>
- /// 修復學校基本資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixSchoolPeriodId(CosmosClient client, string schoolCode)
- {
- List<string> periodIdList = new List<string>();
- await foreach (School schinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: $"SELECT value(c) FROM c WHERE c.id = '{schoolCode}'", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- int periodIndex = 0;
- foreach (Period periodNow in schinfo.period)
- {
- if (periodNow.id.Equals("上學期") || periodNow.id.Equals("上学期") || periodNow.id.Equals("First semester"))
- {
- string periodId = Guid.NewGuid().ToString();
- schinfo.period[periodIndex].id = periodId;
- periodIdList.Add(periodId);
- }
- periodIndex++;
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<School>(schinfo, schinfo.id, new PartitionKey("Base"));
- }
- return periodIdList;
- }
- /// <summary>
- /// 修復學校班級資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixClassInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> classIdList = new List<string>();
- await foreach (Class classinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Class>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- classinfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Class>(classinfo, classinfo.id, new PartitionKey($"Class-{schoolCode}"));
- classIdList.Add(classinfo.id);
- }
- return classIdList;
- }
- /// <summary>
- /// 修復學校課程資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixCourseInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> courseIdList = new List<string>();
- await foreach (Course courseinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Course>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Course-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- courseinfo.period.id = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Course>(courseinfo, courseinfo.id, new PartitionKey($"Course-{schoolCode}"));
- courseIdList.Add(courseinfo.id);
- }
- return courseIdList;
- }
- /// <summary>
- /// 修復學校知識點資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixKnowledgeInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> knowledgeIdList = new List<string>();
- await foreach (Knowledge knowledgeinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Knowledge>(queryText: $"SELECT value(c) FROM c WHERE c.pk = 'Knowledge' AND c.owner = '{schoolCode}'", requestOptions: new QueryRequestOptions() { }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- knowledgeinfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Knowledge>(knowledgeinfo, knowledgeinfo.id, new PartitionKey($"{knowledgeinfo.code}"));
- knowledgeIdList.Add(knowledgeinfo.id);
- }
- return knowledgeIdList;
- }
- /// <summary>
- /// 修復學校試卷資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixPaperInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> paperIdList = new List<string>();
- await foreach (Paper paperinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Paper>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Paper-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- paperinfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Paper>(paperinfo, paperinfo.id, new PartitionKey($"Paper-{schoolCode}"));
- paperIdList.Add(paperinfo.id);
- }
- return paperIdList;
- }
- /// <summary>
- /// 修復學校課綱資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixVolumeInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> volumeIdList = new List<string>();
- await foreach (Volume volumeinfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<Volume>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Volume-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- volumeinfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<Volume>(volumeinfo, volumeinfo.id, new PartitionKey($"Volume-{schoolCode}"));
- volumeIdList.Add(volumeinfo.id);
- }
- return volumeIdList;
- }
- /// <summary>
- /// 修復學校試題資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixItemInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> itemIdList = new List<string>();
- await foreach (ItemInfo iteminfo in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<ItemInfo>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- iteminfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "School").ReplaceItemAsync<ItemInfo>(iteminfo, iteminfo.id, new PartitionKey($"Item-{schoolCode}"));
- itemIdList.Add(iteminfo.id);
- }
- return itemIdList;
- }
- /// <summary>
- /// 修復學校評測資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixExamInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> examIdList = new List<string>();
- await foreach (ExamInfo examinfo in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- examinfo.period.id = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(examinfo, examinfo.id, new PartitionKey($"Exam-{schoolCode}"));
- examIdList.Add(examinfo.id);
- }
- return examIdList;
- }
- /// <summary>
- /// 修復學生資料
- /// </summary>
- /// <param name="client"></param>
- /// <param name="schoolCode"></param>
- /// <param name="dataDic"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixStudentInfo(CosmosClient client, string schoolCode, Dictionary<string, string> dataDic)
- {
- List<string> studentIdList = new List<string>();
- await foreach (Student studentinfo in client.GetContainer(Constant.TEAMModelOS, "Student").GetItemQueryIterator<Student>(queryText: $"SELECT value(c) FROM c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-{schoolCode}") }))
- {
- foreach (KeyValuePair<string, string> item in dataDic)
- {
- switch (item.Key)
- {
- case "periodId":
- studentinfo.periodId = item.Value;
- break;
- }
- }
- await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<Student>(studentinfo, studentinfo.id, new PartitionKey($"Base-{schoolCode}"));
- studentIdList.Add(studentinfo.id);
- }
- return studentIdList;
- }
- /// <summary>
- /// 修復评测内容
- /// </summary>
- /// <param name="client"></param>
- /// <param name="data"></param>
- /// <returns></returns>
- public static async Task<List<string>> FixExamPublish(CosmosClient client, DingDing _dingDing, JsonElement data, Option _option)
- {
- List<string> infos = new List<string>();
- //var dict = data.GetProperty("publish").GetInt32();
- //List<(string id, string code)> ps = new List<(string id, string code)>();
- List<object> exams = new List<object>();
- List<Task<ItemResponse<ExamInfo>>> tasks = new List<Task<ItemResponse<ExamInfo>>>();
- try {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryStreamIterator(queryText: $"SELECT value(c) FROM c where c.pk = 'Exam' and c.publish = '0'" ))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- if (obj.TryGetProperty("publish", out JsonElement publish))
- {
- try
- {
- if (string.IsNullOrEmpty(publish.GetString()) || publish.GetString().Equals("0"))
- {
- ExamInfo examInfo = new ExamInfo
- {
- id = obj.GetProperty("id").GetString(),
- owner = obj.TryGetProperty("owner", out JsonElement owner) ? owner.GetString() : "",
- code = obj.TryGetProperty("code", out JsonElement code) ? code.GetString() : "",
- //examInfo.owner = obj.GetProperty("owner").GetString();
- name = obj.GetProperty("name").GetString(),
- school = obj.GetProperty("school").GetString(),
- creatorId = obj.GetProperty("creatorId").GetString(),
- stuCount = obj.TryGetProperty("stuCount", out JsonElement stuCount) ? stuCount.GetInt32() : 0,
- createTime = obj.GetProperty("createTime").GetInt64(),
- updateTime = obj.TryGetProperty("updateTime", out JsonElement updateTime) ? updateTime.GetInt64() : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- startTime = obj.TryGetProperty("startTime", out JsonElement startTime) ? startTime.GetInt64() : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- endTime = obj.TryGetProperty("endTime", out JsonElement endTime) ? endTime.GetInt64() : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
- year = obj.TryGetProperty("year", out JsonElement year) ? year.GetInt32() : 0,
- source = obj.TryGetProperty("source", out JsonElement source) ? source.GetString() : "0",
- classes = obj.TryGetProperty("classes", out JsonElement classes) ? classes.ToObject<List<string>>() : new List<string>(),
- stuLists = obj.TryGetProperty("stuLists", out JsonElement stuLists) ? stuLists.ToObject<List<string>>() : new List<string>(),
- //examInfo.stuLists = obj.GetProperty("stuLists").ToObject<List<string>>();
- papers = obj.TryGetProperty("papers", out JsonElement papers) ? papers.ToObject<List<PaperSimple>>() : new List<PaperSimple>(),
- type = obj.TryGetProperty("type", out JsonElement type) ? type.GetString() : "",
- period = obj.TryGetProperty("period", out JsonElement period) ? period.ToObject<PeriodSimple>() : new PeriodSimple(),
- grades = obj.TryGetProperty("grades", out JsonElement grades) ? grades.ToObject<List<Grade>>() : new List<Grade>(),
- subjects = obj.GetProperty("subjects").ToObject<List<ExamSubject>>(),
- progress = obj.TryGetProperty("progress", out JsonElement progress) ? progress.GetString() : "finish",
- scope = obj.TryGetProperty("scope", out JsonElement scope) ? scope.GetString() : "school",
- examType = obj.TryGetProperty("examType", out JsonElement examType) ? examType.ToObject<Custom>() : new Custom(),
- status = obj.TryGetProperty("status", out JsonElement status) ? status.GetInt32() : 0,
- average = obj.TryGetProperty("average", out JsonElement average) ? average.GetDouble() : 0,
- sRate = obj.TryGetProperty("sRate", out JsonElement sRate) ? sRate.GetDouble() : 0,
- lostStu = obj.TryGetProperty("lostStu", out JsonElement lostStu) ? lostStu.ToObject<List<string>>() : new List<string>(),
- standard = obj.TryGetProperty("standard", out JsonElement standard) ? standard.GetDouble() : 0,
- size = obj.TryGetProperty("size", out JsonElement size) ? size.GetInt64() : 0,
- income = obj.TryGetProperty("income", out JsonElement income) ? income.GetInt32() : 0,
- touch = obj.TryGetProperty("touch", out JsonElement touch) ? touch.GetInt32() : 0,
- publish = 0,
- groupLists = obj.TryGetProperty("groupLists", out JsonElement groupLists) ? groupLists.ToObject<List<Dictionary<string, List<string>>>>() : new List<Dictionary<string, List<string>>>(),
- targets = obj.TryGetProperty("targets", out JsonElement targets) ? targets.ToObject<List<JsonElement>>() : new List<JsonElement>()
- };
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(examInfo, examInfo.id, new PartitionKey(examInfo.code)));
- infos.Add(examInfo.id);
- };
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location} /fix-data/fix-publish \n {ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- }
- }
- }
- }
- //await Task.WhenAll(tasks);
- int pagesize = 50;
- if (tasks.Count <= pagesize)
- {
- await Task.WhenAll(tasks);
- }
- else
- {
- int pages = (tasks.Count + pagesize) / pagesize; //256是批量操作最大值,pages = (total + max -1) / max;
- for (int i = 0; i < pages; i++)
- {
- var listssb = tasks.Skip((i) * pagesize).Take(pagesize).ToList();
- await Task.WhenAll(listssb);
- }
- }
- } catch (Exception e) {
- await _dingDing.SendBotMsg($"OS,{_option.Location} /fix-data/fix-publish \n {e.Message}\n{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
-
- /*foreach (var item in exams) {
- dynamic dyn = JsonConvert.DeserializeObject(Convert.ToString(item)) ;
- foreach (var obj in dyn)
- {
- if (obj.Name == "publish")
- {
- obj.Value = 0;
- break;
- }
- }
- ExamInfo info = new ExamInfo();
- try {
- string dy = JsonConvert.SerializeObject(dyn);
- info = JsonConvert.DeserializeObject<ExamInfo>(dy);
- } catch (Exception e ) {
- //string dy = JsonConvert.SerializeObject(dyn);
- }
-
- //await client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(dyn, dyn.id, new PartitionKey(dyn.code));
- infos.Add(info.id);
- }*/
- return infos;
- }
- public static async Task<List<string>> FixExamClassResult(CosmosClient client, JsonElement data, DingDing _dingDing, CoreAPIHttpService _coreAPIHttpService, Option _option)
- {
- List<ExamClassResult> results = new List<ExamClassResult>();
- List<string> ids = new List<string>();
- List<Task<ItemResponse<ExamClassResult>>> tasks = new List<Task<ItemResponse<ExamClassResult>>>();
- List<Task<ItemResponse<ExamInfo>>> taskInfo = new List<Task<ItemResponse<ExamInfo>>>();
- try
- {
- /*await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamClassResult>(queryText: $"SELECT value(c) FROM c where c.pk = 'ExamClassResult' and c._ts >= 1640966400"))
- {
- results.Add(item);
- //await Task.WhenAll(tasks);
- }
- HashSet<string> examIds = new HashSet<string>();
- foreach (var item in results)
- {
- ids.Add(item.id);
- examIds.Add(item.examId);
- List<int> status = new List<int>();
- //List<string> classIds = new List<string>();
- //classIds.Add(item.info.id);
- if (item.status.Count == 0)
- {
- if (item.studentAnswers.Count > 0)
- {
- foreach (var answer in item.studentAnswers)
- {
- if (answer.Count == 0)
- {
- item.status.Add(1);
- }
- else
- {
- item.status.Add(0);
- }
- }
- }
- }
- else
- {
- List<int> vs = new();
- foreach (int st in item.status)
- {
- var ans = (st == -2) ? 1 : 0;
- vs.Add(ans);
- }
- item.status = vs;
- }
- *//*if (item.progress == true) {
- int n = 0;
- foreach (string sta in item.studentIds)
- {
- for (int i = 0; i < item.studentScores[n].Count; i++)
- {
- if (item.studentScores[n][i] == -1)
- {
- item.studentScores[n][i] = 0;
- }
- }
- n++;
- }
- }*//*
-
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamClassResult>(item, item.id, new PartitionKey(item.code)));
- }*/
- List<ExamInfo> info = new List<ExamInfo>();
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<ExamInfo>(queryText: $"SELECT value(c) FROM c where c.pk = 'Exam' and c.progress = 'finish' and c._ts >= 1640966400"))
- {
- info.Add(item);
- //await Task.WhenAll(tasks);
- }
- foreach (var item in info) {
- item.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- taskInfo.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<ExamInfo>(item, item.id, new PartitionKey(item.code)));
- }
- //TODO 数据量过大的时候暂未处理
- await Task.WhenAll(taskInfo);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location} /fix-data/fix-classIds \n {ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- return ids;
- }
- public static async Task<List<string>> FixSchoolType(CosmosClient client, JsonElement data, DingDing _dingDing, CoreAPIHttpService _coreAPIHttpService, Option _option)
- {
- List<Task<ItemResponse<School>>> tasks = new List<Task<ItemResponse<School>>>();
- List<School> info = new List<School>() ;
- try
- {
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<School>(queryText: $"SELECT value(c) FROM c ",requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- info.Add(item);
- }
- foreach (var item in info)
- {
- foreach (var period in item.period) {
-
- }
- tasks.Add(client.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<School>(item, item.id, new PartitionKey(item.code)));
- }
- //TODO 数据量过大的时候暂未处理
- await Task.WhenAll(tasks);
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location} /fix-data/fix-type \n {ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- }
- var ids = info.Select(x => x.id).ToList();
- return ids;
- }
- }
- }
|