瀏覽代碼

解决Students导入bug.,

CrazyIter_Bin 4 年之前
父節點
當前提交
500ce6482a

+ 232 - 218
TEAMModelFunction/TriggerSurvey.cs

@@ -25,260 +25,274 @@ namespace TEAMModelFunction
         public static async void Trigger( AzureServiceBusFactory _serviceBus, AzureStorageFactory _azureStorage, DingDing _dingDing,
                CosmosClient client, Document input, TriggerData tdata,AzureRedisFactory _azureRedis)
         {
-            if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
-            {
-                return;
-            }
-            var adid = tdata.id;
-            var adcode = "";
-            string blobcntr = null;
-            if (tdata.scope == "school")
-            {
-                  adcode = $"Activity-{tdata.school}";
-                blobcntr = tdata.school;
-            }
-            else if (tdata.scope == "private"){
-                adcode = $"Activity-{tdata.creatorId}";
-                 blobcntr = tdata.creatorId;
-            }
-            Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
-            List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
-            if (survey != null) {
-                switch (survey.progress)
+            try {
+                if ((tdata.status != null && tdata.status.Value == 404) || tdata.ttl > 0)
+                {
+                    return;
+                }
+                var adid = tdata.id;
+                var adcode = "";
+                string blobcntr = null;
+                if (tdata.scope == "school")
+                {
+                    adcode = $"Activity-{tdata.school}";
+                    blobcntr = tdata.school;
+                }
+                else if (tdata.scope == "private")
                 {
-                    case "pending":
-                        var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
-                        messageSurvey.ApplicationProperties.Add("name", "Survey");
-                        if (changeRecords.Count > 0)
-                        {
-                            await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                            long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                            changeRecords[0].sequenceNumber = start;
-                            await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                        }
-                        else
-                        {
-                            long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
-                            ChangeRecord changeRecord = new ChangeRecord
+                    adcode = $"Activity-{tdata.creatorId}";
+                    blobcntr = tdata.creatorId;
+                }
+                Survey survey = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<Survey>(input.Id, new Azure.Cosmos.PartitionKey($"{tdata.code}"));
+                List<ChangeRecord> changeRecords = await _azureStorage.FindListByDict<ChangeRecord>(new Dictionary<string, object>() { { "RowKey", input.Id }, { "PartitionKey", survey.progress } });
+                if (survey != null)
+                {
+                    switch (survey.progress)
+                    {
+                        case "pending":
+                            var messageSurvey = new ServiceBusMessage(new { id = input.Id, progress = "going", code = tdata.code }.ToJsonString());
+                            messageSurvey.ApplicationProperties.Add("name", "Survey");
+                            if (changeRecords.Count > 0)
                             {
-                                RowKey = input.Id,
-                                PartitionKey = "pending",
-                                sequenceNumber = start,
-                                msgId = messageSurvey.MessageId
-                            };
-                            await _azureStorage.Save<ChangeRecord>(changeRecord);
-                        }
-                        break;
-                    case "going":
-                        (List<string> tmdids,List<Students> students) =   await TriggerStuActivity. GetStuList(client, _dingDing, survey.classes, survey.school);
+                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
+                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
+                                changeRecords[0].sequenceNumber = start;
+                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
+                            }
+                            else
+                            {
+                                long start = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurvey, DateTimeOffset.FromUnixTimeMilliseconds(tdata.stime));
+                                ChangeRecord changeRecord = new ChangeRecord
+                                {
+                                    RowKey = input.Id,
+                                    PartitionKey = "pending",
+                                    sequenceNumber = start,
+                                    msgId = messageSurvey.MessageId
+                                };
+                                await _azureStorage.Save<ChangeRecord>(changeRecord);
+                            }
+                            break;
+                        case "going":
+                            (List<string> tmdids, List<Students> students) = await TriggerStuActivity.GetStuList(client, _dingDing, survey.classes, survey.school);
 #if DEBUG
-                        await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入学生表作为活动列表!", GroupNames.成都开发測試群組);
+                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入学生表作为活动列表!", GroupNames.成都开发測試群組);
 #endif
-                        List<StuActivity> stuActivities = new List<StuActivity>();
-                        List<StuActivity> tmdActivities = new List<StuActivity>();
-                        if (tmdids.IsNotEmpty()) {
-                            tmdids.ForEach(x=> {
-                                tmdActivities.Add(new StuActivity
-                                {
-                                    pk = "Activity",
-                                    id = survey.id,
-                                    code = $"Activity-{x}",
-                                    type = "Survey",
-                                    name = survey.name,
-                                    startTime = survey.startTime,
-                                    endTime = survey.endTime,
-                                    scode = survey.code,
-                                    scope = survey.scope,
-                                    school = survey.school,
-                                    creatorId = survey.creatorId,
-                                    subjects = new List<string> { "" },
-                                    blob = survey.blob,
-                                    owner = survey.owner
+                            List<StuActivity> stuActivities = new List<StuActivity>();
+                            List<StuActivity> tmdActivities = new List<StuActivity>();
+                            if (tmdids.IsNotEmpty())
+                            {
+                                tmdids.ForEach(x => {
+                                    tmdActivities.Add(new StuActivity
+                                    {
+                                        pk = "Activity",
+                                        id = survey.id,
+                                        code = $"Activity-{x}",
+                                        type = "Survey",
+                                        name = survey.name,
+                                        startTime = survey.startTime,
+                                        endTime = survey.endTime,
+                                        scode = survey.code,
+                                        scope = survey.scope,
+                                        school = survey.school,
+                                        creatorId = survey.creatorId,
+                                        subjects = new List<string> { "" },
+                                        blob = survey.blob,
+                                        owner = survey.owner
 
+                                    });
                                 });
-                            });
-                        }
-                        if (students.IsNotEmpty()) {
-                            students.ForEach(x => {
-                                stuActivities.Add(new StuActivity {
-                                    pk = "Activity",
-                                    id = survey.id,
-                                    code = $"Activity-{survey.school}-{x.id}",
-                                    type = "Survey",
-                                    name = survey.name,
-                                    startTime = survey.startTime,
-                                    endTime = survey.endTime,
-                                    scode = survey.code,
-                                    scope = survey.scope,
-                                    school = survey.school,
-                                    creatorId = survey.creatorId,
-                                    subjects = new List<string> { "" },
-                                    blob = survey.blob,
-                                    owner = survey.owner
+                            }
+                            if (students.IsNotEmpty())
+                            {
+                                students.ForEach(x => {
+                                    stuActivities.Add(new StuActivity
+                                    {
+                                        pk = "Activity",
+                                        id = survey.id,
+                                        code = $"Activity-{survey.school}-{x.id}",
+                                        type = "Survey",
+                                        name = survey.name,
+                                        startTime = survey.startTime,
+                                        endTime = survey.endTime,
+                                        scode = survey.code,
+                                        scope = survey.scope,
+                                        school = survey.school,
+                                        creatorId = survey.creatorId,
+                                        subjects = new List<string> { "" },
+                                        blob = survey.blob,
+                                        owner = survey.owner
+                                    });
                                 });
-                            });
-                        }
-                        await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
-                        //向学生或醍摩豆账号发起通知
-                        #region
-                        Notice notice = new Notice()
-                        {
-                            creation = survey.startTime,
-                            expire = survey.endTime,
-                            creatorId = survey.creatorId,
-                            stuids = students,
-                            tmdids = tmdids,
-                            type = "notice",//问卷参加参加通知
-                            priority = "normal",
-                            //data = new { }.ToJsonString()
-                            msgId = survey.id,
-                            school = survey.school,
-                            scope = survey.scope,
-                            body = new Body { sid = survey.id, scode = survey.code, spk = survey.pk,  biztype = "survey-join" }
+                            }
+                            await TriggerStuActivity.SaveStuActivity(client, _dingDing, stuActivities, tmdActivities);
+                            //向学生或醍摩豆账号发起通知
+                            #region
+                            Notice notice = new Notice()
+                            {
+                                creation = survey.startTime,
+                                expire = survey.endTime,
+                                creatorId = survey.creatorId,
+                                stuids = students,
+                                tmdids = tmdids,
+                                type = "notice",//问卷参加参加通知
+                                priority = "normal",
+                                //data = new { }.ToJsonString()
+                                msgId = survey.id,
+                                school = survey.school,
+                                scope = survey.scope,
+                                body = new Body { sid = survey.id, scode = survey.code, spk = survey.pk, biztype = "survey-join" }
 
-                        };
-                        //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
-                        //messageBlob.ApplicationProperties.Add("name", "Notice");
-                        //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
-                        #endregion
+                            };
+                            //var messageBlob = new ServiceBusMessage(notice.ToJsonString());
+                            //messageBlob.ApplicationProperties.Add("name", "Notice");
+                            //await _serviceBus.GetServiceBusClient().SendMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageBlob);
+                            #endregion
 #if DEBUG
-                        await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入完成!", GroupNames.成都开发測試群組);
+                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}写入完成!", GroupNames.成都开发測試群組);
 #endif
-                        var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
-                        messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
-                        if (changeRecords.Count > 0)
-                        {
-                            long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                            await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
-                            changeRecords[0].sequenceNumber = end;
-                            await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
-                        }
-                        else
-                        {
-                            long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
-                            ChangeRecord changeRecord = new ChangeRecord
+                            var messageSurveyEnd = new ServiceBusMessage(new { id = input.Id, progress = "finish", code = tdata.code }.ToJsonString());
+                            messageSurveyEnd.ApplicationProperties.Add("name", "Survey");
+                            if (changeRecords.Count > 0)
                             {
-                                RowKey = input.Id,
-                                PartitionKey = "going",
-                                sequenceNumber = end,
-                                msgId = messageSurveyEnd.MessageId
-                            };
-                            await _azureStorage.Save<ChangeRecord>(changeRecord);
-                        }
+                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
+                                await _serviceBus.GetServiceBusClient().cancelMessage(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), changeRecords[0].sequenceNumber);
+                                changeRecords[0].sequenceNumber = end;
+                                await _azureStorage.SaveOrUpdate<ChangeRecord>(changeRecords[0]);
+                            }
+                            else
+                            {
+                                long end = await _serviceBus.GetServiceBusClient().SendScheduleMessageAsync(Environment.GetEnvironmentVariable("Azure:ServiceBus:ActiveTask"), messageSurveyEnd, DateTimeOffset.FromUnixTimeMilliseconds(tdata.etime));
+                                ChangeRecord changeRecord = new ChangeRecord
+                                {
+                                    RowKey = input.Id,
+                                    PartitionKey = "going",
+                                    sequenceNumber = end,
+                                    msgId = messageSurveyEnd.MessageId
+                                };
+                                await _azureStorage.Save<ChangeRecord>(changeRecord);
+                            }
 #if DEBUG
-                        await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
+                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}将于:{tdata.etime}完成并结算!", GroupNames.成都开发測試群組);
 #endif
-                        break;
-                    case "finish":
+                            break;
+                        case "finish":
 #if DEBUG
-                        await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
+                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{tdata.id}开始结算{tdata.etime}!", GroupNames.成都开发測試群組);
 #endif
-                        var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
-                        var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
-                        List<dynamic> recs = new List<dynamic>();
-                        foreach (var rcd in records)
-                        {
-                            var value = rcd.Value.ToString().ToObject<JsonElement>();
-                            recs.Add(new { index = rcd.Name.ToString(), ans = value });
-                        }
-
-                        List<dynamic> userids = new List<dynamic>();
-                        foreach (var submit in submits)
-                        {
-                            var value = submit.ToString();
-                            userids.Add(value);
-                        }
+                            var records = await _azureRedis.GetRedisClient(8).HashGetAllAsync($"Survey:Record:{survey.id}");
+                            var submits = await _azureRedis.GetRedisClient(8).SetMembersAsync($"Survey:Submit:{survey.id}");
+                            List<dynamic> recs = new List<dynamic>();
+                            foreach (var rcd in records)
+                            {
+                                var value = rcd.Value.ToString().ToObject<JsonElement>();
+                                recs.Add(new { index = rcd.Name.ToString(), ans = value });
+                            }
 
-                        List<QuestionRecord> questionRecords = new List<QuestionRecord>();
-                        //结算每道题的答题情况
-                        var ContainerClient =  _azureStorage.GetBlobContainerClient(blobcntr);
-                        //List<Task<string>> tasks = new List<Task<string>>();
-                        //获取
-                        try {
-                            List<string> items = await ContainerClient.List($"survey/{survey.id}/urecord");
-                            List<SurveyRecord> surveyRecords = new List<SurveyRecord>();
-                            foreach (string item in items)
+                            List<dynamic> userids = new List<dynamic>();
+                            foreach (var submit in submits)
                             {
-                                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);
+                                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>>();
+                            //获取
+                            try
+                            {
+                                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);
+                                }
 #if DEBUG
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
+                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算数据{surveyRecords.ToJsonString()}", GroupNames.成都开发測試群組);
 #endif
-                            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)
+                                for (int index = 0; index < survey.answers.Count; index++)
                                 {
-                                    if (record.ans.Count == survey.answers.Count)
+                                    string url = $"{survey.id}/qrecord/{index}.json";
+                                    QuestionRecord question = new QuestionRecord() { index = index };
+                                    foreach (SurveyRecord record in surveyRecords)
                                     {
-                                        foreach (var an in record.ans[index])
+                                        if (record.ans.Count == survey.answers.Count)
                                         {
-                                            //
-                                            if (question.opt.ContainsKey(an))
+                                            foreach (var an in record.ans[index])
                                             {
-                                                if (question.opt[an] != null)
+                                                //
+                                                if (question.opt.ContainsKey(an))
                                                 {
-                                                    question.opt[an].Add(record.userid);
+                                                    if (question.opt[an] != null)
+                                                    {
+                                                        question.opt[an].Add(record.userid);
+                                                    }
+                                                    else
+                                                    {
+                                                        question.opt[an] = new HashSet<string>() { 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;
+                                                    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));
                                 }
-                                questionRecords.Add(question);
-                                //tasks.Add(  _azureStorage.UploadFileByContainer(blobcntr, question.ToJsonString(), "survey", url));
+                                // await Task.WhenAll(tasks);
                             }
-                           // await Task.WhenAll(tasks);
-                        } catch (Exception ex) {
-                            await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
-                        }
-                        var cods = new { records = recs, userids, question= questionRecords };
-                        //问卷整体情况
-                        await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
-                        if (string.IsNullOrEmpty(survey.recordUrl))
-                        {
-                            survey.recordUrl = $"/survey/{survey.id}/record.json";
-                            await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
-                        }
-                        else {
-                            _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
-                            _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
+                            catch (Exception ex)
+                            {
+                                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查问题结算异常{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
+                            }
+                            var cods = new { records = recs, userids, question = questionRecords };
+                            //问卷整体情况
+                            await _azureStorage.UploadFileByContainer(blobcntr, cods.ToJsonString(), "survey", $"{survey.id}/record.json");
+                            if (string.IsNullOrEmpty(survey.recordUrl))
+                            {
+                                survey.recordUrl = $"/survey/{survey.id}/record.json";
+                                await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync<Survey>(survey, survey.id, new Azure.Cosmos.PartitionKey(survey.code));
+                            }
+                            else
+                            {
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Record:{survey.id}");
+                                _azureRedis.GetRedisClient(8).KeyDelete($"Survey:Submit:{survey.id}");
+                                break;
+                            }
+
+                            //更新结束状态
+                            //data.progress = "finish";
+                            //if (survey.scope == "school")
+                            //{
+                            //    await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
+                            //}
+                            //else if (survey.scope == "private")
+                            //{
+                            //    await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
+                            //}
+
                             break;
-                        }
-                        
-                        //更新结束状态
-                        //data.progress = "finish";
-                        //if (survey.scope == "school")
-                        //{
-                        //    await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
-                        //}
-                        //else if (survey.scope == "private")
-                        //{
-                        //    await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<ActivityData>(data, data.id, new Azure.Cosmos.PartitionKey(data.code));
-                        //}
-                        
-                        break;
+                    }
                 }
+            } catch (Exception ex) {
+                await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}问卷调查{ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
+
             }
         }
     }

