123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.Models.Cosmos;
- using TEAMModelOS.SDK.Extension;
- using Azure.Cosmos;
- using TEAMModelOS.SDK.DI;
- using HTEXLib.COMM.Helpers;
- using System.Text;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.Common.Inner;
- using StackExchange.Redis;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- namespace TEAMModelOS.SDK.Services
- {
- public static class ActivityStudentService
- {
- public static async Task<(int msgid, int taskStatus)> Decide(DingDing _dingDing, Option _option, JsonElement request, AzureCosmosFactory _azureCosmos, AzureRedisFactory _azureRedis,
- AzureStorageFactory _azureStorage, string userid, string school, string standard, AzureServiceBusFactory _serviceBus, Microsoft.Extensions.Configuration.IConfiguration _configuration)
- {
- Vote vote = null;
- DateTimeOffset now = DateTimeOffset.UtcNow;
- long curr = now.ToUnixTimeMilliseconds();
- byte msgid = 0;//0投票失败,1投票成功,2不在时间范围内,3不在发布范围内,4投票周期内重复投票,5周期内的可投票数不足,6未设置投票项
- int taskStatus = 0;
- //活动id
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return (msgid, -1);
- }
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code))
- {
- return (msgid, taskStatus);
- }
- Dictionary<string, int> option = new Dictionary<string, int>();
- if (request.TryGetProperty("option", out JsonElement joption))
- {
- option = joption.ToObject<Dictionary<string, int>>();
- if (option.IsEmpty())
- {
- msgid = 6;
- return (msgid, -1);
- }
- }
- else
- {
- return (msgid, -1);
- }
- try
- {
- //1.再次检查投票
- var client = _azureCosmos.GetCosmosClient();
- ///TODO 检查是否在投票范围内,包括在tmdids 及班级 但是需要处理认证金钥中的班级问题
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Vote>(queryText: $"select c.id,c.code ,c.school,c.creatorId,c.scope , c.progress,c.times,c.voteNum,c.startTime,c.endTime from c where c.id = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- vote = item;
- break;
- }
- if (vote != null)
- {
- //判断投票时间是否在起止时间内
- if (curr >= vote.startTime && curr <= vote.endTime)
- {
- string endField = null;
- string Field = "";
- var endDtae = DateTimeOffset.FromUnixTimeMilliseconds(vote.endTime);
- RedisValue value;
- switch (vote.times)
- {
- case "once":
- // //如果是只能投票一次的活动则直接获取Redis的第一条 只能投一次
- Field = $"{userid}-once";
- HashEntry[] values = _azureRedis.GetRedisClient(8).HashGetAll($"Vote:Record:{vote.id}");
- if (values != null && values.Length > 0)
- {
- value = new RedisValue();
- foreach (var val in values)
- {
- if (val.Name.ToString() == Field)
- {
- value = val.Value;
- break;
- }
- }
- msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, "once");
- }
- else
- {
- msgid = await VoteIng(vote, new RedisValue(), msgid, option, Field, curr, _azureRedis, userid, vote.times, "once");
- }
- if (msgid == 1) { taskStatus = 1; }
- break;
- case "day": //周期内每天
- Field = $"{userid}-day-{now.ToString("yyyyMMdd")}";
- endField = $"{userid}-day-{endDtae.ToString("yyyyMMdd")}";
- if (Field.Equals(endField))
- {
- taskStatus = 1;
- }
- value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field);
- msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyyMMdd"));
- break;
- case "week": //自然周
- int week = GetWeek(now);
- int endweek = GetWeek(endDtae);
- Field = $"{userid}-week-{now.ToString("yyyy")}{week}";
- endField = $"{userid}-week-{endDtae.ToString("yyyy")}{endweek}";
- if (Field.Equals(endField))
- {
- taskStatus = 1;
- }
- value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field);
- msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, $"{now.ToString("yyyy")}{week}");
- break;
- case "month": //月份
- Field = $"{userid}-month-{now.ToString("yyyyMM")}";
- endField = $"{userid}-month-{endDtae.ToString("yyyyMM")}";
- if (Field.Equals(endField))
- {
- taskStatus = 1;
- }
- value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field);
- msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyyMM"));
- break;
- case "year"://年份
- Field = $"{userid}-year-{now.ToString("yyyy")}";
- endField = $"{userid}-year-{endDtae.ToString("yyyy")}";
- if (Field.Equals(endField))
- {
- taskStatus = 1;
- }
- value = _azureRedis.GetRedisClient(8).HashGet($"Vote:Record:{vote.id}", Field);
- msgid = await VoteIng(vote, value, msgid, option, Field, curr, _azureRedis, userid, vote.times, now.ToString("yyyy"));
- break;
- }
- }
- else
- {
- msgid = 2;
- }
- try
- {
- if (!string.IsNullOrEmpty(school))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(vote.id, new PartitionKey($"Activity-{school}-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, vote.id, new PartitionKey($"Activity-{school}-{userid}"));
- }
- else
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(vote.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, vote.id, new PartitionKey($"Activity-{userid}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Status == 404)
- {
- try
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(vote.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, vote.id, new PartitionKey($"Activity-{userid}"));
- }
- catch (CosmosException cex)
- {
- try
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(vote.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, vote.id, new PartitionKey($"Activity-{userid}"));
- if (!string.IsNullOrEmpty(standard) && !string.IsNullOrEmpty(school))
- {
- await StatisticsService.SendServiceBus(($"{standard}", new List<string> { $"{userid}" }, $"{school}", new List<string> { StatisticsService.TeacherVote }, 0), _configuration, _serviceBus, client);
- }
- }
- catch (CosmosException cosex)
- {
- taskStatus = -1;
- }
- }
- }
- }
- }
- else
- {
- return (msgid, -1);
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"OS,{_option.Location},common/delete-activity\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- throw new Exception(ex.StackTrace);
- }
- if (msgid == 1 && vote != null)
- {
- string blobcntr = null;
- if (vote.scope.Equals("school"))
- {
- blobcntr = vote.school;
- }
- else
- {
- blobcntr = vote.creatorId;
- }
- //获取投票活动的所有投票记录
- var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Vote:Record:{vote.id}");
- //获取投票活动的选项及投票数
- var counts = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Vote:Count:{vote.id}");
- List<dynamic> countcds = new List<dynamic>();
- if (counts != null && counts.Length > 0)
- {
- foreach (var count in counts)
- {
- countcds.Add(new { code = count.Element.ToString(), count = (int)count.Score });
- }
- }
- List<Task<string>> tasks = new List<Task<string>>();
- List<VoteRecord> recordsBlob = new List<VoteRecord>();
- foreach (var rcd in records)
- {
- var value = rcd.Value.ToString().ToObject<VoteRecord>();
- recordsBlob.Add(value);
- }
- //分组每个人的
- var gp = recordsBlob.GroupBy(x => x.userid).Select(x => new { key = x.Key, list = x.ToList() });
- var userdata = gp.Where(x => x.key.Equals(userid)).FirstOrDefault();
- if (userdata != null)
- {
- tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, userdata.list.ToJsonString(), "vote", $"{vote.id}/urecord/{userdata.key}.json"));
- }
- //处理活动方的记录,
- string url = $"/vote/{vote.id}/record.json";
- tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, new { options = countcds, records = recordsBlob }.ToJsonString(), "vote", $"{vote.id}/record.json"));
- }
- return (msgid, taskStatus);
- }
- public static async Task<byte> VoteIng(Vote vote, RedisValue value, byte msgid, Dictionary<string, int> option, string Field, long curr, AzureRedisFactory _azureRedis, string userid, string times, string endpoint)
- {
- if (!value.IsNullOrEmpty)
- {
- VoteRecord record = value.ToString().ToObject<VoteRecord>();
- int addCount = 0;
- foreach (var op in option)
- {
- addCount += op.Value;
- }
- int crdCount = 0;
- foreach (var op in record.opt)
- {
- crdCount += op.Value;
- }
- //处理记录投票+当前设置的投票是否小于等于周期内最大投票数
- if (addCount + crdCount <= vote.voteNum)
- {
- foreach (var op in option)
- {
- if (record.opt.ContainsKey(op.Key))
- {
- record.opt[op.Key] = record.opt[op.Key] + op.Value;
- }
- else
- {
- record.opt.Add(op.Key, op.Value);
- }
- }
- record.time = curr;
- record.userid = userid;
- record.times = times;
- record.endpoint = endpoint;
- //保存投票记录
- bool status = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}", Field, record.ToJsonString());
- //单独保存每个人方便查询的记录
- bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}:{userid}", Field, record.ToJsonString());
- //当前投票分组计数存入活动的Redis
- foreach (var opt in option)
- {
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Vote:Count:{vote.id}", opt.Key, opt.Value);
- }
- msgid = 1;
- }
- else
- {
- msgid = 5;
- }
- }
- else
- {
- if (option.Count <= vote.voteNum)
- {
- //保存投票记录
- VoteRecord record = new VoteRecord { opt = option, time = curr, userid = userid, times = times, endpoint = endpoint };
- bool status = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}", Field, record.ToJsonString());
- //单独保存每个人方便查询的记录
- bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"Vote:Record:{vote.id}:{userid}", Field, record.ToJsonString());
- //当前投票分组计数存入活动的Redis
- foreach (var opt in option)
- {
- await _azureRedis.GetRedisClient(8).SortedSetIncrementAsync($"Vote:Count:{vote.id}", opt.Key, opt.Value);
- }
- if (status)
- {
- msgid = 1;
- }
- }
- else
- {
- msgid = 5;
- }
- }
- return msgid;
- }
- /// <summary>
- /// 获取时间的在当年的第几周
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public static int GetWeek(DateTimeOffset dt)
- {
- DateTimeOffset time = Convert.ToDateTime(dt.ToString("yyyy") + "-01-01");
- TimeSpan ts = dt - time;
- int iii = (int)time.DayOfWeek;
- int day = int.Parse(ts.TotalDays.ToString("F0"));
- if (iii == 0)
- {
- day--;
- }
- else
- {
- day = day - (7 - iii) - 1;
- }
- int week = ((day + 7) / 7) + 1;
- return week;
- }
- public static async Task<(List<StuActivity> datas, string continuationToken)> FindActivity(JsonElement request, string id, string school, AzureCosmosFactory _azureCosmos, AzureRedisFactory azureRedis)
- {
- if (string.IsNullOrWhiteSpace(id))
- {
- if (request.TryGetProperty("userid", out JsonElement userid))
- {
- if (!userid.ValueKind.Equals(JsonValueKind.Undefined) && !userid.ValueKind.Equals(JsonValueKind.Null) && userid.ValueKind.Equals(JsonValueKind.String))
- {
- id = userid.GetString();
- }
- }
- }
- if (string.IsNullOrWhiteSpace(school))
- {
- if (request.TryGetProperty("school", out JsonElement schooljson))
- {
- if (!schooljson.ValueKind.Equals(JsonValueKind.Undefined) && !schooljson.ValueKind.Equals(JsonValueKind.Null) && schooljson.ValueKind.Equals(JsonValueKind.String))
- {
- school = schooljson.GetString();
- }
- }
- }
- /// tmdid, schoolid
- var userType = "tmdid";
- if (request.TryGetProperty("userType", out JsonElement usertype))
- {
- if (!usertype.ValueKind.Equals(JsonValueKind.Undefined) && !usertype.ValueKind.Equals(JsonValueKind.Null) && usertype.ValueKind.Equals(JsonValueKind.String))
- {
- userType = usertype.GetString();
- }
- }
- string stimesql = "";
- //开始时间,默认最近三十天
- if (request.TryGetProperty("stime", out JsonElement stime))
- {
- if (!stime.ValueKind.Equals(JsonValueKind.Undefined) && !stime.ValueKind.Equals(JsonValueKind.Null) && stime.TryGetInt64(out long data))
- {
- stimesql = $" and c.startTime >= {data} ";
- }
- }
- string source = "";
- //评测类型
- if (request.TryGetProperty("source", out JsonElement sc))
- {
- source = $" and c.source = '{sc}' ";
- }
- string owner = "";
- //评测来源
- if (request.TryGetProperty("owner", out JsonElement element))
- {
- owner = $" and c.owner = '{element}' ";
- }
- string name = "";
- //评测来源
- if (request.TryGetProperty("name", out JsonElement jsonElement))
- {
- name = $" and Contains( c.name , '{jsonElement}') = true ";
- }
- //默认当前时间, 未开始的不能查询
- var etimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- string etimesql = $" and c.startTime <= {etimestamp} ";
- var typesql = "";
- if (request.TryGetProperty("type", out JsonElement type))
- {
- if (!type.ValueKind.Equals(JsonValueKind.Undefined) && !type.ValueKind.Equals(JsonValueKind.Null) && type.ValueKind.Equals(JsonValueKind.String))
- {
- typesql = $" and c.type='{type}' ";
- }
- }
- string token = default;
- //默认不指定返回大小
- int? topcout = null;
- if (request.TryGetProperty("count", out JsonElement jcount))
- {
- if (!jcount.ValueKind.Equals(JsonValueKind.Undefined) && !jcount.ValueKind.Equals(JsonValueKind.Null) && jcount.TryGetInt32(out int data))
- {
- topcout = data;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (topcout != null && topcout.Value > 0)
- {
- iscontinuation = true;
- }
- //如果指定了返回大小
- if (request.TryGetProperty("continuationToken", out JsonElement token_1))
- {
- //指定了cancellationToken continuationSchool
- if (!token_1.ValueKind.Equals(JsonValueKind.Null) && token_1.ValueKind.Equals(JsonValueKind.String))
- {
- token = token_1.GetString();
- }
- }
- //科目
- string joinSqlSubjects = "";
- string andSqlSubjects = "";
- if (request.TryGetProperty("subjects", out JsonElement jsubjects))
- {
- if (jsubjects.ValueKind is JsonValueKind.Array)
- {
- List<string> subjects = jsubjects.ToObject<List<string>>();
- if (subjects.IsNotEmpty())
- {
- joinSqlSubjects = " join A2 in c.subjects ";
- List<string> sqlList = new List<string>();
- subjects.ForEach(x => { sqlList.Add($" '{x}' "); });
- string sql = string.Join(" , ", sqlList);
- andSqlSubjects = $" and A2 in ({sql}) ";
- }
- }
- }
- List<StuActivity> datas = new List<StuActivity>();
- var client = _azureCosmos.GetCosmosClient();
- string containerId = "Student";
- string PartitionKey = "";
- if (!string.IsNullOrWhiteSpace(school) && userType.Equals("schoolid"))
- {
- containerId = "Student";
- PartitionKey = $"Activity-{school}-{id}";
- }
- else
- {
- containerId = "Student";
- PartitionKey = $"Activity-{id}";
- }
- string querySchool = $" SELECT value c FROM c {joinSqlSubjects} where c.pk='Activity' {stimesql} {etimesql} {typesql} {andSqlSubjects} {source} {owner} {name} order by c.createTime desc";
- //查询数据归属学校的
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, containerId).GetItemQueryStreamIterator(querySchool, continuationToken: token,
- requestOptions: new QueryRequestOptions() { MaxItemCount = topcout, PartitionKey = new PartitionKey(PartitionKey) }))
- {
- 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())
- {
- datas.Add(obj.ToObject<StuActivity>());
- }
- }
- //如果需要分页则跳出
- if (iscontinuation)
- {
- token = item.GetContinuationToken();
- break;
- }
- }
- List<StuActivity> results = datas.Where((x, i) => datas.FindIndex(z => z.id == x.id && z.code == x.code) == i).ToList();
- return (results, token);
- }
- public static async Task<(int msgid, int taskStatus)> Answer(DingDing _dingDing, Option _option, JsonElement request, AzureCosmosFactory _azureCosmos, AzureRedisFactory azureRedis, string userid, string school, AzureStorageFactory _azureStorage, string standard, AzureServiceBusFactory _serviceBus, Microsoft.Extensions.Configuration.IConfiguration _configuration)
- {
- DateTimeOffset now = DateTimeOffset.UtcNow;
- long curr = now.ToUnixTimeMilliseconds();
- int msgid = 0;//
- int taskStatus = 0;
- //活动id
- if (!request.TryGetProperty("id", out JsonElement id))
- {
- return (msgid, -1);
- }
- //活动分区
- if (!request.TryGetProperty("code", out JsonElement code))
- {
- return (msgid, -1);
- }
- try
- {
- //1.再次检查投票
- var client = _azureCosmos.GetCosmosClient();
- Survey survey = null;
- ///TODO 检查是否在投票范围内,包括在tmdids 及班级 但是需要处理认证金钥中的班级问题
- await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Common").GetItemQueryIterator<Survey>(queryText: $"select c.id,c.owner,c.scope, c.code ,c.creatorId,c.answers ,c.school , c.progress,c.times,c.startTime,c.endTime from c where c.id = '{id}'",
- requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{code}") }))
- {
- survey = item;
- break;
- }
- if (survey != null)
- {
- //判断投票时间是否在起止时间内
- if (curr >= survey.startTime && curr <= survey.endTime)
- {
- if (request.TryGetProperty("record", out JsonElement _record))
- {
- var recs = _record.ToObject<List<List<string>>>();
- if (recs.IsNotEmpty() && recs.Count == survey.answers.Count)
- {
- //处理问卷调查表的每一题选项数
- // List<Task<string>> tasks = new List<Task<string>>();
- for (int index = 0; index < recs.Count; index++)
- {
- Dictionary<string, int> dict = new Dictionary<string, int>();
- if (recs[index].IsNotEmpty())
- {
- recs[index].ForEach(x =>
- {
- if (survey.answers[index].Contains(x))
- {
- if (dict.ContainsKey(x))
- {
- dict[x] = dict[x] + 1;
- }
- else
- {
- dict[x] = 1;
- }
- }
- else
- {
- if (dict.ContainsKey("other"))
- {
- dict["other"] = dict["other"] + 1;
- }
- else
- {
- dict["other"] = 1;
- }
- //这里暂不处理, 结算再处理other
- // tasks.Add(_azureStorage.UploadFileByContainer(survey.owner,new { other=x, userid, time =curr }.ToJsonString(), "survey", $"{survey.id}/other/{index}/{userid}.json", false));
- }
- });
- }
- var value = azureRedis.GetRedisClient(8).HashGet($"Survey:Record:{survey.id}", index);
- if (value != default && !value.IsNullOrEmpty)
- {
- Dictionary<string, int> dt = value.ToString().ToObject<Dictionary<string, int>>();
- foreach (var kp in dict)
- { //不建议放在reids
- if (dt.ContainsKey(kp.Key))
- {
- dt[kp.Key] = dt[kp.Key] + kp.Value;
- }
- else
- {
- dt.Add(kp.Key, kp.Value);
- }
- }
- await azureRedis.GetRedisClient(8).HashSetAsync($"Survey:Record:{survey.id}", index, dt.ToJsonString());
- }
- else
- {
- await azureRedis.GetRedisClient(8).HashSetAsync($"Survey:Record:{survey.id}", index, dict.ToJsonString());
- }
- }
- //处理other ,这里暂不处理, 结算再处理other
- //await Task.WhenAll(tasks);
- //保存当前提交人的记录
- string blobcntr = null;
- if (survey.scope.Equals("school"))
- {
- blobcntr = survey.school;
- }
- else
- {
- blobcntr = survey.creatorId;
- }
- await _azureStorage.UploadFileByContainer(blobcntr, new SurveyRecord { ans = recs, userid = userid, time = curr }.ToJsonString(), "survey", $"{survey.id}/urecord/{userid}.json");
- ///bgn 20210805 huanghb 实时结算
- await azureRedis.GetRedisClient(8).SetAddAsync($"Survey:Submit:{survey.id}", userid);
- var submits = await azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
- List<dynamic> userids = new List<dynamic>();
- foreach (var submit in submits)
- {
- var value = submit.ToString();
- userids.Add(value);
- }
- List<QuestionRecord> questionRecords = new List<QuestionRecord>();
- //结算每道题的答题情况
- var ContainerClient = _azureStorage.GetBlobContainerClient(blobcntr);
- List<Task<string>> tasks = new List<Task<string>>();
- List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
- List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
- foreach (string item in items)
- {
- var Download = await _azureStorage.GetBlobContainerClient(blobcntr).GetBlobClient(item).DownloadAsync();
- var json = await JsonDocument.ParseAsync(Download.Value.Content);
- var Record = json.RootElement.ToObject<SurveyRecord>();
- surveyRecords.Add(Record);
- }
- for (int index = 0; index < survey.answers.Count; index++)
- {
- string url = $"{survey.id}/qrecord/{index}.json";
- QuestionRecord question = new QuestionRecord() { index = index };
- foreach (SurveyRecord record in surveyRecords)
- {
- if (record.ans.Count == survey.answers.Count)
- {
- foreach (var an in record.ans[index])
- {
- //
- if (question.opt.ContainsKey(an))
- {
- if (question.opt[an] != null)
- {
- question.opt[an].Add(record.userid);
- }
- else
- {
- question.opt[an] = new HashSet<string>() { record.userid };
- }
- }
- else
- {
- if (survey.answers[index].Contains(an))
- {
- //如果是客观题code
- question.opt.Add(an, new HashSet<string> { record.userid });
- }
- else
- {
- //如果不是客观code
- question.other[record.userid] = an;
- }
- }
- }
- }
- }
- questionRecords.Add(question);
- tasks.Add(_azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
- }
- var records = await azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
- List<dynamic> recds = new List<dynamic>();
- foreach (var rcd in records)
- {
- var value = rcd.Value.ToString().ToObject<JsonElement>();
- recds.Add(new { index = rcd.Name.ToString(), ans = value });
- }
- await Task.WhenAll(tasks);
- var cods = new { records = recds, userids, question = questionRecords, urecord = surveyRecords };
- //问卷整体情况
- await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
- ///end 20210805 huanghb 实时结算
- taskStatus = 1;
- msgid = 1;
- }
- else
- {
- //提交的作答不符合问卷的答案长度。
- msgid = 3;
- }
- }
- }
- else
- {
- msgid = 2;
- }
- try
- {
- if (!string.IsNullOrEmpty(school))
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(survey.id, new PartitionKey($"Activity-{school}-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, survey.id, new PartitionKey($"Activity-{school}-{userid}"));
- }
- else
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(survey.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, survey.id, new PartitionKey($"Activity-{userid}"));
- }
- }
- catch (CosmosException ex)
- {
- if (ex.Status == 404)
- {
- try
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<StuActivity>(survey.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<StuActivity>(activity, survey.id, new PartitionKey($"Activity-{userid}"));
- }
- catch (CosmosException cex)
- {
- if (cex.Status == 404)
- {
- try
- {
- StuActivity activity = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<StuActivity>(survey.id, new PartitionKey($"Activity-{userid}"));
- activity.taskStatus = taskStatus;
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<StuActivity>(activity, survey.id, new PartitionKey($"Activity-{userid}"));
- if (!string.IsNullOrEmpty(standard) && !string.IsNullOrEmpty(school))
- {
- await StatisticsService.SendServiceBus(($"{standard}", new List<string> { $"{userid}" }, $"{school}", new List<string> { StatisticsService.TeacherSurvey }, 0), _configuration, _serviceBus, client);
- }
- }
- catch (CosmosException cosex)
- {
- if (cosex.Status == 404)
- {
- taskStatus = -1;
- }
- }
- }
- }
- }
- }
- }
- else
- {
- return (msgid, -1);
- }
- }
- catch (Exception e)
- {
- throw new Exception(e.StackTrace);
- }
- return (msgid, taskStatus);
- }
- public class RdsRecord
- {
- public Dictionary<string, int> srecord { get; set; } = new Dictionary<string, int>();
- public Dictionary<string, string[]> urecord { get; set; } = new Dictionary<string, string[]>();
- }
- }
- }
|