+ 1 - 1
TEAMModelOS/Controllers/Client/HiScanController.cs

@@ -121,7 +121,7 @@ namespace TEAMModelOS.Controllers.Core
                                     var schoolPicture = school.RootElement.GetProperty("picture");
                                     //检查学校购买的模组是否包含阅卷模组
                                     int count = 0;
-                                    string sql = $" SELECT value(count(serial))  FROM c join serial in c.serial where c.id ='{schoolId}'  and  c.pk='Product' and serial.prodCode='3222C6D2' ";
+                                    string sql = $" SELECT value(count(serial))  FROM c join serial in c.serial where c.id ='{schoolId}'  and  c.pk='Product' and serial.prodCode='YMPCVCIM' ";
                                     await  foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<int>(sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Product") })) {
                                         count = item;
                                     }

+ 37 - 27
TEAMModelOS/Controllers/School/StudentController.cs

@@ -128,8 +128,8 @@ namespace TEAMModelOS.Controllers
         /// <param name="schoolId"></param>
         /// <param name="students"></param>
         /// <returns></returns>
-        private (Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int gradeIndex)> studs,
-            Dictionary<string, (string className, string periodId, int gradeIndex, int year, string no )> classInfo,
+        private (Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId)> studs,
+            Dictionary<string, (string className, string periodId,  int year, string no )> classInfo,
             Dictionary<string, List<(string id, string no)>> classStudNo,
             List<string> errorYear,
             List<string> duplId) doSortImpStuds(string schoolId, JsonElement.ArrayEnumerator students)
@@ -137,10 +137,10 @@ namespace TEAMModelOS.Controllers
             //批量匯入 檢查輸入數據 確認座號 確認教室(創建教室) 確認學生存不存在或是要不要更新
 
             //存放輸入的學生資訊 key:stud id value:學生詳細資料
-            Dictionary<string, (string name, string no, int  year, string salt, string pw, string classNo, string className, string periodId, int gradeIndex)> dicStuds = new Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int gradeIndex)>();
+            Dictionary<string, (string name, string no, int  year, string salt, string pw, string classNo, string className, string periodId)> dicStuds = new Dictionary<string, (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId)>();
 
             //存放教室資訊用 key:classNo value:className
-            Dictionary<string, (string className, string periodId, int gradeIndex,int year,string no)> dicClassInfo = new Dictionary<string, (string className, string periodId, int gradeIndex, int year,string no)>();
+            Dictionary<string, (string className, string periodId, int year,string classNo)> dicClassInfo = new Dictionary<string, (string className, string periodId,  int year,string classNo)>();
             //存放欲加入該間教室的學生座號清單 key:classNo value:no list
             Dictionary<string, List<(string id, string no)>> dicClassStudNo = new Dictionary<string, List<(string id, string no)>>();
             //存放輸入id重複
@@ -173,7 +173,7 @@ namespace TEAMModelOS.Controllers
                         dicStuds.Remove(id);
                     }
 
-                    (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId, int gradeIndex) studentInfo = (null, null, 0, null, null, null, null, null, -1);
+                    (string name, string no, int year, string salt, string pw, string classNo, string className, string periodId) studentInfo = (null, null, 0, null, null, null, null, null);
 
                     if (student.TryGetProperty("name", out var tmpName) && !string.IsNullOrWhiteSpace(tmpName.GetString())) studentInfo.name = tmpName.GetString();
 
@@ -193,7 +193,7 @@ namespace TEAMModelOS.Controllers
                                 : Utils.HashedPassword(id, studentInfo.salt);
 
                     if (student.TryGetProperty("periodId", out var tmpPeriodId) && !string.IsNullOrWhiteSpace(tmpPeriodId.GetString())) studentInfo.periodId = tmpPeriodId.GetString();
-                    if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
+                  //  if (student.TryGetProperty("gradeIndex", out var tmpGradeIndex)) studentInfo.gradeIndex = tmpGradeIndex.GetInt32();
 
 
                     if (student.TryGetProperty("classNo", out var tmpClassNo) && !string.IsNullOrWhiteSpace(tmpClassNo.GetString()))
@@ -221,7 +221,7 @@ namespace TEAMModelOS.Controllers
                            
                             studentInfo.className = tmpClassName.GetString();
                             if (!dicClassInfo.ContainsKey($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}"))
-                            { dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, studentInfo.gradeIndex, year, tmpClassNo.GetString())); }
+                            { dicClassInfo.Add($"{studentInfo.periodId}_{year}_{tmpClassNo.GetString()}", (tmpClassName.GetString(), studentInfo.periodId, year, tmpClassNo.GetString())); }
                         }
                     }
                     
@@ -282,15 +282,22 @@ namespace TEAMModelOS.Controllers
                     var key = $"{classInfo.Value.periodId}_{classInfo.Value.year}_{classInfo.Value.no}";
                     exsitkey.Add(key);
                 }
-                var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
+                List<KeyValuePair<string, (string className, string periodId, int year, string no)>> nonexistentClassNo =new List<KeyValuePair<string, (string className, string periodId, int year, string no)>>();
+                foreach (var key in sortedImpData.classInfo.Keys) {
+                    if (!exsitkey.Contains(key)) {
+                        nonexistentClassNo.Add(new KeyValuePair<string, (string className, string periodId, int year, string no)> (key, sortedImpData.classInfo[key]));
+                    }
+                }
+
+               // var nonexistentClassNo = exsitkey.Except(sortedImpData.classInfo.Select(o => o.Key).ToList());
                 if (nonexistentClassNo.Count() != 0)
                 {
                     var gradesInfo = await getGrades(schoolId);
                     foreach (var item in nonexistentClassNo)
                     {
                         string gradeId = string.Empty;
-                        string periodId = periodId = sortedImpData.classInfo[item].periodId;
-                        int  year  = sortedImpData.classInfo[item].year;
+                        string periodId = periodId = sortedImpData.classInfo[item.Key].periodId;
+                        int  year  = sortedImpData.classInfo[item.Key].year;
                         //確認該學段存在及輸入的年級index正確(-1後大於等於0)
                         //if (gradesInfo.ContainsKey(sortedImpData.classInfo[item].periodId) && sortedImpData.classInfo[item].gradeIndex - 1>=0)
                        // {
@@ -303,8 +310,8 @@ namespace TEAMModelOS.Controllers
                         await createClassInfo(
                             schoolId,
                             null,
-                            sortedImpData.classInfo[item].className,
-                            item,
+                            sortedImpData.classInfo[item.Key].className,
+                            sortedImpData.classInfo[item.Key].no,
                             periodId,
                             gradeId, 
                             year);
@@ -520,7 +527,7 @@ namespace TEAMModelOS.Controllers
             catch (Exception ex)
             {
                 await _dingDing.SendBotMsg(
-                            $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}",
+                            $"IES5,{_option.Location},StudentController/upsertStudents()\nex:{ex.Message}{ex.StackTrace}",
                             GroupNames.醍摩豆服務運維群組);
             }
             return (null, null, null);
@@ -1194,7 +1201,7 @@ namespace TEAMModelOS.Controllers
         /// 取得教室資訊,使用classNo進行查詢。
         /// </summary>
         /// <returns></returns>
-        private async Task<Dictionary<string, Class>> getClassInfoUseNo(string schoolId, Dictionary<string, (string className, string periodId, int gradeIndex, int year,string no)> classNos)
+        private async Task<Dictionary<string, Class>> getClassInfoUseNo(string schoolId, Dictionary<string, (string className, string periodId,  int year,string no)> classNos)
         {
             try
             {
@@ -1203,7 +1210,7 @@ namespace TEAMModelOS.Controllers
                 {
                    
                     foreach (var key in classNos.Keys) {
-                        string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.no='{classNos[key].no}' and c.year={classNos[key].year} and c.periodId='{classNos[key].periodId}' ";
+                        string queryText = $"SELECT * FROM c WHERE c.code = 'Class-{schoolId}' AND c.no='{classNos[key]}' and c.year={classNos[key].year} and c.periodId='{classNos[key].periodId}' ";
                         await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer("TEAMModelOS", "School")
                        .GetItemQueryIterator<Class>(queryText: queryText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Class-{schoolId}") }))
                         {
@@ -1669,12 +1676,12 @@ namespace TEAMModelOS.Controllers
         /// </summary>
         /// <param name="schoolId"></param>
         /// <returns>Key:periodId  Vaule:list gradeInfo</returns>
-        private async Task<Dictionary<string, List<(string gradeId, string gradeName)>>> getGrades(string schoolId)
+        private async Task<Dictionary<string, List<(int gradeId, string gradeName)>>> getGrades(string schoolId)
         {
             try
             {
                 //Key:學制 Value:年級資訊list
-                Dictionary<string, List<(string gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(string gradeId, string gradeName)>>();
+                Dictionary<string, List<(int gradeId, string gradeName)>> dicPeriod = new Dictionary<string, List<(int gradeId, string gradeName)>>();
 
                 var response = await _azureCosmos
                     .GetCosmosClient()
@@ -1690,19 +1697,22 @@ namespace TEAMModelOS.Controllers
 
                 while (period.MoveNext())
                 {
+                    List<(int gradeId, string gradeName)> gradeInfos = new List<(int gradeId, string gradeName)>();
                     JsonElement jsonPeriod = period.Current;
                     var periodId = jsonPeriod.GetProperty("id").GetString();
-                    var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
-
-                    List<(string gradeId, string gradeName)> gradeInfos = new List<(string gradeId, string gradeName)>();
-
-                    while (grades.MoveNext())
-                    {
-                        JsonElement grade = grades.Current;
-                        var gradeId = grade.GetProperty("id").GetString();
-                        var gradeName = grade.GetProperty("name").GetString();
-                        gradeInfos.Add((gradeId, gradeName));
+                    var grades = jsonPeriod.GetProperty("grades").ToObject<List<string>>();
+                    for (int index = 0; index < grades.Count; index++) {
+                        gradeInfos.Add((index, grades[index]));
                     }
+                    //var grades = jsonPeriod.GetProperty("grades").EnumerateArray();
+                    //while (grades.MoveNext())
+                    //{
+                    //    JsonElement grade = grades.Current;
+                    //    var gradeId = grade.GetInt32();
+                    //    var gradeName = grade.GetProperty("name").GetString();
+                    //    gradeInfos.Add((gradeId, gradeName));
+                    //}
+
                     dicPeriod.Add(periodId, gradeInfos);
                 }
                 return dicPeriod;