Browse Source

Merge branch 'develop3.0-tmd' of http://106.12.23.251:10080/TEAMMODEL/TEAMModelOS into develop3.0-tmd

liqk 4 years ago
parent
commit
951def4fbb
44 changed files with 2398 additions and 3329 deletions
  1. 7 1
      TEAMModelFunction/MonitorCosmosDB.cs
  2. 1 6
      TEAMModelFunction/Properties/serviceDependencies.json
  3. 1 7
      TEAMModelFunction/Properties/serviceDependencies.local.json
  4. 2 12
      TEAMModelFunction/Startup.cs
  5. 14 768
      TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosExtensions.cs
  6. 3 122
      TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactory.cs
  7. 4 4
      TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactoryExtensions.cs
  8. 1 3
      TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactoryOptions.cs
  9. 668 0
      TEAMModelOS.SDK/DI/AzureCosmos/Inner/AzureCosmosExOld.cs
  10. 1 22
      TEAMModelOS/ClientApp/src/api/knowledge.js
  11. 0 10
      TEAMModelOS/ClientApp/src/components/selflearn/ExerciseList.vue
  12. 1 6
      TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/LessonTest.vue
  13. 51 35
      TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/LessonTestPop.vue
  14. 94 81
      TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/composePaper.vue
  15. 1 0
      TEAMModelOS/ClientApp/src/components/student-web/EventView/EventList.vue
  16. 11 0
      TEAMModelOS/ClientApp/src/store/module/studentWeb.js
  17. 14 7
      TEAMModelOS/ClientApp/src/utils/editorTools.js
  18. 0 10
      TEAMModelOS/ClientApp/src/view/evaluation/bank/ExerciseList.vue
  19. 0 10
      TEAMModelOS/ClientApp/src/view/evaluation/bank/TestPaperList.vue
  20. 7 2
      TEAMModelOS/ClientApp/src/view/evaluation/bank/index.vue
  21. 1 1
      TEAMModelOS/ClientApp/src/view/evaluation/components/BaseImport.vue
  22. 2 2
      TEAMModelOS/ClientApp/src/view/evaluation/index/CreateExercises.less
  23. 1 1
      TEAMModelOS/ClientApp/src/view/evaluation/types/BaseMultiple.vue
  24. 2 1
      TEAMModelOS/ClientApp/src/view/evaluation/types/BaseSingle.vue
  25. 2 21
      TEAMModelOS/ClientApp/src/view/knowledge-point/index/Index.vue
  26. 501 498
      TEAMModelOS/Controllers/Analysis/AchievementController.cs
  27. 506 506
      TEAMModelOS/Controllers/Analysis/ChangeController.cs
  28. 0 198
      TEAMModelOS/Controllers/Analysis/ClassController.cs
  29. 0 55
      TEAMModelOS/Controllers/Analysis/FileTool.cs
  30. 0 20
      TEAMModelOS/Controllers/BaseController.cs
  31. 82 245
      TEAMModelOS/Controllers/Exam/ExamController.cs
  32. 1 14
      TEAMModelOS/Controllers/Task/SurveyController.cs
  33. 0 0
      TEAMModelOS/Controllers/Common/VoteController.cs
  34. 0 98
      TEAMModelOS/Controllers/Core/CommonController.cs
  35. 0 162
      TEAMModelOS/Controllers/Core/FileController.cs
  36. 1 1
      TEAMModelOS/Controllers/Exam/ImportExerciseController.cs
  37. 340 0
      TEAMModelOS/Controllers/Import/ImportExerciseController.cs
  38. 54 238
      TEAMModelOS/Controllers/School/CourseController.cs
  39. 4 61
      TEAMModelOS/Controllers/Syllabus/ItemInfoController.cs
  40. 0 53
      TEAMModelOS/Controllers/Syllabus/KnowledgeController.cs
  41. 0 15
      TEAMModelOS/Controllers/Syllabus/ResourceController.cs
  42. 19 31
      TEAMModelOS/Controllers/Teacher/CommentController.cs
  43. 1 1
      TEAMModelOS/Controllers/xTest/BlobController.cs
  44. 0 1
      TEAMModelOS/TEAMModelOS.csproj

+ 7 - 1
TEAMModelFunction/MonitorCosmosDB.cs

@@ -20,13 +20,15 @@ namespace TEAMModelFunction
         private readonly AzureCosmosFactory _azureCosmos;
         private readonly AzureServiceBusFactory _serviceBus;
         private readonly AzureStorageFactory _azureStorage;
+        private readonly DingDing _dingDing;
 
-        public MonitorCosmosDB(IHttpClientFactory clientFactory, AzureCosmosFactory azureCosmos,AzureServiceBusFactory azureServiceBus, AzureStorageFactory azureStorage)
+        public MonitorCosmosDB(IHttpClientFactory clientFactory, AzureCosmosFactory azureCosmos,AzureServiceBusFactory azureServiceBus, AzureStorageFactory azureStorage, DingDing dingDing)
         {
             _clientFactory = clientFactory;
             _azureCosmos = azureCosmos;
             _serviceBus = azureServiceBus;
             _azureStorage = azureStorage;
+            _dingDing = dingDing;
         }
 
         [FunctionName("Common")]
@@ -51,6 +53,10 @@ namespace TEAMModelFunction
                         long etime = input.GetPropertyValue<long>("endTime");
                         string school = input.GetPropertyValue<string>("school");
                         string code = input.GetPropertyValue<string>("code");
+                        await _dingDing.SendBotMsg($"CosmosDBTrigger,{pk}\n" +
+                                        $"Start Time:{DateTimeOffset.FromUnixTimeMilliseconds(stime).AddHours(8)}\n" +
+                                        $"End Time:{DateTimeOffset.FromUnixTimeMilliseconds(etime).AddHours(8)}",
+                                        GroupNames.醍摩豆服務運維群組);
                         switch (pk)
                         {
                             case "Exam":

+ 1 - 6
TEAMModelFunction/Properties/serviceDependencies.json

@@ -1,8 +1,3 @@
 {
-  "dependencies": {
-    "storage1": {
-      "type": "storage",
-      "connectionId": "AzureWebJobsStorage"
-    }
-  }
+  "dependencies": {}
 }

+ 1 - 7
TEAMModelFunction/Properties/serviceDependencies.local.json

@@ -1,9 +1,3 @@
 {
-  "dependencies": {
-    "storage1": {
-      "resourceId": "/subscriptions/[parameters('subscriptionId')]/resourceGroups/[parameters('resourceGroup')]/providers/Microsoft.Storage/storageAccounts/teammodelstorage",
-      "type": "storage.azure",
-      "connectionId": "AzureWebJobsStorage"
-    }
-  }
+  "dependencies": {}
 }

+ 2 - 12
TEAMModelFunction/Startup.cs

@@ -15,22 +15,12 @@ namespace TEAMModelFunction
     public class Startup : FunctionsStartup
     { 
         public override void Configure(IFunctionsHostBuilder builder)
-        {
-            var ConnectionString = Environment.GetEnvironmentVariable("Azure:Cosmos:ConnectionString");
-            var ScanModel = Environment.GetEnvironmentVariable("ScanModel");
-            var Database = Environment.GetEnvironmentVariable("Database");  
-            
+        { 
             builder.Services.AddHttpClient();
             builder.Services.AddHttpClient<DingDing>();
             builder.Services.AddAzureServiceBus(Environment.GetEnvironmentVariable("Azure:ServiceBus:ConnectionString"));
             builder.Services.AddAzureStorage(Environment.GetEnvironmentVariable("Azure:Starage:ConnectionString"));
-            builder.Services.AddAzureCosmos(new AzureCosmosFactoryOptions
-            {
-                ConnectionString = ConnectionString,
-                Name = "Default",
-                ScanModel = ScanModel.Split(","),
-                Database = Database.Split(","),
-            });
+            builder.Services.AddAzureCosmos(Environment.GetEnvironmentVariable("Azure:Cosmos:ConnectionString"));
         }
     }
 }

+ 14 - 768
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosExtensions.cs

@@ -25,23 +25,7 @@ using TEAMModelOS.SDK.Models;
 namespace TEAMModelOS.SDK.DI
 {
     public static class AzureCosmosExtensions
-    {
-        /// <summary>
-        /// 缓存前缀
-        /// </summary>
-        private const string CacheCosmosPrefix = "cosmos:";
-        /// <summary>
-        /// ttl时长 1秒
-        /// </summary>
-        private const int ttl = 1;
-        /// <summary>
-        /// 分页大小
-        /// </summary>
-        private const int pageSize = 200;
-        /// <summary>
-        /// 超时时间
-        /// </summary>
-        private const int timeoutSeconds = 86400;
+    {    
         public static double RU(this Response response)
         {
             try
@@ -50,11 +34,12 @@ namespace TEAMModelOS.SDK.DI
                 var ru = Convert.ToDouble(value);
                 return ru;
             }
-            catch (Exception)
+            catch
             {
                 return 0;
             }
         }
+
         public static string GetContinuationToken(this Response response)
         {
             try
@@ -62,768 +47,29 @@ namespace TEAMModelOS.SDK.DI
                 response.Headers.TryGetValue("x-ms-continuation", out var value);
                 return value;
             }
-            catch (Exception)
+            catch
             {
                 return null;
             }
         }
-        public static async Task<T> FindByIdPk<T>(this AzureCosmosFactory azureCosmosFactory, string id, string pk) where T : CosmosEntity
-        {
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            try
-            {
-                ItemResponse<T> response = await container.container.ReadItemAsync<T>(id: id, partitionKey: new PartitionKey(pk));
-                return response.Value;
-            }
-            catch (Exception){
-                return default;
-            }
-        }
-        public static async Task<List<T>> FindByIds<T>(this AzureCosmosFactory azureCosmosFactory, List<string> ids) where T : CosmosEntity
-        {
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            if (container.cache && RedisHelper.Instance != null)
-            {
-                List<T> list = new List<T>();
-                List<string> NotIn = new List<string>();
-                foreach (string id in ids)
-                {
-                    if (!await RedisHelper.HExistsAsync(CacheCosmosPrefix + container.container.Id, id))
-                    {
-                        NotIn.Add(id);
-                    }
-                    else
-                    {
-                        list.Add(await RedisHelper.HGetAsync<T>(CacheCosmosPrefix + container.container.Id, id));
-                    }
-                }
-                if (NotIn.IsNotEmpty())
-                {
-                    List<T> noInList = await FindByDict<T>(azureCosmosFactory, new Dictionary<string, object> { { "id", NotIn.ToArray() } });
-                    noInList.ForEach(x => { RedisHelper.HSet(CacheCosmosPrefix + container.container.Id, x.id, x); RedisHelper.Expire(CacheCosmosPrefix + container.container.Id, timeoutSeconds); });
-                    list.AddRange(noInList);
-                }
-                return list;
-            }
-            else
-            {
-                return await FindByDict<T>(azureCosmosFactory, new Dictionary<string, object> { { "id", ids.ToArray() } });
-            }
-        }
-        public static async Task<T> Save<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
-        {
-
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            entity.pk = container.type.Name;            
-            ItemResponse<T> response = await container.container.CreateItemAsync<T>(entity);
-            if (container.cache && RedisHelper.Instance != null)
-            {
-                if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                }
-                else
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                    await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-                }
-            }
-            return response.Value;
-        }
-        public static async Task<List<T>> SaveAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            bool flag = false;
-            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-            {
-                flag = true;
-            }
-            string partitionKey =AzureCosmosUtil.GetPartitionKey (type);
-           
-            Stopwatch stopwatch = Stopwatch.StartNew();
-            for (int i = 0; i < pages; i++)
-            {
-                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
-                List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
-                lists.ForEach(async x =>
-                {
-                    x.pk = type.Name;                    
-                    MemoryStream stream = new MemoryStream();
-                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
-                    object o = type.GetProperty(partitionKey).GetValue(x, null);
-                    KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
-                    itemsToInsert.Add(keyValue);
-                });
-                List<Task> tasks = new List<Task>(lists.Count);
-                itemsToInsert.ForEach(item =>
-                {
-                    tasks.Add(container.container.CreateItemStreamAsync(item.Value, item.Key)
-                        .ContinueWith((Task<Response> task) =>
-                        {
-                            using (Response response = task.Result)
-                            {
-                                //if (!response.IsSuccessStatusCode)
-                                //{
-                                //}
-                            }
-                        }
-                        ));
-                });
-                await Task.WhenAll(tasks);
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    lists.ForEach(async x => {
-                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
-                    });
-                }
-            }
-            if (container.cache && RedisHelper.Instance != null && !flag)
-            {
-                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-            }
-            stopwatch.Stop();
-            return enyites;
-        }
-        public static async Task<T> SaveOrUpdate<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
-        {
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            entity.pk = container.type.Name;            
-            ItemResponse<T> response = await container.container.UpsertItemAsync(item: entity);
-            if (container.cache && RedisHelper.Instance != null)
-            {
-                if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                }
-                else
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                    await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-                }
-            }
-            return response.Value;
-        }
-        public static async Task<List<T>> SaveOrUpdateAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            bool flag = false;
-            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-            {
-                flag = true;
-            }
-            
-            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
-            
-            Stopwatch stopwatch = Stopwatch.StartNew();
-            for (int i = 0; i < pages; i++)
-            {
-                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
-                List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
-                lists.ForEach(async x =>
-                {
-                    x.pk = type.Name;                    
-                    MemoryStream stream = new MemoryStream();
-                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
-                    object o = type.GetProperty(partitionKey).GetValue(x, null);
-                    KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
-                    itemsToInsert.Add(keyValue);
-                });
-                List<Task> tasks = new List<Task>(lists.Count);
-                itemsToInsert.ForEach(item =>
-                {
-                    tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
-                        .ContinueWith((Task<Response> task) =>
-                        {
-                        }
-                        ));
-                });
-                await Task.WhenAll(tasks);
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    lists.ForEach(async x => {
-                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
-                    });
-                }
-            }
-            if (container.cache && RedisHelper.Instance != null && !flag)
-            {
-                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-            }
-            stopwatch.Stop();
-            return enyites;
-        }
-        public static async Task<List<int>> FindCountByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict)
-        {
-            Type type = typeof(T);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            string pk = type.Name;
-            StringBuilder sql = new StringBuilder("select  value count(c)  from c");
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
-            if (cosmosDbQuery == null)
-            {
-                return new List<int> { 0 };
-            }
-            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-            AsyncPageable<int> query = container.container.GetItemQueryIterator<int>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-            return await ResultsFromFeedIterator(query);
-        }
-        public static async Task<List<int>> FindCountByDict<T>(this AzureCosmosFactory azureCosmosFactory,JsonElement json)
-        {
-            Type type = typeof(T);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            string pk = type.Name;
-            StringBuilder sql = new StringBuilder("select  value count(c)  from c");
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(json, sql, pk);
-            if (cosmosDbQuery == null)
-            {
-                return new List<int> { 0 };
-            }
-            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-            AsyncPageable<int> query = container.container.GetItemQueryIterator<int>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-            return await ResultsFromFeedIterator(query);
-        }
-        public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict)
-        {
-            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
-            {
-                string pk = container.type.Name;
-                dict.Remove("@CURRPAGE");
-                dict.Remove("@PAGESIZE");
-                dict.Remove("@ASC");
-                dict.Remove("@DESC");
-                StringBuilder sql = new StringBuilder("select  value count(c)  from c");
-                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
-                if (cosmosDbQuery == null)
-                {
-                    return new List<dynamic> { 0 };
-                }
-                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-                return await ResultsFromFeedIterator(query);
-            }
-            else
-            {
-                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
-            }
-        }
-        public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName,JsonElement json)
-        {
-            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
-            {
-                Dictionary<string, object> dict = new Dictionary<string, object>();
-                var emobj = json.EnumerateObject();
-                while (emobj.MoveNext())
-                {
-                    if (emobj.Current.Name != "@CURRPAGE"|| 
-                        emobj.Current.Name != "@PAGESIZE" || 
-                        emobj.Current.Name != "@ASC" || 
-                        emobj.Current.Name != "@DESC") {
-                        dict[emobj.Current.Name] = emobj.Current.Value;
-                    }
-                }
-                string pk = container.type.Name;
-                StringBuilder sql = new StringBuilder("select  value count(c)  from c");
-                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
-                if (cosmosDbQuery == null)
-                {
-                    return new List<dynamic> { 0 };
-                }
-                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-                return await ResultsFromFeedIterator(query);
-            }
-            else
-            {
-                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
-            }
-        }
-        public static async Task<T> Update<T>(this AzureCosmosFactory azureCosmosFactory,  T entity) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            string partitionKey =AzureCosmosUtil.GetPartitionKey (type);
-            entity.pk = type.Name;            
-            object o = type.GetProperty(partitionKey).GetValue(entity, null);
-            ItemResponse<T> response = await container.container.ReplaceItemAsync(entity, entity.id, new PartitionKey(o.ToString()));
-            if (container.cache && RedisHelper.Instance != null)
-            {
-                if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                }
-                else
-                {
-                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
-                    await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-                }
-            }
-            return response.Value;
-        }
-        internal class Item
-        {
-            public string id { get; set; }
-            public string pk { get; set; }
-            public MemoryStream stream { get; set; }
-        } 
-        public static async Task<List<T>> UpdateAll<T>(this AzureCosmosFactory azureCosmosFactory,  List<T> enyites) where T : CosmosEntity
-        {
-            //await Task.Run(() => Parallel.ForEach(entities, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (item) =>
-            //{
-            //    Task.WaitAll(Update(item));
-            //}));
-            Type type = typeof(T);
-            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            bool flag = false;
-            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-            {
-                flag = true;
-            }
-            string partitionKey =AzureCosmosUtil.GetPartitionKey (type);
-           
-            Stopwatch stopwatch = Stopwatch.StartNew();
-            for (int i = 0; i < pages; i++)
-            {
-                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
-                List<Item> itemsToInsert = new List<Item>();
-                lists.ForEach(async x =>
-                {
-                    x.pk = type.Name;                    
-                    MemoryStream stream = new MemoryStream();
-                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
-                    object o = type.GetProperty(partitionKey).GetValue(x, null);
-                    Item keyValue = new Item { id = x.id, pk = o.ToString(), stream = stream };
-                    itemsToInsert.Add(keyValue);
-                });
-                List<Task> tasks = new List<Task>(lists.Count);
-                itemsToInsert.ForEach(item =>
-                {
-                    tasks.Add(container.container.ReplaceItemStreamAsync(item.stream, item.id, new PartitionKey(item.pk))
-                        .ContinueWith((Task<Response> task) =>
-                        {
-                            //using (ResponseMessage response = task.Result)
-                            //{
-                            //    if (!response.IsSuccessStatusCode)
-                            //    {
-                            //    }
-                            //}
-                        }
-                        ));
-                });
-                await Task.WhenAll(tasks);
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    lists.ForEach(async x => {
-                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
-                    });
-                }
-            }
-            if (container.cache && RedisHelper.Instance != null && !flag)
-            {
-                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
-            }
-            stopwatch.Stop();
-            return enyites;
-        }
-        public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict, List<string> propertys = null) where T : CosmosEntity
-        {
-            StringBuilder sql;
-            sql = SQLHelper.GetSQLSelect(propertys);
-            string pk = typeof(T).Name;
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
-            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-            return await ResultsFromQueryAndOptions<T>(azureCosmosFactory,cosmosDbQuery, queryRequestOptions);
-        }
-        public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement jsonElement, List<string> propertys = null) where T : CosmosEntity
-        {
-            StringBuilder sql;
-            sql = SQLHelper.GetSQLSelect(propertys);
-            string pk = typeof(T).Name;
-            //Dictionary<string, object> dict = new Dictionary<string, object>();
-           /* var emobj = jsonElement.EnumerateObject();
-            while (emobj.MoveNext())
-            {
-                dict[emobj.Current.Name] = emobj.Current.Value;
-            }
-            //处理code
-            if (dict.TryGetValue("code", out object _))
-            {
-                dict.Remove("code");
-            }*/
-            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(jsonElement, sql, pk);
-            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-            return await ResultsFromQueryAndOptions<T>(azureCosmosFactory, cosmosDbQuery, queryRequestOptions);
-        }
-        public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, JsonElement json, List<string> propertys = null)
-        {
-            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
-            {
-
-                string pk = container.type.Name;
-                StringBuilder sql;
-                sql = SQLHelper.GetSQLSelect(propertys);
-                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(json, sql, pk);
-                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-                return await ResultsFromFeedIterator(query);
-            }
-            else
-            {
-                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
-            }
-        }
-        public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict, List<string> propertys = null)
-        {
-            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
-            {
-
-                string pk = container.type.Name;
-                StringBuilder sql;
-                sql = SQLHelper.GetSQLSelect(propertys);
-                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
-                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
-                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
-                return await ResultsFromFeedIterator(query);
-            }
-            else
-            {
-                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
-            }
-        }
-        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<IdPk> ids) where T : CosmosEntity
-        {
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            List<IdPk> idPks = new List<IdPk>();
-            if (container.monitor)
-            {
-                List<T> list = await azureCosmosFactory.FindByDict<T>(new Dictionary<string, object>() { { "id", ids.Select(x => x.id).ToArray() } });
-                list = await azureCosmosFactory. DeleteTTL(list);
-                return ids;
-            }
-            else
-            {
-                int pages = (int)Math.Ceiling((double)ids.Count / pageSize);
-                Stopwatch stopwatch = Stopwatch.StartNew();
-                for (int i = 0; i < pages; i++)
-                {
-                    List<IdPk> lists = ids.Skip((i) * pageSize).Take(pageSize).ToList();
-                    List<Task> tasks = new List<Task>(lists.Count);
-                    lists.ForEach(item =>
-                    {
-                        tasks.Add(container.container.DeleteItemStreamAsync(item.id, new PartitionKey(item.pk))
-                            .ContinueWith((Task<Response> task) =>
-                            {
-                                using (Response response = task.Result)
-                                {
-                                    idPks.Add(new IdPk { id = item.id, pk = item.pk, Status = response.Status });
-                                    //    if (!response.IsSuccessStatusCode)
-                                    //    {
-                                    //    }
-                                }
-                            }
-                            ));
-                    });
-                    await Task.WhenAll(tasks);
-                    if (container.cache && RedisHelper.Instance != null)
-                    {
-                        lists.ForEach(async x => {
-                            await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
-                        });
-                    }
-                }
-                stopwatch.Stop();
-                return idPks;
-            }
-        }
-        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict) where T : CosmosEntity
-        {
-            if (dict.Keys.Count > 0)
-            {
-                List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
-
-                return await azureCosmosFactory.DeleteAll(list);
-            }
-            else
-            {
-                throw new BizException("参数为空", 500);
-            }
 
-        }
-        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement dict) where T : CosmosEntity
+        public static async Task<int> GetCount(this CosmosContainer container, string partitionkey, string queryWhere = "WHERE 1=1")
         {
-            List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
-            return await azureCosmosFactory.DeleteAll(list);
-        }
-        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            AzureCosmosModel container =   azureCosmosFactory.GetCosmosModel (type.Name);
-            List<IdPk> idPks = new List<IdPk>();            
-            
-            string pk = AzureCosmosUtil.GetPartitionKey (type);
-            if (container.monitor)
+            int totalCount = 0;
+            await foreach (var item in container.GetItemQueryStreamIterator(
+                queryText: $"SELECT VALUE COUNT(1) From c {queryWhere}",
+                requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey(partitionkey), MaxItemCount = -1 }))
             {
-                enyites = await azureCosmosFactory.DeleteTTL(enyites);
-                foreach (T t in enyites)
+                using var json = await JsonDocument.ParseAsync(item.ContentStream);
+                if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
                 {
-                    object o = type.GetProperty(pk).GetValue(t, null);
-                    idPks.Add(new IdPk { id = t.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent });
-                }
-                return idPks;
-            }
-            else
-            {
-                int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
-                Stopwatch stopwatch = Stopwatch.StartNew();
-                for (int i = 0; i < pages; i++)
-                {
-                    List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
-                    List<KeyValuePair<PartitionKey, string>> itemsToInsert = new List<KeyValuePair<PartitionKey, string>>();
-                    lists.ForEach(x =>
-                    {
-                        object o = type.GetProperty(pk).GetValue(x, null);
-                        KeyValuePair<PartitionKey, string> keyValue = new KeyValuePair<PartitionKey, string>(new PartitionKey(o.ToString()), x.id);
-                        itemsToInsert.Add(keyValue);
-                    });
-
-                    List<Task> tasks = new List<Task>(lists.Count);
-                    itemsToInsert.ForEach(item =>
-                    {
-                        tasks.Add(container.container.DeleteItemStreamAsync(item.Value, item.Key)
-                        .ContinueWith((Task<Response> task) =>
-                        {
-                            using (Response response = task.Result)
-                            {
-
-                                idPks.Add(new IdPk { id = item.Value, pk = item.Key.ToString(), Status = response.Status });
-
-                            }
-                        }
-                        ));
-                    });
-                    await Task.WhenAll(tasks); if (container.cache && RedisHelper.Instance != null)
+                    foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
                     {
-                        lists.ForEach(async x => {
-                            await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
-                        });
+                        totalCount = obj.GetInt32();
                     }
                 }
-                stopwatch.Stop();
-                return idPks;
-            }
-        }
-        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, IdPk idPk) where T : CosmosEntity
-        {
-            return await DeleteAsync<T>(azureCosmosFactory, idPk.id, idPk.pk);
-        }
-        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, string id, string pk) where T : CosmosEntity
-        {
-
-            //  pk =AzureCosmosUtil.GetPartitionKey<T>();
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            if (container.monitor)
-            {
-                List<T> list = await FindByDict<T>(azureCosmosFactory,new Dictionary<string, object>() { { "id", id } });
-                if (list.Count > 0)
-                {
-                    await DeleteTTL<T>(azureCosmosFactory, list);
-                    return new IdPk { id = id, pk = pk, StatusCode = HttpStatusCode.NoContent };
-                }
-                else
-                {
-                    throw new BizException("未找到ID匹配的数据,删除失败");
-                }
-            }
-            else
-            {
-                Response response = await container.container.DeleteItemStreamAsync(id: id, partitionKey: new PartitionKey(pk));
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, id);
-                }
-                return new IdPk { id = id, pk = pk, Status = response.Status };
-            }
-
-        }
-        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            AzureCosmosModel container =   azureCosmosFactory.GetCosmosModel(type.Name);
-            string partitionKey = AzureCosmosUtil.GetPartitionKey (type);
-           
-            object o = type.GetProperty(partitionKey).GetValue(entity, null);
-            if (container.monitor)
-            {
-                await DeleteTTL<T>(azureCosmosFactory, new List<T>() { entity });
-                return new IdPk { id = entity.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent };
-            }
-            else
-            {
-                Response response = await container.container.DeleteItemStreamAsync(id: entity.id, partitionKey: new PartitionKey(o.ToString()));
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, entity.id);
-                }
-                return new IdPk { id = entity.id, pk = partitionKey, Status = response.Status };
-            }
-        }
-        public static async Task<List<T>> FindSQL<T>(this AzureCosmosFactory azureCosmosFactory, string sql, Dictionary<string, object> Parameters = null) where T : CosmosEntity
-        {
-            if (sql.Contains(".pk"))
-            {
-                AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-                QueryRequestOptions queryOptions = GetQueryRequestOptions(GetEffectivePageSize(-1, null));
-                if (Parameters != null)
-                {
-                    AzureCosmosQuery cosmosDbQuery = new AzureCosmosQuery
-                    {
-                        QueryText = sql,
-                        Parameters = Parameters
-                    };
-                    AsyncPageable<T> feedIterator = container.container
-                    .GetItemQueryIterator<T>(cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryOptions);
-                    return await ResultsFromFeedIterator(feedIterator);
-                }
-                else
-                {
-                    QueryDefinition queryDefinition = new QueryDefinition(sql);
-                    return await ResultsFromFeedIterator<T>(container.container.GetItemQueryIterator<T>(queryDefinition));
-                }
-            }
-            else
-            {
-                throw new BizException("查询参数必须设置 .pk ", ResponseCode.PARAMS_ERROR);
-            }
-        }
-        /// <summary>
-        /// 偌TTL刉壺
-        /// </summary>
-        /// <typeparam name="T"></typeparam>
-        /// <param name="list"></param>
-        /// <returns></returns>
-        private static  async Task<List<T>> DeleteTTL<T>(this AzureCosmosFactory azureCosmosFactory ,List<T> list) where T : CosmosEntity
-        {
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            list.ForEach(x => { x.ttl = ttl; });
-            list = await DeleteTTlALL(azureCosmosFactory,list);
-            if (container.cache && RedisHelper.Instance != null)
-            {
-                list.ForEach(async x => {
-                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
-                });
-            }
-            return list;
-        }
-        private static  async Task<List<T>> DeleteTTlALL<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
-        {
-            Type type = typeof(T);
-            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
-            bool flag = false;
-            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
-            {
-                flag = true;
-            }
-            string partitionKey = AzureCosmosUtil.GetPartitionKey (type);
-           
-            Stopwatch stopwatch = Stopwatch.StartNew();
-            for (int i = 0; i < pages; i++)
-            {
-                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
-                List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
-                lists.ForEach(async x =>
-                {
-                    x.pk = type.Name;
-                    //x.ttl = null;
-                    MemoryStream stream = new MemoryStream();
-                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
-                    object o = type.GetProperty(partitionKey).GetValue(x, null);
-                    KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
-                    itemsToInsert.Add(keyValue);
-                });
-                List<Task> tasks = new List<Task>(lists.Count);
-                itemsToInsert.ForEach(item =>
-                {
-                    tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
-                        .ContinueWith((Task<Response> task) =>
-                        {
-                            //using (ResponseMessage response = task.Result)
-                            //{
-                            //    if (!response.IsSuccessStatusCode)
-                            //    {
-                            //    }
-                            //}
-                        }
-                        ));
-                });
-                await Task.WhenAll(tasks);
-                if (container.cache && RedisHelper.Instance != null)
-                {
-                    lists.ForEach(async x => {
-                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
-                    });
-                }
-            }
-            if (container.cache && RedisHelper.Instance != null && !flag)
-            {
-                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
             }
-            stopwatch.Stop();
-            return enyites;
-        }
-        private static QueryRequestOptions GetDefaultQueryRequestOptions(int? itemsPerPage = null, int? maxBufferedItemCount = null,  int? maxConcurrency = null)
-        {
-            QueryRequestOptions queryRequestOptions = new QueryRequestOptions
-            {
-                MaxItemCount = itemsPerPage == -1 ? 1000 : itemsPerPage,
-                MaxBufferedItemCount = maxBufferedItemCount ?? 100,
-                MaxConcurrency = maxConcurrency ?? 50
-            };
-            return queryRequestOptions;
-        }
-        private static int GetEffectivePageSize(int itemsPerPage, int? maxItemCount)
-        {
-            return itemsPerPage == -1 ? maxItemCount ?? itemsPerPage : Math.Min(maxItemCount ?? itemsPerPage, itemsPerPage);
-        }
-        private static async Task<List<T>> ResultsFromQueryAndOptions<T>(this AzureCosmosFactory azureCosmosFactory, AzureCosmosQuery cosmosDbQuery, QueryRequestOptions queryOptions)
-        {
-            if (cosmosDbQuery == null)
-            {
-                return null;
-            }
-            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
-            AsyncPageable<T> query = container.container.GetItemQueryIterator<T>(
-                queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
-                requestOptions: queryOptions);
-
-            return await ResultsFromFeedIterator(query);
-        }
-        private static async Task<List<T>> ResultsFromFeedIterator<T>(AsyncPageable<T> query, int? maxItemCount = null)
-        {
-            List<T> results = new List<T>();
-             
-            await  foreach (T t in   query)
-            {
-                results.Add(t);
-                if (results.Count == maxItemCount)
-                {
-                    return results;
-                }
-            }
-            return results;
-        }
-        private static QueryRequestOptions GetQueryRequestOptions(int itemsPerPage)
-        {
-            QueryRequestOptions queryRequestOptions = new QueryRequestOptions
-            {
-                MaxItemCount = itemsPerPage
-            };
-
-            return queryRequestOptions;
+            return totalCount;
         }
     }
 }

+ 3 - 122
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactory.cs

@@ -34,7 +34,7 @@ namespace TEAMModelOS.SDK.DI
         private readonly ILogger _logger;
         //private Option _option;
         private ConcurrentDictionary<string, CosmosClient> CosmosClients { get; } = new ConcurrentDictionary<string, CosmosClient>();
-        public AzureCosmosDict CosmosDict { get; set; } = new AzureCosmosDict();
+        
         //   private CosmosDatabase database { get; set; }
         
         public AzureCosmosFactory(IServiceProvider services, IOptionsMonitor<AzureCosmosFactoryOptions> optionsMonitor, ILogger<AzureCosmosFactory> logger)
@@ -44,9 +44,7 @@ namespace TEAMModelOS.SDK.DI
 
             _services = services;
             _optionsMonitor = optionsMonitor;
-            _logger = logger;
-           
-            InitializeDatabase().GetAwaiter().GetResult();
+            _logger = logger;  
         }
 
         /// <summary>
@@ -59,7 +57,7 @@ namespace TEAMModelOS.SDK.DI
         {
             try
             {
-                var cm = CosmosClients.GetOrAdd(name, x => new CosmosClient(_optionsMonitor.Get(name).ConnectionString, new CosmosClientOptions() { ApplicationRegion = region, SerializerOptions = new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase } }));
+                var cm = CosmosClients.GetOrAdd(name, x => new CosmosClient(_optionsMonitor.Get(name).CosmosConnectionString, new CosmosClientOptions() { ApplicationRegion = region, SerializerOptions = new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase } }));
                 return cm;
             }
             catch (Exception e)
@@ -68,122 +66,5 @@ namespace TEAMModelOS.SDK.DI
                 return null;
             }
         }
-         
-        /// <summary>
-        /// 获取容器信息
-        /// </summary>
-        /// <param name="cosmosDBAttribute"></param>
-        /// <param name="typeName"></param>
-        /// <param name="PartitionKey"></param>
-        /// <returns></returns>
-        public AzureCosmosModel GetCosmosModel( string typeName )
-        {
-            /////内存中已经存在这个表则直接返回
-            if (CosmosDict.typeCosmos.TryGetValue(typeName, out AzureCosmosModel AzureCosmosModel))
-            {
-                return AzureCosmosModel;
-            }
-            else {
-                return null;
-            }
-          
-        }
-        /// <summary>
-        /// 初始化数据配置信息
-        /// </summary>
-        /// <returns></returns>
-        public async Task InitializeDatabase()
-        {
-            //    string[] DatabaseIds = BaseConfigModel.Configuration.GetSection("Azure:Cosmos:Database").Get<string[]>();
-            string[] DatabaseIds =_optionsMonitor.Get("Default").Database;
-
-            
-            bool isMonitor = false;
-            string leases = "leases";
-            if (DatabaseIds != null)
-            {
-                foreach (string DatabaseId in DatabaseIds)
-                {
-                    CosmosDatabase databaseDef = GetCosmosClient().GetDatabase(DatabaseId);
-                    AsyncPageable<ContainerProperties> resultSetIterator = databaseDef.GetContainerQueryIterator<ContainerProperties>();
-                    await foreach (var container in resultSetIterator)
-                    {
-                        CosmosDict.nameCosmos.TryAdd(container.Id, new AzureCosmosModel { container = databaseDef.GetContainer(container.Id), partitionKey = container.PartitionKeyPath.Replace("/", ""), cache = false, monitor = false, database = databaseDef });
-                    }
-                }
-            }
-            //获取数据库所有的表
-            // List<Type> types = ReflectorExtensions.GetAllTypeAsAttribute<CosmosDBAttribute>(BaseConfigModel.Configuration.GetSection("Azure:Cosmos:ScanModel").Get<string[]>() );
-            List<Type> types = new List<Type>() ;
-            try {
-                types = ReflectorExtensions.GetAllTypeAsAttribute<CosmosDBAttribute>(_optionsMonitor.Get("Default").ScanModel);
-            } catch(Exception e) {
-                Console.WriteLine(e.StackTrace);
-            }
-            foreach (Type type in types)
-            {
-                string PartitionKey = AzureCosmosUtil.GetPartitionKey(type);
-                string CollectionName = "";
-                bool cache = false;
-                bool monitor = false;
-                IEnumerable<CosmosDBAttribute> attributes = type.GetCustomAttributes<CosmosDBAttribute>(true);
-                if (attributes != null && !string.IsNullOrEmpty(attributes.First<CosmosDBAttribute>().Name))
-                {
-                    CollectionName = attributes.First<CosmosDBAttribute>().Name;
-                }
-                else
-                {
-                    throw new BizException("必须指定容器名", ResponseCode.PARAMS_ERROR);
-                }
-                if (attributes.First<CosmosDBAttribute>().Cache)
-                {
-                    cache = attributes.First<CosmosDBAttribute>().Cache;
-                }
-                if (attributes.First<CosmosDBAttribute>().Monitor)
-                {
-                    monitor = attributes.First<CosmosDBAttribute>().Monitor;
-                    if (monitor)
-                    {
-                        isMonitor = true;
-                    }
-                }
-              
-                //如果表存在于数据则检查RU是否变动,如果不存在则执行创建DocumentCollection
-                if (CosmosDict.nameCosmos.TryGetValue(CollectionName, out AzureCosmosModel AzureCosmosModel))
-                { //更新RU
-
-                    AzureCosmosModel.cache = cache;
-                    CosmosContainer container = GetCosmosClient().GetDatabase(attributes.First().Database).GetContainer(AzureCosmosModel.container.Id);
-                    AzureCosmosModel cosmos = new AzureCosmosModel { container = container, cache = cache, monitor = monitor, type = type, partitionKey = PartitionKey };
-                    CosmosDict.nameCosmos[CollectionName] = cosmos;
-                    CosmosDict.typeCosmos.Add(type.Name, cosmos);
-                }
-                else
-                {
-                    ContainerProperties containerProperties = new ContainerProperties { Id = CollectionName, DefaultTimeToLive = -1 };
-                    if (!string.IsNullOrEmpty(PartitionKey))
-                    {
-                        containerProperties.PartitionKeyPath = "/" + PartitionKey;
-                    }
-                    CosmosDatabase database = GetCosmosClient().GetDatabase(attributes.First().Database);
-                    CosmosContainer containerWithConsistentIndexing = database.GetContainer(CollectionName);
-                    AzureCosmosModel cosmos = new AzureCosmosModel { container = containerWithConsistentIndexing, cache = cache, monitor = monitor, type = type, partitionKey = PartitionKey,database=database };
-                    CosmosDict.nameCosmos[CollectionName] = cosmos;
-                    CosmosDict.typeCosmos.Add(type.Name, cosmos);
-                }
-            }
-            if (isMonitor)
-            {
-                if (DatabaseIds != null)
-                {
-                    foreach (string DatabaseId in DatabaseIds)
-                    {
-                        CosmosDatabase database = GetCosmosClient().GetDatabase(DatabaseId);
-                        CosmosContainer leaseContainer =   database.GetContainer(leases);
-                        CosmosDict.nameCosmos.TryAdd(leases, new AzureCosmosModel { container = leaseContainer, cache = false, monitor = false, partitionKey = "/id", database = database });
-                    }
-                }
-            }
-        }
     }
 }

+ 4 - 4
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactoryExtensions.cs

@@ -8,12 +8,12 @@ namespace TEAMModelOS.SDK.DI
 {
     public static class AzureCosmosFactoryExtensions
     {
-        public static IServiceCollection AddAzureCosmos(this IServiceCollection services, AzureCosmosFactoryOptions options, string name = "Default")
+        public static IServiceCollection AddAzureCosmos(this IServiceCollection services, string connectionString, string name = "Default")
         {
-            if (services == null) throw new ArgumentNullException(nameof(services));            
-            if (options == null) throw new ArgumentNullException(nameof(options));
+            if (services == null) throw new ArgumentNullException(nameof(services));
+            if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
             services.TryAddSingleton<AzureCosmosFactory>();
-            services.Configure<AzureCosmosFactoryOptions>(name, o => { o.Name = name; o.ConnectionString = options.ConnectionString;o.ScanModel = options.ScanModel; o.Database=options.Database ; });
+            services.Configure<AzureCosmosFactoryOptions>(name, o => { o.Name = name; o.CosmosConnectionString = connectionString; });
             return services;
         }
     }

+ 1 - 3
TEAMModelOS.SDK/DI/AzureCosmos/AzureCosmosFactoryOptions.cs

@@ -7,9 +7,7 @@ namespace TEAMModelOS.SDK.DI
     public class AzureCosmosFactoryOptions
     {
         public string Name { get; set; }
-        public string ConnectionString { get; set; }
-        public string[] Database { get; set; }
-        public string[] ScanModel { get; set; }
+        public string CosmosConnectionString { get; set; }        
     }
 
    

+ 668 - 0
TEAMModelOS.SDK/DI/AzureCosmos/Inner/AzureCosmosExOld.cs

@@ -0,0 +1,668 @@
+//using Azure;
+//using Azure.Cosmos;
+//using System;
+//using System.Collections.Generic;
+//using System.Diagnostics;
+//using System.IO;
+//using System.Linq;
+//using System.Text;
+//using System.Text.Json;
+//using System.Threading.Tasks;
+//using TEAMModelOS.SDK.Context.Exception;
+//using TEAMModelOS.SDK.Models;
+
+//namespace TEAMModelOS.SDK.DI.AzureCosmos.Inner
+//{
+//    public static class AzureCosmosExOld
+//    {
+//        /// <summary>
+//        /// 缓存前缀
+//        /// </summary>
+//        private const string CacheCosmosPrefix = "cosmos:";
+//        /// <summary>
+//        /// ttl时长 1秒
+//        /// </summary>
+//        private const int ttl = 1;
+//        /// <summary>
+//        /// 分页大小
+//        /// </summary>
+//        private const int pageSize = 200;
+//        /// <summary>
+//        /// 超时时间
+//        /// </summary>
+//        private const int timeoutSeconds = 86400;
+
+//        // TODO 此区需移除或优化
+//        #region 此区需移除或优化 
+
+//        public static async Task<T> SaveOrUpdate<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
+//        {
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//            entity.pk = container.type.Name;
+//            ItemResponse<T> response = await container.container.UpsertItemAsync(item: entity);
+//            if (container.cache && RedisHelper.Instance != null)
+//            {
+//                if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
+//                {
+//                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
+//                }
+//                else
+//                {
+//                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
+//                    await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
+//                }
+//            }
+//            return response.Value;
+//        }
+//        public static async Task<List<T>> SaveOrUpdateAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
+//        {
+//            Type type = typeof(T);
+//            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            bool flag = false;
+//            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
+//            {
+//                flag = true;
+//            }
+
+//            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
+
+//            Stopwatch stopwatch = Stopwatch.StartNew();
+//            for (int i = 0; i < pages; i++)
+//            {
+//                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
+//                List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
+//                lists.ForEach(async x =>
+//                {
+//                    x.pk = type.Name;
+//                    MemoryStream stream = new MemoryStream();
+//                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
+//                    object o = type.GetProperty(partitionKey).GetValue(x, null);
+//                    KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
+//                    itemsToInsert.Add(keyValue);
+//                });
+//                List<Task> tasks = new List<Task>(lists.Count);
+//                itemsToInsert.ForEach(item =>
+//                {
+//                    tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
+//                        .ContinueWith((Task<Response> task) =>
+//                        {
+//                        }
+//                        ));
+//                });
+//                await Task.WhenAll(tasks);
+//                if (container.cache && RedisHelper.Instance != null)
+//                {
+//                    lists.ForEach(async x => {
+//                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
+//                    });
+//                }
+//            }
+//            if (container.cache && RedisHelper.Instance != null && !flag)
+//            {
+//                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
+//            }
+//            stopwatch.Stop();
+//            return enyites;
+//        }
+//        public static async Task<List<int>> FindCountByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict)
+//        {
+//            Type type = typeof(T);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            string pk = type.Name;
+//            StringBuilder sql = new StringBuilder("select  value count(c)  from c");
+//            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
+//            if (cosmosDbQuery == null)
+//            {
+//                return new List<int> { 0 };
+//            }
+//            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//            AsyncPageable<int> query = container.container.GetItemQueryIterator<int>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
+//            return await ResultsFromFeedIterator(query);
+//        }
+
+//        public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict)
+//        {
+//            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
+//            {
+//                string pk = container.type.Name;
+//                dict.Remove("@CURRPAGE");
+//                dict.Remove("@PAGESIZE");
+//                dict.Remove("@ASC");
+//                dict.Remove("@DESC");
+//                StringBuilder sql = new StringBuilder("select  value count(c)  from c");
+//                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
+//                if (cosmosDbQuery == null)
+//                {
+//                    return new List<dynamic> { 0 };
+//                }
+//                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
+//                return await ResultsFromFeedIterator(query);
+//            }
+//            else
+//            {
+//                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
+//            }
+//        }
+//        public static async Task<List<dynamic>> FindCountByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, JsonElement json)
+//        {
+//            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
+//            {
+//                Dictionary<string, object> dict = new Dictionary<string, object>();
+//                var emobj = json.EnumerateObject();
+//                while (emobj.MoveNext())
+//                {
+//                    if (emobj.Current.Name != "@CURRPAGE" ||
+//                        emobj.Current.Name != "@PAGESIZE" ||
+//                        emobj.Current.Name != "@ASC" ||
+//                        emobj.Current.Name != "@DESC")
+//                    {
+//                        dict[emobj.Current.Name] = emobj.Current.Value;
+//                    }
+//                }
+//                string pk = container.type.Name;
+//                StringBuilder sql = new StringBuilder("select  value count(c)  from c");
+//                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
+//                if (cosmosDbQuery == null)
+//                {
+//                    return new List<dynamic> { 0 };
+//                }
+//                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
+//                return await ResultsFromFeedIterator(query);
+//            }
+//            else
+//            {
+//                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
+//            }
+//        }
+//        public static async Task<T> Update<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
+//        {
+//            Type type = typeof(T);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
+//            entity.pk = type.Name;
+//            object o = type.GetProperty(partitionKey).GetValue(entity, null);
+//            ItemResponse<T> response = await container.container.ReplaceItemAsync(entity, entity.id, new PartitionKey(o.ToString()));
+//            if (container.cache && RedisHelper.Instance != null)
+//            {
+//                if (!RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
+//                {
+//                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
+//                }
+//                else
+//                {
+//                    await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, entity.id, entity);
+//                    await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
+//                }
+//            }
+//            return response.Value;
+//        }
+//        internal class Item
+//        {
+//            public string id { get; set; }
+//            public string pk { get; set; }
+//            public MemoryStream stream { get; set; }
+//        }
+//        public static async Task<List<T>> UpdateAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
+//        {
+//            //await Task.Run(() => Parallel.ForEach(entities, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (item) =>
+//            //{
+//            //    Task.WaitAll(Update(item));
+//            //}));
+//            Type type = typeof(T);
+//            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            bool flag = false;
+//            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
+//            {
+//                flag = true;
+//            }
+//            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
+
+//            Stopwatch stopwatch = Stopwatch.StartNew();
+//            for (int i = 0; i < pages; i++)
+//            {
+//                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
+//                List<Item> itemsToInsert = new List<Item>();
+//                lists.ForEach(async x =>
+//                {
+//                    x.pk = type.Name;
+//                    MemoryStream stream = new MemoryStream();
+//                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
+//                    object o = type.GetProperty(partitionKey).GetValue(x, null);
+//                    Item keyValue = new Item { id = x.id, pk = o.ToString(), stream = stream };
+//                    itemsToInsert.Add(keyValue);
+//                });
+//                List<Task> tasks = new List<Task>(lists.Count);
+//                itemsToInsert.ForEach(item =>
+//                {
+//                    tasks.Add(container.container.ReplaceItemStreamAsync(item.stream, item.id, new PartitionKey(item.pk))
+//                        .ContinueWith((Task<Response> task) =>
+//                        {
+//                            //using (ResponseMessage response = task.Result)
+//                            //{
+//                            //    if (!response.IsSuccessStatusCode)
+//                            //    {
+//                            //    }
+//                            //}
+//                        }
+//                        ));
+//                });
+//                await Task.WhenAll(tasks);
+//                if (container.cache && RedisHelper.Instance != null)
+//                {
+//                    lists.ForEach(async x => {
+//                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
+//                    });
+//                }
+//            }
+//            if (container.cache && RedisHelper.Instance != null && !flag)
+//            {
+//                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
+//            }
+//            stopwatch.Stop();
+//            return enyites;
+//        }
+//        public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict, List<string> propertys = null) where T : CosmosEntity
+//        {
+//            StringBuilder sql;
+//            sql = SQLHelper.GetSQLSelect(propertys);
+//            string pk = typeof(T).Name;
+//            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
+//            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//            return await ResultsFromQueryAndOptions<T>(azureCosmosFactory, cosmosDbQuery, queryRequestOptions);
+//        }
+//        public static async Task<List<T>> FindByDict<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement jsonElement, List<string> propertys = null) where T : CosmosEntity
+//        {
+//            StringBuilder sql;
+//            sql = SQLHelper.GetSQLSelect(propertys);
+//            string pk = typeof(T).Name;
+//            //Dictionary<string, object> dict = new Dictionary<string, object>();
+//            /* var emobj = jsonElement.EnumerateObject();
+//             while (emobj.MoveNext())
+//             {
+//                 dict[emobj.Current.Name] = emobj.Current.Value;
+//             }
+//             //处理code
+//             if (dict.TryGetValue("code", out object _))
+//             {
+//                 dict.Remove("code");
+//             }*/
+//            AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(jsonElement, sql, pk);
+//            QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//            return await ResultsFromQueryAndOptions<T>(azureCosmosFactory, cosmosDbQuery, queryRequestOptions);
+//        }
+//        public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, JsonElement json, List<string> propertys = null)
+//        {
+//            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
+//            {
+
+//                string pk = container.type.Name;
+//                StringBuilder sql;
+//                sql = SQLHelper.GetSQLSelect(propertys);
+//                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(json, sql, pk);
+//                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
+//                return await ResultsFromFeedIterator(query);
+//            }
+//            else
+//            {
+//                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
+//            }
+//        }
+//        public static async Task<List<dynamic>> FindByDict(this AzureCosmosFactory azureCosmosFactory, string CollectionName, Dictionary<string, object> dict, List<string> propertys = null)
+//        {
+//            if (azureCosmosFactory.CosmosDict.typeCosmos.TryGetValue(CollectionName, out AzureCosmosModel container))
+//            {
+
+//                string pk = container.type.Name;
+//                StringBuilder sql;
+//                sql = SQLHelper.GetSQLSelect(propertys);
+//                AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql, pk);
+//                QueryRequestOptions queryRequestOptions = GetDefaultQueryRequestOptions(itemsPerPage: GetEffectivePageSize(-1, null));
+//                AsyncPageable<dynamic> query = container.container.GetItemQueryIterator<dynamic>(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryRequestOptions);
+//                return await ResultsFromFeedIterator(query);
+//            }
+//            else
+//            {
+//                throw new BizException("CollectionName named:" + CollectionName + " dose not exsit in Database!");
+//            }
+//        }
+//        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<IdPk> ids) where T : CosmosEntity
+//        {
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//            List<IdPk> idPks = new List<IdPk>();
+//            if (container.monitor)
+//            {
+//                List<T> list = await azureCosmosFactory.FindByDict<T>(new Dictionary<string, object>() { { "id", ids.Select(x => x.id).ToArray() } });
+//                list = await azureCosmosFactory.DeleteTTL(list);
+//                return ids;
+//            }
+//            else
+//            {
+//                int pages = (int)Math.Ceiling((double)ids.Count / pageSize);
+//                Stopwatch stopwatch = Stopwatch.StartNew();
+//                for (int i = 0; i < pages; i++)
+//                {
+//                    List<IdPk> lists = ids.Skip((i) * pageSize).Take(pageSize).ToList();
+//                    List<Task> tasks = new List<Task>(lists.Count);
+//                    lists.ForEach(item =>
+//                    {
+//                        tasks.Add(container.container.DeleteItemStreamAsync(item.id, new PartitionKey(item.pk))
+//                            .ContinueWith((Task<Response> task) =>
+//                            {
+//                                using (Response response = task.Result)
+//                                {
+//                                    idPks.Add(new IdPk { id = item.id, pk = item.pk, Status = response.Status });
+//                                    //    if (!response.IsSuccessStatusCode)
+//                                    //    {
+//                                    //    }
+//                                }
+//                            }
+//                            ));
+//                    });
+//                    await Task.WhenAll(tasks);
+//                    if (container.cache && RedisHelper.Instance != null)
+//                    {
+//                        lists.ForEach(async x => {
+//                            await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
+//                        });
+//                    }
+//                }
+//                stopwatch.Stop();
+//                return idPks;
+//            }
+//        }
+//        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, Dictionary<string, object> dict) where T : CosmosEntity
+//        {
+//            if (dict.Keys.Count > 0)
+//            {
+//                List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
+
+//                return await azureCosmosFactory.DeleteAll(list);
+//            }
+//            else
+//            {
+//                throw new BizException("参数为空", 500);
+//            }
+
+//        }
+//        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, JsonElement dict) where T : CosmosEntity
+//        {
+//            List<T> list = await azureCosmosFactory.FindByDict<T>(dict);
+//            return await azureCosmosFactory.DeleteAll(list);
+//        }
+//        public static async Task<List<IdPk>> DeleteAll<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
+//        {
+//            Type type = typeof(T);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            List<IdPk> idPks = new List<IdPk>();
+
+//            string pk = AzureCosmosUtil.GetPartitionKey(type);
+//            if (container.monitor)
+//            {
+//                enyites = await azureCosmosFactory.DeleteTTL(enyites);
+//                foreach (T t in enyites)
+//                {
+//                    object o = type.GetProperty(pk).GetValue(t, null);
+//                    idPks.Add(new IdPk { id = t.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent });
+//                }
+//                return idPks;
+//            }
+//            else
+//            {
+//                int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
+//                Stopwatch stopwatch = Stopwatch.StartNew();
+//                for (int i = 0; i < pages; i++)
+//                {
+//                    List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
+//                    List<KeyValuePair<PartitionKey, string>> itemsToInsert = new List<KeyValuePair<PartitionKey, string>>();
+//                    lists.ForEach(x =>
+//                    {
+//                        object o = type.GetProperty(pk).GetValue(x, null);
+//                        KeyValuePair<PartitionKey, string> keyValue = new KeyValuePair<PartitionKey, string>(new PartitionKey(o.ToString()), x.id);
+//                        itemsToInsert.Add(keyValue);
+//                    });
+
+//                    List<Task> tasks = new List<Task>(lists.Count);
+//                    itemsToInsert.ForEach(item =>
+//                    {
+//                        tasks.Add(container.container.DeleteItemStreamAsync(item.Value, item.Key)
+//                        .ContinueWith((Task<Response> task) =>
+//                        {
+//                            using (Response response = task.Result)
+//                            {
+
+//                                idPks.Add(new IdPk { id = item.Value, pk = item.Key.ToString(), Status = response.Status });
+
+//                            }
+//                        }
+//                        ));
+//                    });
+//                    await Task.WhenAll(tasks); if (container.cache && RedisHelper.Instance != null)
+//                    {
+//                        lists.ForEach(async x => {
+//                            await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
+//                        });
+//                    }
+//                }
+//                stopwatch.Stop();
+//                return idPks;
+//            }
+//        }
+//        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, IdPk idPk) where T : CosmosEntity
+//        {
+//            return await DeleteAsync<T>(azureCosmosFactory, idPk.id, idPk.pk);
+//        }
+//        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, string id, string pk) where T : CosmosEntity
+//        {
+
+//            //  pk =AzureCosmosUtil.GetPartitionKey<T>();
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//            if (container.monitor)
+//            {
+//                List<T> list = await FindByDict<T>(azureCosmosFactory, new Dictionary<string, object>() { { "id", id } });
+//                if (list.Count > 0)
+//                {
+//                    await DeleteTTL<T>(azureCosmosFactory, list);
+//                    return new IdPk { id = id, pk = pk, StatusCode = HttpStatusCode.NoContent };
+//                }
+//                else
+//                {
+//                    throw new BizException("未找到ID匹配的数据,删除失败");
+//                }
+//            }
+//            else
+//            {
+//                Response response = await container.container.DeleteItemStreamAsync(id: id, partitionKey: new PartitionKey(pk));
+//                if (container.cache && RedisHelper.Instance != null)
+//                {
+//                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, id);
+//                }
+//                return new IdPk { id = id, pk = pk, Status = response.Status };
+//            }
+
+//        }
+//        public static async Task<IdPk> DeleteAsync<T>(this AzureCosmosFactory azureCosmosFactory, T entity) where T : CosmosEntity
+//        {
+//            Type type = typeof(T);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
+
+//            object o = type.GetProperty(partitionKey).GetValue(entity, null);
+//            if (container.monitor)
+//            {
+//                await DeleteTTL<T>(azureCosmosFactory, new List<T>() { entity });
+//                return new IdPk { id = entity.id, pk = o.ToString(), StatusCode = HttpStatusCode.NoContent };
+//            }
+//            else
+//            {
+//                Response response = await container.container.DeleteItemStreamAsync(id: entity.id, partitionKey: new PartitionKey(o.ToString()));
+//                if (container.cache && RedisHelper.Instance != null)
+//                {
+//                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, entity.id);
+//                }
+//                return new IdPk { id = entity.id, pk = partitionKey, Status = response.Status };
+//            }
+//        }
+//        public static async Task<List<T>> FindSQL<T>(this AzureCosmosFactory azureCosmosFactory, string sql, Dictionary<string, object> Parameters = null) where T : CosmosEntity
+//        {
+//            if (sql.Contains(".pk"))
+//            {
+//                AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//                QueryRequestOptions queryOptions = GetQueryRequestOptions(GetEffectivePageSize(-1, null));
+//                if (Parameters != null)
+//                {
+//                    AzureCosmosQuery cosmosDbQuery = new AzureCosmosQuery
+//                    {
+//                        QueryText = sql,
+//                        Parameters = Parameters
+//                    };
+//                    AsyncPageable<T> feedIterator = container.container
+//                    .GetItemQueryIterator<T>(cosmosDbQuery.CosmosQueryDefinition, requestOptions: queryOptions);
+//                    return await ResultsFromFeedIterator(feedIterator);
+//                }
+//                else
+//                {
+//                    QueryDefinition queryDefinition = new QueryDefinition(sql);
+//                    return await ResultsFromFeedIterator<T>(container.container.GetItemQueryIterator<T>(queryDefinition));
+//                }
+//            }
+//            else
+//            {
+//                throw new BizException("查询参数必须设置 .pk ", ResponseCode.PARAMS_ERROR);
+//            }
+//        }
+//        /// <summary>
+//        /// 偌TTL刉壺
+//        /// </summary>
+//        /// <typeparam name="T"></typeparam>
+//        /// <param name="list"></param>
+//        /// <returns></returns>
+//        private static async Task<List<T>> DeleteTTL<T>(this AzureCosmosFactory azureCosmosFactory, List<T> list) where T : CosmosEntity
+//        {
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//            list.ForEach(x => { x.ttl = ttl; });
+//            list = await DeleteTTlALL(azureCosmosFactory, list);
+//            if (container.cache && RedisHelper.Instance != null)
+//            {
+//                list.ForEach(async x => {
+//                    await RedisHelper.HDelAsync(CacheCosmosPrefix + container.container.Id, x.id);
+//                });
+//            }
+//            return list;
+//        }
+//        private static async Task<List<T>> DeleteTTlALL<T>(this AzureCosmosFactory azureCosmosFactory, List<T> enyites) where T : CosmosEntity
+//        {
+//            Type type = typeof(T);
+//            int pages = (int)Math.Ceiling((double)enyites.Count / pageSize);
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(type.Name);
+//            bool flag = false;
+//            if (RedisHelper.Exists(CacheCosmosPrefix + container.container.Id))
+//            {
+//                flag = true;
+//            }
+//            string partitionKey = AzureCosmosUtil.GetPartitionKey(type);
+
+//            Stopwatch stopwatch = Stopwatch.StartNew();
+//            for (int i = 0; i < pages; i++)
+//            {
+//                List<T> lists = enyites.Skip((i) * pageSize).Take(pageSize).ToList();
+//                List<KeyValuePair<PartitionKey, Stream>> itemsToInsert = new List<KeyValuePair<PartitionKey, Stream>>();
+//                lists.ForEach(async x =>
+//                {
+//                    x.pk = type.Name;
+//                    //x.ttl = null;
+//                    MemoryStream stream = new MemoryStream();
+//                    await JsonSerializer.SerializeAsync(stream, x, new JsonSerializerOptions { IgnoreNullValues = true });
+//                    object o = type.GetProperty(partitionKey).GetValue(x, null);
+//                    KeyValuePair<PartitionKey, Stream> keyValue = new KeyValuePair<PartitionKey, Stream>(new PartitionKey(o.ToString()), stream);
+//                    itemsToInsert.Add(keyValue);
+//                });
+//                List<Task> tasks = new List<Task>(lists.Count);
+//                itemsToInsert.ForEach(item =>
+//                {
+//                    tasks.Add(container.container.UpsertItemStreamAsync(item.Value, item.Key)
+//                        .ContinueWith((Task<Response> task) =>
+//                        {
+//                            //using (ResponseMessage response = task.Result)
+//                            //{
+//                            //    if (!response.IsSuccessStatusCode)
+//                            //    {
+//                            //    }
+//                            //}
+//                        }
+//                        ));
+//                });
+//                await Task.WhenAll(tasks);
+//                if (container.cache && RedisHelper.Instance != null)
+//                {
+//                    lists.ForEach(async x => {
+//                        await RedisHelper.HSetAsync(CacheCosmosPrefix + container.container.Id, x.id, x);
+//                    });
+//                }
+//            }
+//            if (container.cache && RedisHelper.Instance != null && !flag)
+//            {
+//                await RedisHelper.ExpireAsync(CacheCosmosPrefix + container.container.Id, timeoutSeconds);
+//            }
+//            stopwatch.Stop();
+//            return enyites;
+//        }
+//        private static QueryRequestOptions GetDefaultQueryRequestOptions(int? itemsPerPage = null, int? maxBufferedItemCount = null, int? maxConcurrency = null)
+//        {
+//            QueryRequestOptions queryRequestOptions = new QueryRequestOptions
+//            {
+//                MaxItemCount = itemsPerPage == -1 ? 1000 : itemsPerPage,
+//                MaxBufferedItemCount = maxBufferedItemCount ?? 100,
+//                MaxConcurrency = maxConcurrency ?? 50
+//            };
+//            return queryRequestOptions;
+//        }
+//        private static int GetEffectivePageSize(int itemsPerPage, int? maxItemCount)
+//        {
+//            return itemsPerPage == -1 ? maxItemCount ?? itemsPerPage : Math.Min(maxItemCount ?? itemsPerPage, itemsPerPage);
+//        }
+//        private static async Task<List<T>> ResultsFromQueryAndOptions<T>(this AzureCosmosFactory azureCosmosFactory, AzureCosmosQuery cosmosDbQuery, QueryRequestOptions queryOptions)
+//        {
+//            if (cosmosDbQuery == null)
+//            {
+//                return null;
+//            }
+//            AzureCosmosModel container = azureCosmosFactory.GetCosmosModel(typeof(T).Name);
+//            AsyncPageable<T> query = container.container.GetItemQueryIterator<T>(
+//                queryDefinition: cosmosDbQuery.CosmosQueryDefinition,
+//                requestOptions: queryOptions);
+
+//            return await ResultsFromFeedIterator(query);
+//        }
+//        private static async Task<List<T>> ResultsFromFeedIterator<T>(AsyncPageable<T> query, int? maxItemCount = null)
+//        {
+//            List<T> results = new List<T>();
+
+//            await foreach (T t in query)
+//            {
+//                results.Add(t);
+//                if (results.Count == maxItemCount)
+//                {
+//                    return results;
+//                }
+//            }
+//            return results;
+//        }
+//        private static QueryRequestOptions GetQueryRequestOptions(int itemsPerPage)
+//        {
+//            QueryRequestOptions queryRequestOptions = new QueryRequestOptions
+//            {
+//                MaxItemCount = itemsPerPage
+//            };
+
+//            return queryRequestOptions;
+//        }
+//    }
+
+//    #endregion
+//}
+//}

+ 1 - 22
TEAMModelOS/ClientApp/src/api/knowledge.js

@@ -1,39 +1,18 @@
 import { post } from '@/api/http'
 export default {
-    // 获取标准知识点
-    GetStantardPoints: function(data) {
-        return post('/api/knowledge/findStdPoint', data)
-    },
-    // 获取标准的知识块及包含的知识点
-    GetStantardBlocks: function(data) {
-        return post('/common/knowledge/findStdBlockPoint', data)
-    },
     // 获取知识块知识点
     GetSchoolPoints: function(data) {
         return post('/common/knowledge/find', data)
     },
-    // 获取知识块知识点
-    GetSchoolBlocks: function(data) {
-        return post('/common/knowledge/find', data)
-    },
     // 批量更新保存知识点知识块
     SaveOrUpdateKnowledge: function(data) {
         return post('/common/knowledge/upsert-all', data)
     },
-    // �ֶ�����ѧУ��˽��֪ʶ��
     SaveOrUpdateSchoolPoint: function(data) {
         return post('/common/knowledge/SaveOrUpdateAllSchoolPoint', data)
     },
     // 删除知识点知识块
     DeleteSchoolPoint: function(data) {
-        return post('/common/knowledge/delete', data)
-    },
-    // 删除知识点知识块
-    DeleteSchoolBlock: function(data) {
-        return post('/common/knowledge/delete', data)
-    },
-    // 根据id集合获取知识点知识块
-    FindKnowledgebyId: function(data) {
-        return post('/common/knowledge/findByIds', data)
+        return post('/ /knowledge/delete', data)
     },
 }

+ 0 - 10
TEAMModelOS/ClientApp/src/components/selflearn/ExerciseList.vue

@@ -382,16 +382,6 @@
                 return [...new Set(ids)];
             },
 
-            /**
-             * 获取筛选结果数量
-             * @param data
-             */
-            getResultCount(data) {
-                this.$api.newEvaluation.FindCount(data).then((res) => {
-                    this.totalNum = res.result.data[0];
-                });
-            },
-
             /**
              * 根据知识点id集合换取知识点对象集合
              * @param ids

+ 1 - 6
TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/LessonTest.vue

@@ -366,7 +366,6 @@
             opentestWithSubject(item) {
                 console.log(item)
                 if (item.code !== '') {
-                    console.log('5645645646354')
                     this.getPaper(item)
                 }
             },
@@ -380,16 +379,12 @@
                         code: key[(key.length - 1)],
                         blob: data.blob
                     }
-                    //let code = {
-                    //    scope: 'school',
-                    //    code: 'hbcn',
-                    //    blob: "/paper/预设试卷名称"
-                    //}
                     this.selectData = await this.$evTools.getStuPaper(code)
                     console.log(this.selectData)
                     if (this.selectData.item.length > 0) {
                         this.$store.commit("ToggleLessonTestPopWithSubject", data)
                         this.$store.commit("SetPaperInfo", this.selectData)
+                        this.$store.commit("SetExamInfo", data)
                     }
                 }
             },

File diff suppressed because it is too large
+ 51 - 35
TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/LessonTestPop.vue


+ 94 - 81
TEAMModelOS/ClientApp/src/components/student-web/EventView/EventContentTypeTemplate/composePaper.vue

@@ -5,93 +5,106 @@
 </template>
 <script>
     import E from 'wangeditor'
-	export default {
-		components: {
+    export default {
+        components: {
 
         },
         props: {
-            index:""
+            index: {
+                type: Number,
+                default: -1
+            },
+            textData: {
+                type: Array,
+                default: () => {
+                    return []
+                }
+            }
         },
-		data() {
-			return {
-				tabName: 'exercise',
-                editorContent:""
-			}
-		},
-		created() {
-
-		},
-		methods: {
+        data() {
+            return {
+                tabName: 'exercise',
+                editorContent: "",
+                examInfo: [],
+                editor: null
+            }
+        },
+        created() {
 
-		},
-		mounted() {
-            var editor = new E("#textArea");
-            editor.customConfig.onchange = html => {
-                this.editorContent = html;
-                if (this.editorContent !== "") {
-                    console.log('454564164556')
-                    this.$emit("change", this.editorContent,this.index)
+        },
+        methods: {
+            getInfo() {
+                this.initEditor()
+                this.examInfo = []
+                console.log('变化数据')
+                console.log(this.textData)
+                if (this.textData.length > 0) {
+                    this.examInfo = [...this.textData]
+                        this.editor.txt.html(this.examInfo[0])
                 }
-            };
-            editor.customConfig.menus = [
-                "fontSize", // 字号
-                "fontName", // 字体
-                "italic", // 斜体
-                "underline", // 下划线
-                "link", // 插入链接
-                "justify", // 对齐方式
-                "quote", // 引用
-                "emoticon", // 表情
-                "image", // 插入图片
-                "video", // 插入视频
-                "undo", // 撤销
-                "redo" // 重复
-            ]
-            editor.customConfig.zIndex = 1
-            //// 选项编辑器失焦隐藏工具栏
-            //editor.customConfig.onblur = function () {
-            //    let allToolbars = document.getElementsByClassName('textArea')
-            //    for (let i = 0; i < allToolbars.length; i++) {
-            //        if (allToolbars[i].children.length) {
-            //            allToolbars[i].children[0].style.visibility = 'hidden'
-            //        }
-            //    }
-            //}
-            editor.customConfig.linkImgCallback = function (url) {
-                console.log(url); // url 即插入图片的地址
-            };
-            editor.customConfig.linkCheck = function (text, link) {
-                console.log(text); // 插入的文字
-                console.log(link); // 插入的链接
-                return true; // 返回 true 表示校验成功
-            };
-            // 自定义配置颜色(字体颜色、背景色)
-            editor.customConfig.colors = [
-                "#000000",
-                "#eeece0",
-                "#1c487f",
-                "#4d80bf",
-                "#c24f4a",
-                "#8baa4a",
-                "#7b5ba1",
-                "#46acc8",
-                "#f9963b",
-                "#ffffff"
-            ];
-            // 自定义字体
-            editor.customConfig.fontNames = [
-                "宋体",
-                "微软雅黑",
-                "Verdana"
-            ];
-            // 隐藏“网络图片”tab
-            editor.customConfig.showLinkImg = false;
-            // 下面两个配置,使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用!!!
-            editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片不建议使用这种,我只是图个方便
-            // editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器
-            editor.create();
-
-		}
+                console.log(this.textData)
+            },
+            initEditor() {
+                this.editorContent = ""
+                this.editor = new E("#textArea");
+                this.editor.customConfig.onchange = html => {
+                    this.editorContent = html;
+                    if (this.editorContent !== "") {
+                        this.$emit("dataChange", this.editorContent, this.index)
+                    }
+                };
+                this.editor.customConfig.menus = [
+                    "fontSize", // 字号
+                    "fontName", // 字体
+                    "italic", // 斜体
+                    "underline", // 下划线
+                    "link", // 插入链接
+                    "justify", // 对齐方式
+                    "quote", // 引用
+                    "emoticon", // 表情
+                    "image", // 插入图片
+                    "video", // 插入视频
+                    "undo", // 撤销
+                    "redo" // 重复
+                ]
+                this.editor.customConfig.zIndex = 1
+                this.editor.customConfig.linkImgCallback = function (url) {
+                    console.log(url); // url 即插入图片的地址
+                };
+                this.editor.customConfig.linkCheck = function (text, link) {
+                    console.log(text); // 插入的文字
+                    console.log(link); // 插入的链接
+                    return true; // 返回 true 表示校验成功
+                };
+                // 自定义字体
+                this.editor.customConfig.fontNames = [
+                    "宋体",
+                    "微软雅黑",
+                    "Verdana"
+                ];
+                this.editor.customConfig.showLinkImg = false;
+                // 下面两个配置,使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用!!!
+                this.editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片不建议使用这种,我只是图个方便
+                // editor.customConfig.uploadImgServer = '/upload'  // 上传图片到服务器
+                this.editor.create();
+                this.editor.txt.clear()
+                if (this.examInfo.length > 0) {
+                    this.editor.txt.html(this.examInfo[0])
+                } 
+            }
+        },
+        mounted() {
+            this.initEditor()
+            this.getInfo()
+        },
+        watch: {
+            index() {
+                console.log(this.index)
+                this.getInfo()
+                deep: true;
+                immediate:true
+            }
+        }
 	}
 </script>
 <style>

+ 1 - 0
TEAMModelOS/ClientApp/src/components/student-web/EventView/EventList.vue

@@ -640,6 +640,7 @@
             },
 
             sentSelectedEventTitle(item) {
+                console.log(item)
                 this.$router.push({
                     path: "/studentWeb/eventView",
                     query: {

+ 11 - 0
TEAMModelOS/ClientApp/src/store/module/studentWeb.js

@@ -25,6 +25,7 @@ export default {
         },
         paperInfo: {},
         Item: {}, //存放活動相關的狀態
+        examInfo: {},
         tempfinishedItem: [], //用來暫存目前完成的項目ID
         tempfinishedItemtime: [],
         CountedIsDonePercent: myMockData.initialfinishResult, //存放活動完成度值,初始值先從Api抓資料,後續透過vuex抓狀態變化
@@ -138,8 +139,15 @@ export default {
             state.currentQuestionNo = no;
         },
         SetPaperInfo(state, data) {
+            console.log('存入数据')
+            console.log(data)
             state.paperInfo = data
         },
+        SetExamInfo(state, data) {
+            console.log('存入数据')
+            console.log(data)
+            state.examInfo = data
+        },
         SetTrytestCount(state, nowCountArray) {
             state.trytestCount = nowCountArray;
             //console.log("目前單元嘗試次數" + state.trytestCount);
@@ -307,6 +315,9 @@ export default {
         getPaperInfo: (state) => {
             return state.paperInfo;
         },
+        getExamInfo: (state) => {
+            return state.examInfo;
+        },
         getSidebarisOpen: (state) => {
             return state.sideBarIsOpen;
         },

+ 14 - 7
TEAMModelOS/ClientApp/src/utils/editorTools.js

@@ -2,6 +2,7 @@ import $api from '@/api'
 import store from '@/store'
 import $tools from './public.js'
 import E from 'wangeditor'
+import { Message } from 'view-design'
 
 
 export default {
@@ -51,14 +52,20 @@ export default {
 							selector: "#" + inputIFrameId,
 							type: "click",
 							fn: () => {
-								var $file = $('#' + upFileId);
-								var fileElem = $file.elems[0];
-								if (fileElem) {
-									fileElem.click();
-								} else {
-									// 返回 true 可关闭 panel
-									return true;
+								var hasVideo = editor.txt.html().includes('class="richText-video"')
+								if(hasVideo){
+									Message.warning('最多只能上传一个视频!')
+								}else{
+									var $file = $('#' + upFileId);
+									var fileElem = $file.elems[0];
+									if (fileElem) {
+										fileElem.click();
+									} else {
+										// 返回 true 可关闭 panel
+										return true;
+									}
 								}
+								
 							},
 						},
 						{

+ 0 - 10
TEAMModelOS/ClientApp/src/view/evaluation/bank/ExerciseList.vue

@@ -427,16 +427,6 @@
 				})
 			},
 
-			/**
-			 * 获取筛选结果数量
-			 * @param data
-			 */
-			getResultCount(data) {
-				this.$api.newEvaluation.FindCount(data).then((res) => {
-					this.totalNum = res.result.data[0];
-				});
-			},
-
 			/**
 			 * 根据知识点id集合换取知识点对象集合
 			 * @param ids

+ 0 - 10
TEAMModelOS/ClientApp/src/view/evaluation/bank/TestPaperList.vue

@@ -229,16 +229,6 @@
 
 			},
 
-			/**
-			 * 获取筛选结果数量
-			 * @param data
-			 */
-			getResultCount(data) {
-				this.$api.newEvaluation.FindCount(data).then(res => {
-					this.totalNum = res.result.data[0]
-				})
-			},
-
 			/**
 			 * 删除试卷
 			 * @param item

+ 7 - 2
TEAMModelOS/ClientApp/src/view/evaluation/bank/index.vue

@@ -10,11 +10,11 @@
 		</Tabs>
 		<div class="ev-list-operation">
 			<div class="import-exercise common-save-btn">
-				<span @click="goCreatePaper" v-show="currentTab === 'paper'" class="bank-tools-btn">
+				<span @click="goCreatePaper" v-show="currentTab === 'paper' && ($access.can('admin.*||exercise-upd') || !isSchool)" class="bank-tools-btn">
 					<Icon type="md-add" size="16"/>
 					<span>新建试卷</span>
 				</span>
-				<span @click="goCreateExercise" v-show="currentTab === 'exercise'" class="bank-tools-btn">
+				<span @click="goCreateExercise" v-show="currentTab === 'exercise' && ($access.can('admin.*||exercise-upd') || !isSchool)" class="bank-tools-btn">
 					<Icon type="md-add" size="16"/>
 					<span>新建习题</span>
 				</span>
@@ -108,6 +108,11 @@
 			}else{
 				this.$EventBus.$emit('showSchoolBank',false)
 			}
+		},
+		computed:{
+			isSchool(){
+				return this.$route.name === "schoolBank";
+			}
 		}
 	}
 </script>

+ 1 - 1
TEAMModelOS/ClientApp/src/view/evaluation/components/BaseImport.vue

@@ -43,7 +43,6 @@
     </div>
 </template>
 <script>
-    import Loading from '@/common/Loading.vue'
 	import FileSaver from "file-saver";
     export default {
         props: ['period', 'subject'],
@@ -101,6 +100,7 @@
 				  downloadRes();
 			},
 			
+			/* 下载模板制作详情说明文件 */
 			onDownloadDetails(){
 				const downloadRes = async () => {
 				      let response = await fetch(this.hostName + '/download/%E6%A8%A1%E6%9D%BF%E5%88%B6%E4%BD%9C%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9.txt'); // 内容转变成blob地址

+ 2 - 2
TEAMModelOS/ClientApp/src/view/evaluation/index/CreateExercises.less

@@ -6,7 +6,7 @@
 
     .ev-container .w-e-text-container {
 		z-index:0 !important;
-        height:180px !important;
+        height:250px !important;
     }
 
     .ev-container .ev-title {
@@ -26,7 +26,6 @@
     .display-flex {
         display: flex;
         flex-direction: row;
-        align-items: center;
         justify-content:flex-start;
     }
 
@@ -87,6 +86,7 @@
 
 .my-radio-style .ivu-radio-group-button .ivu-radio-wrapper {
     margin-right: 20px;
+	margin-bottom: 10px;
     border-radius: 5px;
     background: #fff;
     border: 1px solid #dcdee2;

+ 1 - 1
TEAMModelOS/ClientApp/src/view/evaluation/types/BaseMultiple.vue

@@ -232,7 +232,7 @@
 			/* 保存试题 获取最新选项数据 */
 			doSave() {
 				// 拿到当前还剩的选项DOM
-				let wraps = Array.from(document.getElementsByClassName('option-order'))
+				let wraps = Array.from(document.getElementsByClassName('option-editor'))
 				let arr = []
 				wraps.forEach((item, index) => {
 					// 遍历选项 找到对应的 Editor 然后获取编辑器里面的内容

+ 2 - 1
TEAMModelOS/ClientApp/src/view/evaluation/types/BaseSingle.vue

@@ -201,8 +201,9 @@
 			/* 保存试题 获取最新选项数据 */
 			doSave() {
 				// 拿到当前还剩的选项DOM
-				let wraps = Array.from(document.getElementsByClassName('option-order'))
+				let wraps = Array.from(document.getElementsByClassName('option-editor'))
 				let arr = []
+				console.log(wraps)
 				wraps.forEach((item, index) => {
 					// 遍历选项 找到对应的 Editor 然后获取编辑器里面的内容
 					let id = item.dataset.editorId

+ 2 - 21
TEAMModelOS/ClientApp/src/view/knowledge-point/index/Index.vue

@@ -415,7 +415,7 @@
 				let that = this
 				let params = JSON.parse(JSON.stringify(this.currentParams))
 				params.type = 0
-				this.$api.knowledge.GetSchoolBlocks(params).then(res => {
+				this.$api.knowledge.GetSchoolPoints(params).then(res => {
 					if (!res.error && res.knowledges) {
 						let list = res.knowledges
 						this.blockList = list
@@ -599,7 +599,7 @@
 					onOk: () => {
 						let that = this
 						this.isLoading = true
-						this.$api.knowledge.DeleteSchoolBlock({
+						this.$api.knowledge.DeleteSchoolPoint({
 							id: data.id
 						}).then(res => {
 							if (res.knowledges) {
@@ -801,25 +801,6 @@
 				this.pageChange(1)
 			},
 
-			// 获取知识点完整对象数据 ID换对象
-			getPointObject(arr) {
-				return new Promise((r, j) => {
-					let params = {
-						collectionName: 'Knowledge',
-						queryDict: {
-							id: arr
-						}
-					}
-					this.$api.FindCollection(params).then(res => {
-						if (!res.error && res.result.data) {
-							r(res.result.data)
-						} else {
-							this.$Message.warning('获取数据失败')
-						}
-					})
-				})
-
-			}
 		},
 		mounted() {
 

File diff suppressed because it is too large
+ 501 - 498
TEAMModelOS/Controllers/Analysis/AchievementController.cs


File diff suppressed because it is too large
+ 506 - 506
TEAMModelOS/Controllers/Analysis/ChangeController.cs


+ 0 - 198
TEAMModelOS/Controllers/Analysis/ClassController.cs

@@ -1,198 +0,0 @@
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Mvc;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-using TEAMModelOS.Helper.Common.FileHelper;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Helper.Common.JsonHelper;
-
-namespace TEAMModelOS.Starter.CloudServer.Controllers.AnalysisControllers
-{
-    [Route("api/[controller]")]
-    [ApiController]
-    public class ClassController: Controller
-    {
-        IWebHostEnvironment _hostingEnvironment;
-
-        public ClassController(IWebHostEnvironment hostingEnvironment)
-        {
-            _hostingEnvironment = hostingEnvironment;
-        }
-        /// <summary>
-        /// 获取年级菜单
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getGrade")]
-        public BaseResponse getGrade(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            //identity = "grade";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath,identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 获取学期菜单
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getTerm")]
-        public BaseResponse getTerm(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            //identity = "term";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-        /// <summary>
-        /// 获取考试列表
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getExam")]
-        public BaseResponse getExam(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            //identity = "Exam";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 获取基础信息
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getBase")]
-        public BaseResponse getBase(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "Base";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-        /// <summary>
-        /// 点击关注年级后,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChange")]
-        public BaseResponse getChange(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "Changegrade";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 点击关注学年期后,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChangeterm")]
-        public BaseResponse getChangeterm(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "Changeterm";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 点击某次考试详情,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChangeExam")]
-        public BaseResponse getChangeExam(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "ChangeExam";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-
-
-        /// <summary>
-        /// 筛选考试类型,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChangeExamType")]
-        public BaseResponse getChangeExamType(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "ChangeExamType";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 显示文科按钮,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChangeArts")]
-        public BaseResponse getChangeArts(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "Changearts";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-        /// <summary>
-        /// 显示理科按钮,动态数据
-        /// </summary>
-        /// <param name="identity"></param>
-        /// <returns></returns>
-        [HttpGet("getChangeScience")]
-        public BaseResponse getChangeScience(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "Changescience";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(JsonConvert.DeserializeObject(data));
-            return builder.build();
-        }
-
-
-        [HttpGet("getClass")]
-        public BaseResponse getClass(string identity)
-        {
-            string contentRootPath = _hostingEnvironment.ContentRootPath;
-            identity = "json";
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string data = FileTool.getJson(contentRootPath, identity);
-            builder.Data(data);
-            return builder.build();
-        }
-    }
-}

+ 0 - 55
TEAMModelOS/Controllers/Analysis/FileTool.cs

@@ -1,55 +0,0 @@
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Hosting;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Text;
-using System.Text.RegularExpressions;
-
-namespace TEAMModelOS.Helper.Common.FileHelper
-{
-    public static class FileTool
-    {
-
-
-        public static string getJson(string contentRootPath, string name)
-        {
-            //string webRootPath = _hostingEnvironment.WebRootPath;
-
-            try
-            {
-                String path = contentRootPath + "/JsonFile/" + name + ".json";
-                //获取正在占用的文件
-                FileStream fs = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
-                StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);
-                String line;
-                StringBuilder builder = new StringBuilder();
-                while ((line = sr.ReadLine()) != null)
-                {
-                    builder.Append(line.ToString());
-                }
-
-                sr.Close();
-                string log = builder.ToString();
-                return log;
-            }
-            catch (Exception e)
-            {
-                var s = e.Message;
-                return s;
-            }
-        }
-
-        public static string UnicodeToString(string unicode)
-        {
-            string result = "";
-            //正则匹配
-            Regex reg = new Regex(@"(?i)//u([0-9a-f]{4})");
-            result = reg.Replace(unicode, delegate (Match m)
-            {
-                return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
-            });
-            return result;
-        }
-    }
-}

+ 0 - 20
TEAMModelOS/Controllers/BaseController.cs

@@ -1,20 +0,0 @@
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using System.Collections.Generic;
-using TEAMModelOS.SDK.Context.Constant.Common;
-using System.Security.Claims;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK.Helper.Security.ShaHash;
-using System.IdentityModel.Tokens.Jwt;
-using Microsoft.IdentityModel.Tokens;
-using System.Text;
-using System;
-using System.Diagnostics;
-
-namespace TEAMModelOS.Controllers
-{
-    public class BaseController : ControllerBase
-    {
-       
-    }
-}

+ 82 - 245
TEAMModelOS/Controllers/Exam/ExamController.cs

@@ -26,20 +26,18 @@ namespace TEAMModelOS.Controllers
     [ProducesResponseType(StatusCodes.Status200OK)]
     [ProducesResponseType(StatusCodes.Status400BadRequest)]
     //[Authorize(Roles = "IES5")
-    [Route("school/exam")]
+    [Route("common/exam")]
     [ApiController]
     public class ExamController : ControllerBase
     {
-        private readonly AzureCosmosFactory _azureCosmos;        
-        private readonly SnowflakeId _snowflakeId;     
+        private readonly AzureCosmosFactory _azureCosmos;
+        private readonly SnowflakeId _snowflakeId;
         private readonly AzureServiceBusFactory _serviceBus;
         private readonly DingDing _dingDing;
         private readonly Option _option;
 
-        public ExamController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId,
-                        DingDing dingDing,
-            IOptionsSnapshot<Option> option)
-        {            
+        public ExamController(AzureCosmosFactory azureCosmos, AzureServiceBusFactory serviceBus, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option)
+        {
             _azureCosmos = azureCosmos;
             _serviceBus = serviceBus;
             _snowflakeId = snowflakeId;
@@ -57,7 +55,8 @@ namespace TEAMModelOS.Controllers
         [HttpPost("save")]
         public async Task<IActionResult> Save(ExamInfo request)
         {
-            try {
+            try
+            {
                 //新增
                 //string code = request.code;
                 var client = _azureCosmos.GetCosmosClient();
@@ -121,11 +120,13 @@ namespace TEAMModelOS.Controllers
                 //string msgEndId = _snowflakeId.NextId() + "";
                 //await _serviceBus.GetServiceBusClient().SendLeamMessage<ExamInfo>(Constants.TopicName, request.id, request.code, request.endTime);
                 return Ok(new { exam });
-            } catch (Exception ex) {
+            }
+            catch (Exception ex)
+            {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},exam/save()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
             }
-            
+
         }
         /// <summary>
         /// 删除
@@ -161,7 +162,8 @@ namespace TEAMModelOS.Controllers
                         }
                     }
                 }
-                foreach (ExamClassResult classResult in examClassResults) {
+                foreach (ExamClassResult classResult in examClassResults)
+                {
                     await client.GetContainer("TEAMModelOS", "Common").DeleteItemStreamAsync(classResult.id, new PartitionKey($"ExamClassResult-{code}"));
                 }
                 //await _azureCosmos.DeleteAll(examClassResults);
@@ -186,7 +188,8 @@ namespace TEAMModelOS.Controllers
         [HttpPost("find")]
         public async Task<IActionResult> Find(JsonElement requert)
         {
-            try {
+            try
+            {
                 //ResponseBuilder builder = ResponseBuilder.custom();
                 //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
                 if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
@@ -218,18 +221,20 @@ namespace TEAMModelOS.Controllers
                     return builder.build();
                 }*/
             }
-            catch (Exception e) {
+            catch (Exception e)
+            {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},exam/find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
             }
-            
+
         }
         [ProducesDefaultResponseType]
         //[AuthToken(Roles = "Teacher")]
         [HttpPost("find-summary")]
         public async Task<IActionResult> FindSummary(JsonElement requert)
         {
-            try {
+            try
+            {
                 //ResponseBuilder builder = ResponseBuilder.custom();
                 //if (!requert.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
                 if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
@@ -254,77 +259,15 @@ namespace TEAMModelOS.Controllers
                     }
                 }
                 return Ok(new { examInfo });
-            } catch (Exception e) {
-                await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
-                return BadRequest();
             }
-            
-        }
-        /// <summary>
-        /// 教师阅卷
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("marking")]
-        public async Task<BaseResponse> Marking(ExamRecord request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            //判断是否每一个题目都有分数
-            List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request.examCode } });
-
-            if (exams.IsNotEmpty())
-            {
-                ExamInfo examInfo = exams[0];
-                //提交答案时间必须是状态已发布,且时间在起止时间内
-                if ( examInfo.status == 300 &&
-                   examInfo.endTime <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
-                {
-                    return builder.Data(await _azureCosmos.SaveOrUpdate(request)).build();
-                }
-                else
-                {
-                    return builder.Error(ResponseCode.FAILED, "请在作答时间段内提交答案!").build();
-                }
-            }
-            else
+            catch (Exception e)
             {
-                return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
+                await _dingDing.SendBotMsg($"OS,{_option.Location},exam/FindSummary()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
             }
-        }
-
 
-        /// <summary>
-        /// 学生回答问题
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("upsert-all-record")]
-        public async Task<BaseResponse> upsertRecord(List<ExamRecord> request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            if (request.IsNotEmpty())
-            {
-                //要先处理状态,判断卷子是否存在,并判断卷子归属的考试是否允许再次提交
-                List<ExamInfo> exams = await _azureCosmos.FindByDict<ExamInfo>(new Dictionary<string, object> { { "id", request[0].examCode } });
-                if (exams.IsNotEmpty())
-                {
-                    
-                    return builder.Data(await _azureCosmos.SaveOrUpdateAll(request)).build();
-                }
-                else
-                {
-                    return builder.Error(ResponseCode.DATA_EXIST, "考试不存在!").build();
-                    
-                }
-            }
-            else {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "作答数据为空!").build();
-            }
         }
+        
         /// <summary>
         /// 学生回答问题
         /// </summary>
@@ -335,7 +278,7 @@ namespace TEAMModelOS.Controllers
         [HttpPost("upsert-record")]
         public async Task<IActionResult> upsertRecord(JsonElement request)
         {
-            
+
             if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
             //if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
             if (!request.TryGetProperty("answer", out JsonElement answer)) return BadRequest();
@@ -346,7 +289,8 @@ namespace TEAMModelOS.Controllers
             //if (!request.TryGetProperty("answers ", out JsonElement tandardAnswer)) return BadRequest();
             if (!request.TryGetProperty("paperId", out JsonElement paperId)) return BadRequest();
             if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
-            try {
+            try
+            {
                 var client = _azureCosmos.GetCosmosClient();
                 List<ExamClassResult> examClassResults = new List<ExamClassResult>();
                 await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(
@@ -519,7 +463,8 @@ namespace TEAMModelOS.Controllers
                 {
                     ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school}"));
                     examClassResults[0].progress = true;
-                    exam.subjects.ForEach(s => {
+                    exam.subjects.ForEach(s =>
+                    {
                         if (s.id.Equals(subjectId.ToString()))
                         {
                             s.classCount += 1;
@@ -529,11 +474,13 @@ namespace TEAMModelOS.Controllers
                 }
                 classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClassResults[0], examClassResults[0].id, new PartitionKey($"{examClassResults[0].code}"));
                 return Ok(new { classResult });
-            } catch (Exception e) {
+            }
+            catch (Exception e)
+            {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecord()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
-            }            
-            
+            }
+
         }
 
         [ProducesDefaultResponseType]
@@ -542,7 +489,8 @@ namespace TEAMModelOS.Controllers
         public async Task<IActionResult> upsertRecordByTeacher(JsonElement request)
         {
             //ResponseBuilder builder = ResponseBuilder.custom();
-            try {
+            try
+            {
                 if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
                 if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
                 if (!request.TryGetProperty("point", out JsonElement point)) return BadRequest();
@@ -575,7 +523,8 @@ namespace TEAMModelOS.Controllers
                     classResult.studentScores.in
                 }*/
                 int index = examClassResults[0].studentIds.IndexOf(studentId.ToString());
-                for (int i = 0;i < ans.Count;i++) {
+                for (int i = 0; i < ans.Count; i++)
+                {
                     examClassResults[0].studentScores[index][i] = ans[i];
                 }
                 if (!examClassResults[0].progress)
@@ -606,14 +555,17 @@ namespace TEAMModelOS.Controllers
                         await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{school}"));
                     }
                 }
-                else {
+                else
+                {
                     ExamInfo exam = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"Exam-{school}"));
                     exam.updateTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                     await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(exam, id.ToString(), new PartitionKey($"Exam-{school}"));
-                }                
-                classResult =  await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClassResults[0], examClassResults[0].id, new PartitionKey($"{examClassResults[0].code}"));
-                return Ok( new { classResult });
-            } catch (Exception ex) {
+                }
+                classResult = await client.GetContainer("TEAMModelOS", "Common").ReplaceItemAsync(examClassResults[0], examClassResults[0].id, new PartitionKey($"{examClassResults[0].code}"));
+                return Ok(new { classResult });
+            }
+            catch (Exception ex)
+            {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},exam/upsertRecordByTeacher()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
             }
@@ -650,7 +602,8 @@ namespace TEAMModelOS.Controllers
         {
             //ResponseBuilder builder = ResponseBuilder.custom();
             //var (id, school) = HttpContext.GetAuthTokenInfo();
-            try {
+            try
+            {
                 if (!requert.TryGetProperty("id", out JsonElement id)) return BadRequest();
                 //if (!requert.TryGetProperty("code", out JsonElement school_code)) return BadRequest();
                 if (!requert.TryGetProperty("subjectId", out JsonElement subjectId)) return BadRequest();
@@ -660,19 +613,19 @@ namespace TEAMModelOS.Controllers
                 var client = _azureCosmos.GetCosmosClient();
                 //string code = school_code.ToString().Substring(5);
                 //ExamInfo info = await client.GetContainer("TEAMModelOS", "Common").ReadItemAsync<ExamInfo>(id.ToString(), new PartitionKey($"{school_code}"));
-                List<object> examClassResults = new List<object>();                   
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id, c.code,c.info,c.studentIds,c.studentAnswers,c.studentScores from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'", 
+                List<object> examClassResults = new List<object>();
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: $"select c.id, c.code,c.info,c.studentIds,c.studentAnswers,c.studentScores from c where c.examId = '{id}' and c.subjectId = '{subjectId}' and c.info.id = '{classId}'",
                     requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school_code}") }))
+                {
+                    using var json = await JsonDocument.ParseAsync(item.ContentStream);
+                    if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 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())
                         {
-                            foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
-                            {
-                                examClassResults.Add(obj.ToObject<object>());
-                            }
+                            examClassResults.Add(obj.ToObject<object>());
                         }
-                 }                
+                    }
+                }
                 /*if (StringHelper.getKeyCount(requert) == 1 && requert.TryGetProperty("code", out JsonElement code))
                 {
                     List<object> props = new List<object>();
@@ -712,11 +665,13 @@ namespace TEAMModelOS.Controllers
                     }                   
                 }*/
                 return Ok(new { examClassResults });
-            } catch (Exception ex) {
+            }
+            catch (Exception ex)
+            {
                 await _dingDing.SendBotMsg($"OS,{_option.Location},exam/findSummaryRecord()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
             }
-            
+
         }
         //学生端查询评测列表
         [ProducesDefaultResponseType]
@@ -735,7 +690,7 @@ namespace TEAMModelOS.Controllers
                 var client = _azureCosmos.GetCosmosClient();
                 var query = $"select c.id,c.code,A0.id paperId,A0.code paperCode,A0.name paperName,A0.multipleRule,A0.scope,A0.blob from c join A0 in c.papers where c.id ='{id}' and c.progress = 'going'";
                 List<object> props = new List<object>();
-                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText:query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{school}") }))
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Exam-{school}") }))
                 {
                     using var json = await JsonDocument.ParseAsync(item.ContentStream);
                     if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
@@ -758,33 +713,35 @@ namespace TEAMModelOS.Controllers
                             props.Add(obj.ToObject<object>());
                         }
                     }
-                }                
-				var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}')";
-				List<ExamClassResult> answers = new List<ExamClassResult>();
-				await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryAnswers, 
+                }
+                var queryAnswers = $"select c.id,c.code,c.studentIds,c.subjectId,c.studentAnswers from c where c.examId ='{id}' and array_contains(c.studentIds,'{studentId}')";
+                List<ExamClassResult> answers = new List<ExamClassResult>();
+                await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: queryAnswers,
                     requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ExamClassResult-{school}") }))
-				{
-					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())
-						{
-							answers.Add(obj.ToObject<ExamClassResult>());
-						}
-					}
-				}
+                {
+                    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())
+                        {
+                            answers.Add(obj.ToObject<ExamClassResult>());
+                        }
+                    }
+                }
                 List<List<List<string>>> stuAns = new List<List<List<string>>>();
-                if (answers.Count > 0) {                   
+                if (answers.Count > 0)
+                {
                     for (int i = 0; i < answers.Count; i++)
                     {
                         int index = answers[i].studentIds.IndexOf(studentId.ToString());
-                        if (index == -1) {
+                        if (index == -1)
+                        {
                             break;
                         }
                         stuAns.Add(answers[i].studentAnswers[index]);
                     }
-                }                
-				return Ok(new { props , stuAns});
+                }
+                return Ok(new { props, stuAns });
             }
             catch (Exception ex)
             {
@@ -830,125 +787,5 @@ namespace TEAMModelOS.Controllers
             }
 
         }
-        private  class StanderAnswers {
-            List<List<string>> standard { get; set; }
-            List<double> points { get; set; }
-        }
-        /// <summary>
-        /// 查询单个作答信息  试卷id ,
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        /*[ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("find-by-idPk")]
-        public async Task<BaseResponse> findByIdPk(IdPk request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            ExamRecord record = await _azureCosmos.FindByIdPk<ExamRecord>(request.id,request.pk);
-            if (record != null) {
-                //处理客观题自动阅卷
-                Paper paper = await _azureCosmos.FindByIdPk<Paper>(record.id, record.examCode);
-                //允许自动对客观题阅卷及,及阅卷状态大于2 已完成.
-                if (paper.markConfig != null && paper.markConfig.auto && record.mark<2) {
-                    // TODO 需要处理已经打分的作答,以防止手动改分后被冲掉。
-
-                    if (paper.answers.IsNotEmpty() && record.answers.IsNotEmpty()) {
-                        autoMark(paper.item, paper.answers, record.answers, paper.markConfig);
-                    }
-                }
-            }
-            return builder.Data(record).build();
-        }*/
-
-
-        #region private        
-
-        /*private List<Answer> autoMark(List<ItemInfo> items ,List<Answer> stdAnswers, List<Answer> stuAnswers ,MarkConfig markConfig) {
-            int size = stuAnswers.Count;
-            for (int i = 0; i < size; i++) {
-                //如果当前题目已经打分则直接跳过。
-                if (stuAnswers[i].score > 0) {
-                    stuAnswers[i].mark = 1;
-                    continue;
-                }
-                //客观题
-                if (stuAnswers[i].type.Equals("single") || stuAnswers[i].type.Equals("multiple") || stuAnswers[i].type.Equals("judge")) {
-                    stuAnswers[i].mark = 1;
-                    //多选题单独处理
-                    if (stuAnswers[i].type.Equals("multiple"))
-                    {
-                        List<string> stuAns = stuAnswers[i].ans;
-                        Answer stdAnswer = stdAnswers.Where(x =>x.num== stuAnswers[i].num).FirstOrDefault();
-                        if (stdAnswer != null) {
-                            //处理多选答案是否有选错的 选错的则直接0分 ,如果少选则处理部分分数
-                            bool right = true;
-                            List<string> rightStr = new List<string>();
-                            if (stuAns.IsNotEmpty())
-                            {
-                                foreach (string stuAn in stuAns)
-                                {
-                                    if (!stdAnswer.ans.Contains(stuAn))
-                                    {
-                                        right = false;
-                                        break;
-                                    }
-                                    else {
-                                        rightStr.Add(stuAn);
-                                    }
-                                }
-                            }
-                            else {
-                                right = false;
-                            }
-                            if (right && rightStr.IsNotEmpty() && rightStr.Count != stdAnswer.ans.Count)
-                            {
-
-                                if (markConfig.type == 1)
-                                {
-                                    //1多选漏选不得分
-                                    stuAnswers[i].score = 0;
-                                }
-                                else if(markConfig.type==3){
-                                    stuAnswers[i].score=Math.Floor((double)(1.0 * rightStr.Count / stdAnswer.ans.Count * stdAnswer.score));
-                                    if (stuAnswers[i].score == 0) {
-                                        stuAnswers[i].score = 1;
-                                    }
-                                }
-                                else if (markConfig.type == 4)
-                                {
-                                    stuAnswers[i].score = markConfig.score;
-                                }
-                                else
-                                {   //2多选漏选得一半的分数(默认)
-                                    stuAnswers[i].score = stdAnswer.score/2;
-
-                                }
-                            }
-                            else {
-                                //选错不得分
-                                stuAnswers[i].score = 0;
-                            }
-                        }
-                    }
-                    else {
-                        List<string> stuAns = stuAnswers[i].ans;
-                        Answer stdAnswer = stdAnswers.Where(x => x.num == stuAnswers[i].num).FirstOrDefault();
-                        if (stdAnswer != null&&stdAnswer.ans.IsNotEmpty()&& stuAns.IsNotEmpty()) {
-                            if (stuAns[0].Equals(stdAnswer.ans[0]))
-                            {
-                                stuAnswers[i].score = stdAnswer.score;
-                            }
-                            else {
-                                stuAnswers[i].score = 0;
-                            }
-                        }
-                    }
-                }
-            }
-            return stuAnswers;
-        }*/
-
-        #endregion
     }
 }

+ 1 - 14
TEAMModelOS/Controllers/Task/SurveyController.cs

@@ -486,20 +486,7 @@ namespace TEAMModelOS.Controllers
                 return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
             }
             return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
-        }
-        /// <summary>
-        /// 学生问卷作答
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-record")]
-        public async Task<IActionResult> UpsertRecord(List<SurveyRecord> request)
-        {
-            //ResponseBuilder builder = ResponseBuilder.custom();
-            await _azureCosmos.SaveOrUpdateAll<SurveyRecord>(request);
-            return Ok(request);
-        }
+        }        
          
     }
 }

TEAMModelOS/Controllers/Task/VoteController.cs → TEAMModelOS/Controllers/Common/VoteController.cs


+ 0 - 98
TEAMModelOS/Controllers/Core/CommonController.cs

@@ -1,98 +0,0 @@
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Mvc;
-using Newtonsoft.Json.Linq;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK.Context.Exception;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Helper.Common.JsonHelper;
-using TEAMModelOS.SDK.Helper.Common.JsonHelper.JsonPath;
-using TEAMModelOS.SDK.DI;
-using static System.Text.Json.JsonElement;
-using TEAMModelOS.Models.Dto;
-
-namespace TEAMModelOS.Controllers
-{
-    [Route("api/[controller]")]
-    [ApiController]
-    // [Authorize]
-    public class CommonController : BaseController
-    {
-
-        private readonly AzureCosmosFactory _azureCosmos;
-        private readonly IWebHostEnvironment webHostEnvironment;
-        public CommonController(IWebHostEnvironment _webHostEnvironment, AzureCosmosFactory azureCosmos)
-        {
-            webHostEnvironment = _webHostEnvironment;
-            _azureCosmos = azureCosmos;
-        }
-       
-
-
-        public static string getJson(string contentRootPath, string name)
-        {
-            //string webRootPath = _hostingEnvironment.WebRootPath;
-
-            try
-            {
-                String path = contentRootPath + name;
-                //获取正在占用的文件
-                FileStream fs = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
-                StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);
-                String line;
-                StringBuilder builder = new StringBuilder();
-                while ((line = sr.ReadLine()) != null)
-                {
-                    builder.Append(line.ToString());
-                }
-
-                sr.Close();
-                string log = builder.ToString();
-                return log;
-            }
-            catch (Exception e)
-            {
-                var s = e.Message;
-                return s;
-            }
-        }
-        public static async Task<JsonDocument> GetJson(string contentRootPath, string name)
-        {
-            try
-            {
-                string path = contentRootPath + name;
-                var fs = await System.IO.File.ReadAllTextAsync(path, Encoding.UTF8);
-                return JsonDocument.Parse(fs);
-            }
-            catch (Exception e)
-            {
-                new BizException(e.Message);
-            }
-            return null;
-        }
-
-        [HttpPost("FindCollection")]
-        public async  Task<BaseResponse> FindCollection(CommonQuery request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<dynamic>  data =  await _azureCosmos.FindByDict(request.collectionName,request.queryDict);
-           // JsonElement json = JsonApiHelper.FromApiJson<JsonElement>( data.ToJson());
-            return builder.Data(data).build();
-        }
-
-
-        [HttpPost("FindCount")]
-        public async Task<BaseResponse> FindCount(CommonQuery request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<dynamic> data = await _azureCosmos.FindCountByDict(request.collectionName, request.queryDict);
-            return builder.Data(data).build();
-        }
-    }
-}

+ 0 - 162
TEAMModelOS/Controllers/Core/FileController.cs

@@ -1,162 +0,0 @@
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using TEAMModelOS.Models;
-using TEAMModelOS.SDK.Context.Constant.Common;
-using TEAMModelOS.SDK.Context.Exception;
-using TEAMModelOS.SDK;
-using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
-using TEAMModelOS.SDK.Helper.Security.AESCrypt;
-using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
-using TEAMModelOS.SDK.Module.AzureBlob.Container;
-
-using TEAMModelOS.SDK.DI;
-
-namespace TEAMModelOS.Controllers
-{
-    [Route("api/[controller]")]
-    [ApiController]
-    public class FileController:BaseController
-    {
-        private readonly AzureStorageFactory _azureStorage;
-       // private readonly IAzureBlobDBRepository _azureBlobDBRepository;
-        public FileController(AzureStorageFactory azureStorage
-        )
-        {
-            _azureStorage = azureStorage;
-           // _azureBlobDBRepository = azureBlobDBRepository;
-        }
-
-
-        //[HttpPost("uploadFiles")]
-        //[RequestSizeLimit(204_800_000_00)] //最大20000m左右
-        //public async Task<BaseResponse> BlobSaveFile([FromForm] IFormFile[] files)
-        //{
-        //    ResponseBuilder responseBuilder = new ResponseBuilder();
-        //    FileTypeMap fileTypeMap = new FileTypeMap();
-        //    fileTypeMap.GetFileTypes().TryGetValue(FileType.GetExtention(files[0].FileName).ToLower(), out FileType fileTpye);
-        //    string type = "";
-        //    if (fileTpye != null)
-        //    {
-        //        type = fileTpye.Type;
-        //    }
-
-        //    List<AzureBlobModel> list = await _azureBlobDBRepository.UploadFiles(files);
-        //    await azureTableDBRepository.SaveAll<AzureBlobModel>(list);
-        //    return responseBuilder.Data(list).build();
-        //}
-        //[HttpPost("uploadFile")]
-        //[RequestSizeLimit(204_800_000_00)] //最大20000m左右
-        //public async Task<BaseResponse> BlobSaveFile([FromForm] IFormFile file)
-        //{
-        //    //IFormFileCollection s =  Request.Form.Files;
-        //    ResponseBuilder responseBuilder = new ResponseBuilder();
-        //    FileTypeMap fileTypeMap = new FileTypeMap();
-        //    fileTypeMap.GetFileTypes().TryGetValue(FileType.GetExtention(file.FileName).ToLower(), out FileType fileTpye);
-        //    string type = "";
-        //    if (fileTpye != null)
-        //    {
-        //        type = fileTpye.Type;
-        //    }
-        //    List<IFormFile> files = new List<IFormFile>();
-        //    files.Add(file);
-        //    List<AzureBlobModel> list = await _azureBlobDBRepository.UploadFiles(files.ToArray());
-        //    await azureTableDBRepository.SaveAll<AzureBlobModel>(list);
-        //    return responseBuilder.Data(list).build();
-        //}
-       
-        //[HttpPost("uploadWangEditor")]
-        //[RequestSizeLimit(102_400_000_00)] //最大10000m左右
-        //public async Task<Dictionary<string, Object>> uploadWangEditor([FromForm] IFormFile[] files)
-        //{
-        //    //IFormFileCollection s =  Request.Form.Files;
-        //    ResponseBuilder responseBuilder = new ResponseBuilder();
-        //    FileTypeMap fileTypeMap = new FileTypeMap();
-        //    fileTypeMap.GetFileTypes().TryGetValue(FileType.GetExtention(files[0].FileName).ToLower(), out FileType fileTpye);
-        //    string type = "";
-        //    if (fileTpye != null)
-        //    {
-        //        type = fileTpye.Type;
-        //    }
-        //    List<AzureBlobModel> list = await _azureBlobDBRepository.UploadFiles(files.ToArray());
-        //    await azureTableDBRepository.SaveAll<AzureBlobModel>(list);
-        //    return new Dictionary<string, object> { { "errno", 0 }, { "data", list.Select(x => x.BlobUrl) } };
-        //}
-       
-
- 
-
-
-        /// <summary>
-        /// {"Sha1Code":"1111","Length":233444}
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [HttpPost("uploaded")]
-        public async Task<BaseResponse> uploaded(JosnRequest<Dictionary<string, object>> request)
-        {
-            ResponseBuilder responseBuilder = new ResponseBuilder();
-            List<AzureBlobModel> models = await _azureStorage.FindListByDict<AzureBlobModel>(request.@params);
-            if (models.IsNotEmpty())
-            {
-                return responseBuilder.Data(models.First()).build();
-            }
-            else
-            {
-                return responseBuilder.Data(null).build();
-            }
-        }
-
-
-
-        /// <summary>
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [HttpPost("saveBlob")]
-        public async Task<BaseResponse> saveBlob(JosnRequest<AzureBlobModel> request)
-        {
-            ResponseBuilder responseBuilder = new ResponseBuilder();
-            AzureBlobModel model = await _azureStorage.SaveOrUpdate<AzureBlobModel>(request.@params);
-            if (model != null && !string.IsNullOrEmpty(model.RowKey))
-            {
-                return responseBuilder.Data(model).build();
-            }
-            else
-            {
-                return responseBuilder.Data(null).build();
-            }
-        }
-
-            
-        private static (string, string) BlobUrlString( string sasUrl) {
-            sasUrl= sasUrl.Substring(8);
-            string[] sasUrls = sasUrl.Split("/");
-            string ContainerName;
-            ContainerName= sasUrls[1].Clone().ToString();
-            string item = sasUrls[0] + "/" + sasUrls[1] + "/";
-            string blob = sasUrl.Replace(item, "");
-            return (ContainerName, blob);
-        }
-
-
-        private static string ContainerUrlString(string sasUrl)
-        {
-            sasUrl = sasUrl.Substring(8);
-            string[] sasUrls = sasUrl.Split("/");
-            string ContainerName;
-            ContainerName = sasUrls[1].Clone().ToString();
-            return ContainerName;
-        }
-
-
-        public static bool IsBlobName(string BlobName)
-        {
-            return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
-             @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
-        }
-    }
-}

+ 1 - 1
TEAMModelOS/Controllers/Exam/ImportExerciseController.cs

@@ -34,7 +34,7 @@ namespace TEAMModelOS.Controllers
 {
     [Route("common/import")]
     [ApiController]
-    public class ImportExerciseController : BaseController
+    public class ImportExerciseController : ControllerBase
     {
         public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
         public DOXC2HTMLTranslator _DOXC2HTMLTranslator { get; set; }

+ 340 - 0
TEAMModelOS/Controllers/Import/ImportExerciseController.cs

@@ -0,0 +1,340 @@
+using Azure.Storage.Blobs.Models;
+using Azure.Storage.Sas;
+using HTEXLib;
+using HTEXLib.Builders;
+using HTEXLib.Helpers.ShapeHelpers;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IdentityModel.Tokens.Jwt;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.Models;
+using TEAMModelOS.Models.Dto;
+using TEAMModelOS.Models.PowerPoint;
+using TEAMModelOS.SDK;
+using TEAMModelOS.SDK.Context.Constant;
+using TEAMModelOS.SDK.Context.Constant.Common;
+using TEAMModelOS.SDK.DI;
+using TEAMModelOS.SDK.Extension;
+using TEAMModelOS.SDK.Module.AzureBlob.Configuration;
+using TEAMModelOS.SDK.Module.AzureBlob.Container;
+using TEAMModelOS.Services;
+using HTEXLib.Translator;
+using HTEXLib.DOCX.Models;
+
+namespace TEAMModelOS.Controllers
+{
+    [Route("import")]
+    [ApiController]
+    public class ImportController : ControllerBase
+    {
+        public PPTX2HTEXTranslator _PPTX2HTEXTranslator { get; set; }
+        public DOXC2HTMLTranslator _DOXC2HTMLTranslator { get; set; }
+        public HTML2ITEMTranslator _HTML2ITEMTranslator { get; set; }
+        //  private readonly IHtexService htexService;
+        private readonly AzureStorageFactory _azureStorage;
+        private readonly IWebHostEnvironment _webHostEnvironment;
+        private  List<LangConfig> langConfigs { get; set; }
+        private readonly IHttpClientFactory _clientFactory;
+        public ImportController(   AzureStorageFactory azureStorage, IWebHostEnvironment webHostEnvironment,
+            PPTX2HTEXTranslator PPTX2HTEXTranslator, IHttpClientFactory clientFactory,
+            DOXC2HTMLTranslator DOXC2HTMLTranslator, HTML2ITEMTranslator HTML2ITEMTranslator)
+        {
+            _HTML2ITEMTranslator = HTML2ITEMTranslator;
+            _DOXC2HTMLTranslator = DOXC2HTMLTranslator;
+            _clientFactory = clientFactory;
+            this._PPTX2HTEXTranslator = PPTX2HTEXTranslator;
+            _webHostEnvironment = webHostEnvironment;
+            _azureStorage = azureStorage;
+            string path = _webHostEnvironment.ContentRootPath + "/JsonFile/Core/LangConfig.json";
+            FileStream fs = new FileStream(path, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+            StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);
+            String line;
+            StringBuilder builder = new StringBuilder();
+            while ((line = sr.ReadLine()) != null)
+            {
+                builder.Append(line.ToString());
+            }
+
+            sr.Close();
+            string text = builder.ToString();
+            langConfigs = text.ToObject<List<LangConfig>>();
+        }
+       
+
+        /// <summary>
+        /// {"url":"https://***.blob.core.cn/xxx/1.pptx"}
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("pptx")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<IActionResult> ParsePPTX(JsonElement request)
+        {
+            //string id_token = HttpContext.GetXAuth("IdToken");
+            //if (string.IsNullOrEmpty(id_token)) return BadRequest();
+            //var jwt = new JwtSecurityToken(id_token);
+            //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
+            //var id = jwt.Payload.Sub;
+
+            request.TryGetProperty("file", out JsonElement code);
+            string azureBlobSAS = System.Web.HttpUtility.UrlDecode(code.ToString(), Encoding.UTF8);
+            (string, string) a = BlobUrlString(azureBlobSAS);
+            string ContainerName = a.Item1;
+            string BlobName = a.Item2;
+            bool flg = IsBlobName(BlobName);
+            var codes = azureBlobSAS.Split("/");
+            var file = codes[codes.Length - 1].Split(".");
+            var FileName = file[0];
+            var ext = file[1];
+            if (flg)
+            {
+                BlobAuth blobAuth = _azureStorage.GetBlobSasUriRead(ContainerName, BlobName);
+                var response = await _clientFactory.CreateClient().GetAsync(new Uri(blobAuth.url));
+                response.EnsureSuccessStatusCode();
+                Stream stream=  await response.Content.ReadAsStreamAsync();
+
+                if (ext.ToLower() == "pptx" || ext.ToLower() == "xml")
+                {
+                    string index = await PPTXTranslator(ContainerName, FileName, stream);
+                    return Ok(new { index = index });
+                }
+                else if (ext.ToLower() == "docx" || ext.ToLower() == "doc")
+                {
+                    return Ok(new { index = "" });
+                }
+                else {
+                    return BadRequest("不支持该文件类型的解析!");
+                }
+            }
+            else { return BadRequest("不是正确的Blob链接!"); }
+        }
+
+        [HttpPost("docx")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<IActionResult> ParseDocx(JsonElement request)
+        {
+            return Ok();
+        }
+        private static (string, string) BlobUrlString(string sasUrl)
+        {
+            sasUrl = sasUrl.Substring(8);
+            string[] sasUrls = sasUrl.Split("/");
+            string ContainerName;
+            ContainerName = sasUrls[1].Clone().ToString();
+            string item = sasUrls[0] + "/" + sasUrls[1] + "/";
+            string blob = sasUrl.Replace(item, "");
+            return (ContainerName, blob);
+        }
+        public static bool IsBlobName(string BlobName)
+        {
+            return System.Text.RegularExpressions.Regex.IsMatch(BlobName,
+             @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
+        }
+        /// <summary>
+        /// 
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("upload-pptx")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public async Task<IActionResult> UploadPPTX([FromForm] IFormFile file)
+        {
+
+            string id_token = HttpContext.GetXAuth("IdToken");
+            if (string.IsNullOrEmpty(id_token)) return BadRequest();
+            var jwt = new JwtSecurityToken(id_token);
+            if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
+            var id = jwt.Payload.Sub;
+            if (FileType.GetExtention(file.FileName).ToLower().Equals("pptx") || FileType.GetExtention(file.FileName).ToLower().Equals("xml"))
+            {
+                string FileName = file.FileName.Split(".")[0];
+                Stream streamFile = file.OpenReadStream();
+                string index = await PPTXTranslator(id, FileName, streamFile);
+                return Ok(new { index = index });
+            }
+            else {
+                return BadRequest("type is not pptx or xml !");
+            }
+            
+           
+        }
+
+        /// <summary>
+        /// docUrl
+        /// folder
+        /// shaCode
+        /// 
+        /// UploadWord
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("upload-word")]
+        [RequestSizeLimit(102_400_000_00)] //最大10000m左右
+        public   IActionResult UploadWord([FromForm] IFormFile file)
+        {
+          //  ResponseBuilder responseBuilder = new ResponseBuilder();
+            if (!FileType.GetExtention(file.FileName).ToLower().Equals("docx"))
+            {
+                return BadRequest(new Dictionary<string, object> { {"msg", "type is not docx!" },{ "code",ResponseCode.FAILED} });
+            }
+
+            var doc= _DOXC2HTMLTranslator.Translate(file.OpenReadStream());
+           // Dictionary<string, object> model = await ImportExerciseService.UploadWord(_azureStorage, file);
+            return Ok(doc);
+        }
+
+        /// <summary>
+        /// htmlString AnalyzeHtml
+        /// </summary>
+        /// <param name="request"></param>
+        /// <returns></returns>
+        [HttpPost("parse-html")]
+        public  IActionResult  AnalyzeHtml(JsonElement request)
+        {
+            //ResponseBuilder builder = ResponseBuilder.custom();
+            Dictionary<string, object> dict = new Dictionary<string, object>();
+            var emobj = request.EnumerateObject();
+            while (emobj.MoveNext())
+            {
+                dict[emobj.Current.Name] = emobj.Current.Value;
+            }
+            bool flag = dict.TryGetValue("htmlString", out object htmlString);
+            bool flagLang = dict.TryGetValue("lang", out object lang);
+            if (flag && htmlString != null && !string.IsNullOrEmpty(htmlString.ToString()))
+            {
+                LangConfig langConfig= langConfigs.Where(x => x.Lang == lang.ToString()).FirstOrDefault();
+                var exercises= _HTML2ITEMTranslator.Translate(htmlString.ToString(), langConfig);
+                return Ok(exercises);
+            }
+            else
+            {
+                return BadRequest();
+            }
+        }
+       
+
+        private async Task<string> PPTXTranslator(string id, string FileName, Stream streamFile)
+        {
+            var status = await _azureStorage.GetBlobServiceClient().DelectBlobs(id, $"res/{FileName}");
+            string shaCode = Guid.NewGuid().ToString("N");
+            HTEXLib.Htex htex = _PPTX2HTEXTranslator.Translate(streamFile);
+            htex.name = FileName;
+            var slides = htex.slides;
+            List<Task> tasks = new List<Task>();
+            HTEX hTEX = new HTEX() { name = FileName, size = htex.size, thumbnail = htex.thumbnail, id = shaCode };
+            Dictionary<string, string> texts = new Dictionary<string, string>();
+            List<string> shas = new List<string>();
+            foreach (var slide in slides)
+            {
+                string text = JsonHelper.ToJson(slide, ignoreNullValue: false);
+                string sha = Guid.NewGuid().ToString("N");
+                texts.Add(sha, text);
+                shas.Add(sha);
+            }
+            Dictionary<string, string> bloburls = new Dictionary<string, string>();
+            foreach (var key in texts.Keys)
+            {
+                tasks.Add(_azureStorage.UploadFileByContainer(id, texts[key], "res", FileName + "/" + key + ".json", false)
+                    .ContinueWith((Task<AzureBlobModel> blob) =>
+                    {
+                        bloburls.Add(key, blob.Result.BlobUrl);
+                    })
+                    );
+            }
+            await Task.WhenAll(tasks);
+            List<Sld> slds = new List<Sld>();
+            foreach (string sha in shas)
+            {
+                slds.Add(new Sld { type = "normal", url = System.Web.HttpUtility.UrlDecode(bloburls[sha], Encoding.UTF8), scoring = null }); ;
+            }
+            Dictionary<string, Store> dict = new Dictionary<string, Store>();
+            List<Task> tasksFiles = new List<Task>();
+            foreach (var key in htex.stores.Keys)
+            {
+                if (key.EndsWith(".wdp") || key.EndsWith(".xlsx"))
+                {
+                    htex.stores.Remove(key);
+                    continue;
+                }
+                var store = htex.stores[key];
+                Store str = new Store() { path = key, contentType = store.contentType, isLazy = store.isLazy };
+                if (!store.isLazy && store.contentType != null && ContentTypeDict.extdict.TryGetValue(store.contentType, out string ext) && store.url.Contains(";base64,"))
+                {
+                    string[] strs = store.url.Split(',');
+                    Stream stream = new MemoryStream(Convert.FromBase64String(strs[1]));
+                    var urlstrs = key.Split("/");
+                    var name = urlstrs[urlstrs.Length - 1];
+                    tasksFiles.Add(_azureStorage.UploadFileByContainer(id, stream, "res", FileName + "/" + name, false)
+                        .ContinueWith((Task<AzureBlobModel> blob) =>
+                        {
+                            str.url = System.Web.HttpUtility.UrlDecode(blob.Result.BlobUrl, Encoding.UTF8);
+                        })
+                        );
+                }
+                else
+                {
+                    str.url = System.Web.HttpUtility.UrlDecode(store.url, Encoding.UTF8);
+                }
+                dict.TryAdd(key, str);
+            }
+            await Task.WhenAll(tasksFiles);
+            hTEX.stores = dict;
+            hTEX.slides = slds;
+            var blob=  await _azureStorage.UploadFileByContainer(id, JsonHelper.ToJson(hTEX, ignoreNullValue: false), "res", FileName + "/" + "index.json", false);
+            return System.Web.HttpUtility.UrlDecode(blob.BlobUrl, Encoding.UTF8);
+        }
+    }
+
+    public class HTEX {
+        public string id { get; set; }
+        public string version { get; set; } = "1.0.20201210";
+        public string name { get; set; }
+        public HTEXLib.HtexSize size { get; set; }
+        public List<Sld> slides { get; set; }
+        //缩略图
+        public string thumbnail { get; set; }
+        //  public int page { get; set; }
+        public Dictionary<string, Store> stores { get; set; }
+        public List<string> points { get; set; }
+        public string periodId { get; set; }
+        public List<string> gradeIds { get; set; }
+        public string subjectId { get; set; }
+        public string subjectName { get; set; }
+        public string score { get; set; }
+        public string code { get; set; }
+        public string scope { get; set; }
+        public int? multipleRule { get; set; }
+    }
+    public class Sld {
+        /// <summary>
+        /// normal,普通的hte页面 single 单选题 multiple 多选题 judge 判断题 complete 填空题 subjective 问答题 compose 综合题 
+        /// </summary>
+        public string type { get; set; }
+        /// <summary>
+        /// 单页PPTx htex 的解析链接或一个题目的链接
+        /// </summary>
+        public string url { get; set; }
+        /// <summary>
+        /// 题目的配分,如果为type为normal 及compose ,则 scoring=null
+        /// </summary>
+        public Scoring scoring { get; set; }
+        /// <summary>
+        /// 单页PPTx htex 的缩略图
+        /// </summary>
+        public string thumbnail { get; set; }
+    }
+
+    public class Scoring { 
+        public double score { get; set; }
+        public List<string> ans { get; set; } = new List<string>();
+    }
+}

+ 54 - 238
TEAMModelOS/Controllers/School/CourseController.cs

@@ -300,105 +300,6 @@ namespace TEAMModelOS.Controllers
             //return Ok(new { idPk });
         }
 
-        /// <summary>
-        /// 保存更新课程安排
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("import-all-plan")]
-        public async Task<BaseResponse> ImportAllPlan(ClassPlan request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            string classroomCode=  request.classroomCode;
-            Dictionary<string, object> dictcode = new Dictionary<string, object>() { { "classes[*].classroomCode", classroomCode } };
-            List<CoursePlan> courses= await _azureCosmos.FindByDict<CoursePlan>(dictcode);
-            //按班级导入课程表 要清除之前的课程安排
-            if (courses.IsNotEmpty()) {
-                for (int i = 0; i < courses.Count; i++)
-                {
-                    for (int j = 0; j < courses[i].classes.Count; j++)
-                    {
-                        if (courses[i].classes[j].classroomCode == classroomCode)
-                        {
-                            courses[i].classes.Remove(courses[i].classes[j]);
-                        }
-                    }
-                }
-                //清除之前的
-                await _azureCosmos.SaveOrUpdateAll(courses);
-                //重新设置
-                for (int i = 0; i < courses.Count; i++) {
-                    CourseClass courseClass =   new CourseClass
-                    {
-                        classroomCode = request.classroomCode,
-                    };
-                    List <CoursePlanDto> coursePlans= request.coursePlans.Where(x => x.code == courses[i].code && x.courseId == courses[i].id).ToList();
-                    coursePlans.ForEach(x=> { courseClass.courseTimes.Add(x.courseTime); });
-                    courses[i].classes.Add(courseClass);
-                }
-                await _azureCosmos.SaveOrUpdateAll(courses);
-            }
-            return builder.Data(courses).build();
-        }
-
-        /// <summary>
-        /// 保存更新课程安排
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("upsert-plan-dto")]
-        public async Task<BaseResponse> UpsertPlan(CoursePlanDto request)
-        {
-            List<CoursePlan> plans = new List<CoursePlan>();
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<CoursePlan> coursePlans = new List<CoursePlan>();
-            CoursePlan data = await _azureCosmos.FindByIdPk<CoursePlan>(request.courseId, request.code );
-            if (data != null)
-            {
-                bool flag = true;
-                data.classes.ForEach(x => {
-                    if (x.classroomCode == request.classroomCode) {
-                        bool dt = true;
-                        x.courseTimes.ForEach(y => {
-                            if (y.time == request.courseTime.time && y.day == request.courseTime.day)
-                            {
-                                //找到相同时间段则替换
-                                y = request.courseTime;
-                                dt = false;
-                            }
-                            
-                        });
-                        //如果都没找到匹配的时间段则新增
-                        if (dt) {
-                            x.courseTimes.Add(request.courseTime);
-                        }
-                       
-                        flag = false;
-                    }
-                });
-                //如果没有找到匹配的班级则新增一个班级的时间安排
-                if (flag) {
-                    data.classes.Add(new CourseClass { classroomCode = request.classroomCode, courseTimes = new List<CourseTime> { request.courseTime } });
-                }
-            }
-            else
-            {
-                data = new CoursePlan
-                {
-                    id = request.courseId,
-                    code = request.code,
-                };
-                data.classes.Add(new CourseClass { classroomCode = request.classroomCode, courseTimes = new List<CourseTime> { request.courseTime } });
-            }
-            await _azureCosmos.SaveOrUpdate(data);
-            return builder.Data(data).build();
-        }
-
-
         /// <summary>
         /// 更新保存排课管理
         /// </summary>
@@ -628,29 +529,31 @@ namespace TEAMModelOS.Controllers
             public string semesterCode { get; set; }
         }
 
+        // TODO 前端没在用
+
         /// <summary>
         /// 教师更新副属信息,助教,分组等。
         /// </summary>
         /// <param name="request"></param>
         /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("upsert-plan")]
-        public async Task<BaseResponse> UpsertPlan(CoursePlan request) {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            CoursePlan datas = await _azureCosmos.FindByIdPk<CoursePlan>(request.id,request.code);
-            if (datas!=null) {
-                request.semesterCode = datas.semesterCode;
-                request.classes.ForEach(x => {
-                    datas.classes.ForEach(m => { 
-                    if (m.classroomCode == x.classroomCode) {
-                        x.courseTimes = m.courseTimes;
-                    } }); 
-                });
-                await _azureCosmos.Update(request);
-            }
-            return builder.Data(request).build();
-        }
+        //[ProducesDefaultResponseType]
+        ////[AuthToken(Roles = "Teacher")]
+        //[HttpPost("upsert-plan")]
+        //public async Task<BaseResponse> UpsertPlan(CoursePlan request) {
+        //    ResponseBuilder builder = ResponseBuilder.custom();
+        //    CoursePlan datas = await _azureCosmos.FindByIdPk<CoursePlan>(request.id,request.code);
+        //    if (datas!=null) {
+        //        request.semesterCode = datas.semesterCode;
+        //        request.classes.ForEach(x => {
+        //            datas.classes.ForEach(m => { 
+        //            if (m.classroomCode == x.classroomCode) {
+        //                x.courseTimes = m.courseTimes;
+        //            } }); 
+        //        });
+        //        await _azureCosmos.Update(request);
+        //    }
+        //    return builder.Data(request).build();
+        //}
 
         [ProducesDefaultResponseType]
         //[AuthToken(Roles = "Teacher")]
@@ -729,85 +632,8 @@ namespace TEAMModelOS.Controllers
                 }
             }
             return Ok(new { courses });
-        }
-
-        /// <summary>
-        /// 查询课程安排
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("find-plan")]
-        public async Task<BaseResponse> FindPlan(JsonElement request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<CoursePlan> data = new List<CoursePlan>();
-            if (StringHelper.getKeyCount(request) > 0 
-                &&
-                //必须保证这几个参数之一有传递
-                (request.TryGetProperty("id",out _)|| request.TryGetProperty("code",out _) ||
-                request.TryGetProperty("classes[*].classroomCode",out _))
-                )
-            {
-                data = await _azureCosmos.FindByDict<CoursePlan>(request);
-                if (data.IsNotEmpty()) {
-                    if (request.TryGetProperty("classes[*].classroomCode",out  JsonElement classcode)) {
-                        List<CoursePlan> coursePlans = new List<CoursePlan>();
-                        data.ForEach(x => {
-                            x.classes.ForEach(y => {
-                                if (y.classroomCode == classcode.ToString()) {
-                                    CoursePlan coursePlan = x;
-                                    coursePlan.classes = new List<CourseClass> { y };
-                                    coursePlans.Add(coursePlan);
-                                }
-                            });
-                        });
-                        data = coursePlans;
-                    }
-                }
-            }
-            return builder.Data(data).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();
-        }
-
-
-        /// <summary>
-        /// 查询课程安排
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("find-teach")]
-        public async Task<BaseResponse> FindTeach(JsonElement request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            request.TryGetProperty("code" ,out JsonElement code);
-            List<CoursePlan> data= await _azureCosmos.FindByDict<CoursePlan>(new Dictionary<string, object> { { "code", code.ToString() } }, new List<string> { "id" });
-            List<Course> courses = new List<Course>();
-            if (data.IsNotEmpty()) {
-                courses= await  _azureCosmos.FindByDict<Course>(new Dictionary<string, object> { { "id", courses.Select(x => x.id).ToArray() } });
-            }
-            List<Course> coursesp = await _azureCosmos.FindByDict<Course>(new Dictionary<string, object> { { "code", code.ToString() } });
-            if (courses.IsNotEmpty())
-            {
-                //个人教室
-                if (coursesp.IsNotEmpty())
-                {
-                    coursesp.ForEach(x =>
-                    {
-                        ///处理重复
-                        if (!courses.Select(y => y.id).Contains(x.id)) {
-                            courses.Add(x);
-                        }
-                    });
-                }
-            }
-            else {
-                courses = coursesp;
-            }
-            return builder.Data(courses).build();
-        }
+        }  
+        
         /// <summary>
         /// 查询执教助教的课程班级
         /// </summary>
@@ -879,53 +705,43 @@ namespace TEAMModelOS.Controllers
             }*/
             //return builder.Data(room).Extend(new Dictionary<string, object> { { "count", room.Count } }).build();
         }
+
+        // TODO 前端没在用
+
         /// <summary>
         /// 删除课程安排
         /// </summary>
         /// <param name="request"></param>
         /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("delete-time")]
-        public async Task<BaseResponse> DeletePlan(JsonElement request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            if (request.TryGetProperty("id",out JsonElement id) && request.TryGetProperty("code",out JsonElement code) && request.TryGetProperty("classroomCode",out JsonElement classroomCode) 
-                && request.TryGetProperty("time",out JsonElement time) && request.TryGetProperty("day",out JsonElement day)) {
-                CoursePlan coursePlan = await _azureCosmos.FindByIdPk<CoursePlan>(id.ToString(), code.ToString());
-                List<CourseTime> courseTimes = new List<CourseTime>();
-                coursePlan.classes.ForEach(x=> {
-                    if (x.classroomCode == classroomCode.ToString()) {
-                        x.courseTimes.ForEach(y => {
-                            if (y.time == time.ToString() && y.day == day.ToString())
-                            {
-                                courseTimes.Add(y);
-                            }
-                        });
-                    }
-                });
-               coursePlan.classes.ForEach(x => { if (x.classroomCode == classroomCode.ToString()) {
-                       courseTimes.ForEach(y => { x.courseTimes.Remove(y); });
-                   } });
-               await _azureCosmos.Update(coursePlan);
-                return builder.Data(coursePlan).build();
-            }
-            return builder.Data(null).build();
-        }
-        /// <summary>
-        /// 删除课程安排
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "Teacher")]
-        [HttpPost("delete-plan")]
-        public async Task<BaseResponse> DeletePlan(IdPk request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            IdPk idPk = await _azureCosmos.DeleteAsync<CoursePlan>(request);
-            return builder.Data(idPk).build();
-        }
+        //[ProducesDefaultResponseType]
+        ////[AuthToken(Roles = "Teacher")]
+        //[HttpPost("delete-time")]
+        //public async Task<BaseResponse> DeletePlan(JsonElement request)
+        //{
+        //    ResponseBuilder builder = ResponseBuilder.custom();
+        //    if (request.TryGetProperty("id",out JsonElement id) && request.TryGetProperty("code",out JsonElement code) && request.TryGetProperty("classroomCode",out JsonElement classroomCode) 
+        //        && request.TryGetProperty("time",out JsonElement time) && request.TryGetProperty("day",out JsonElement day)) {
+        //        CoursePlan coursePlan = await _azureCosmos.FindByIdPk<CoursePlan>(id.ToString(), code.ToString());
+        //        List<CourseTime> courseTimes = new List<CourseTime>();
+        //        coursePlan.classes.ForEach(x=> {
+        //            if (x.classroomCode == classroomCode.ToString()) {
+        //                x.courseTimes.ForEach(y => {
+        //                    if (y.time == time.ToString() && y.day == day.ToString())
+        //                    {
+        //                        courseTimes.Add(y);
+        //                    }
+        //                });
+        //            }
+        //        });
+        //       coursePlan.classes.ForEach(x => { if (x.classroomCode == classroomCode.ToString()) {
+        //               courseTimes.ForEach(y => { x.courseTimes.Remove(y); });
+        //           } });
+        //       await _azureCosmos.Update(coursePlan);
+        //        return builder.Data(coursePlan).build();
+        //    }
+        //    return builder.Data(null).build();
+        //}
+        
     public class Student
         {
          public string id { get; set; }

+ 4 - 61
TEAMModelOS/Controllers/Syllabus/ItemInfoController.cs

@@ -39,28 +39,7 @@ namespace TEAMModelOS.Controllers
             _dingDing = dingDing;
             _option = option?.Value;
         }
-
-        /// <summary>
-        /// 批量保存题目
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("upsert-all")]
-        public async Task<IActionResult> UpsertAll(List<ItemInfo> request)
-        {
-           // ResponseBuilder builder = ResponseBuilder.custom();
-            
-            request.ForEach(x => {
-              
-                if (string.IsNullOrEmpty(x.id)) {
-                    x.id = _snowflakeId.NextId()+"";
-                    x.code = typeof(ItemInfo).Name + "-" + x.code;
-                };
-                x.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
-            });
-            return Ok(await _azureCosmos.SaveOrUpdateAll(request));
-        }
+        
         [ProducesDefaultResponseType]
         [HttpPost("upsert")]
         public async Task<IActionResult> Upsert(JsonElement request)
@@ -215,21 +194,7 @@ namespace TEAMModelOS.Controllers
                 return BadRequest();
             }
             
-        }
-        /// <summary>
-        /// 手动挑题
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "teacher")]
-        [HttpPost("find-by-ids")]
-        public async Task<IActionResult> FindByIds(List<string> request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
-            return Ok(items);
-        }
+        }       
 
         /// <summary>
         /// 删除
@@ -265,21 +230,7 @@ namespace TEAMModelOS.Controllers
             IdPk idPk = await _azureCosmos.DeleteAsync<ItemInfo>( request );
             return Ok(idPk);*/
         }
-
-        /// <summary>
-        /// 删除
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        //[AuthToken(Roles = "teacher")]
-        [HttpPost("delete-all")]
-        public async Task<IActionResult> DeleteAll(JsonElement request)
-        {
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<IdPk> idPk = await _azureCosmos.DeleteAll<ItemInfo>(request);
-            return Ok(idPk);
-        }
+        
         /// <summary>
         /// 手动挑题
         /// </summary>
@@ -424,15 +375,7 @@ namespace TEAMModelOS.Controllers
             }
 
             return Ok(new { items });
-           /* ResponseBuilder builder = ResponseBuilder.custom();
-            List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
-            //List<string> ps = new List<string>() { "6f705b1b-8221-5307-18da-13da05adf91e", "c3e1e95a-561e-fabf-cce3-3a564782e443" };
-            //
-            //
-            //Random random = new Random();
-            //items.ForEach(x => { x.usageCount = random.Next(0, 300);x.createTime = random.Next(1426668584, 1584521384);x.order = random.Next(1, items.Count); });
-            //await cosmosDBV3Repository.SaveOrUpdateAll(items);
-            return builder.Data(items).build();*/
+           
         }
 
         /// <summary>

+ 0 - 53
TEAMModelOS/Controllers/Syllabus/KnowledgeController.cs

@@ -226,59 +226,6 @@ namespace TEAMModelOS.Controllers
              return builder.Data(data.OrderBy(m => m.order)).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
         }
 
-
-        /// <summary>
-        /// 获取知识根据id 
-        /// </summary>
-        /// <param name="request"></param>
-        /// <returns></returns>
-        [ProducesDefaultResponseType]
-        [HttpPost("find-by-ids")]
-        public async Task<IActionResult> FindByIds(JsonElement requert)
-        {
-
-            var client = _azureCosmos.GetCosmosClient();
-            if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
-            if (!requert.TryGetProperty("ids", out JsonElement id)) return BadRequest();
-            string info = "";
-            for (int i = 0; i < id.GetArrayLength(); i++)
-            {
-                info += id[i].ToJsonString() + ",";
-            }
-            List<object> Knowledges = new List<object>();
-            var query = $"select c.id,c.type,c.code, c.name,c.alias,c.subjectId,c.points,c.knowledgeId from c  where c.id in ({info[0..^1]})";
-            await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Knowledge-{school_code}") }))
-            {
-                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())
-                    {
-                        Knowledges.Add(obj.ToObject<object>());
-                    }
-                }
-            }
-
-            return Ok(new { Knowledges });
-            /*// request.@params.TryAdd("PartitionKey", request.lang);
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<Knowledge> data = new List<Knowledge>();
-            if (request.IsNotEmpty())
-            {
-                data = await _azureCosmos.FindByIds<Knowledge>(request);
-            }
-            else
-            {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
-                
-               
-            }
-            return builder.Data(data.OrderBy(m => m.order)).Extend(new Dictionary<string, object> { { "count", data.Count } }).build();*/
-        }
-
-
-
         /// <summary>
         /// 保存或更新知识
         /// </summary>

+ 0 - 15
TEAMModelOS/Controllers/Syllabus/ResourceController.cs

@@ -148,21 +148,6 @@ namespace TEAMModelOS.Controllers
             }
 
             return Ok(new { Resources });
-
-            // request.@params.TryAdd("PartitionKey", request.lang);
-            /* ResponseBuilder builder = ResponseBuilder.custom();
-             if (request != null)
-             {
-                 List<Resource> data = new List<Resource>();
-                 data = await _azureCosmos.FindByIds<Resource>(request);
-
-                 return builder.Data(data.OrderBy(m => m.createTime)).Extend(new Dictionary<string, object> { { "count", data.IsNotEmpty() ? data.Count : 0 } }).build();
-
-
-
-             }
-             else
-             { return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build(); }*/
         }
 
 

+ 19 - 31
TEAMModelOS/Controllers/Teacher/CommentController.cs

@@ -36,26 +36,27 @@ namespace TEAMModelOS.Controllers
         /// <returns></returns>
         [ProducesDefaultResponseType]
         [HttpPost("add-comment")]
-        public async Task<IActionResult> AddComment(CommentsDto request)
+        public async Task<IActionResult> AddComment(JsonElement request)
         {
-            var id = "Comment-" + request.TEAMModelId.Replace("#", "");
-            ResponseBuilder builder = ResponseBuilder.custom();
-            List<Comment> comments = await _azureCosmos.FindByDict<Comment>(new Dictionary<string, object> { { "code", request.TEAMModelId }, { "id", id } });
-            Comment comment = new Comment();
-            if (comments.IsEmpty())
-            {
-                comment.id = id;
-                comment.code = request.TEAMModelId;
-                comment.comment.Add(request.comment);
-                comments.Add(comment);
-            }
-            else {
-                comment = comments[0];
-                comment.comment.Add(request.comment);
-            }
+            //var id = "Comment-" + request.TEAMModelId.Replace("#", "");
+            //ResponseBuilder builder = ResponseBuilder.custom();
+            //List<Comment> comments = await _azureCosmos.FindByDict<Comment>(new Dictionary<string, object> { { "code", request.TEAMModelId }, { "id", id } });
+            //Comment comment = new Comment();
+            //if (comments.IsEmpty())
+            //{
+            //    comment.id = id;
+            //    comment.code = request.TEAMModelId;
+            //    comment.comment.Add(request.comment);
+            //    comments.Add(comment);
+            //}
+            //else {
+            //    comment = comments[0];
+            //    comment.comment.Add(request.comment);
+            //}
             //builder.Data(await _azureCosmos.SaveOrUpdate(comment));
             //return builder.build();
-            return Ok(await _azureCosmos.SaveOrUpdate(comment));
+            //return Ok(await _azureCosmos.SaveOrUpdate(comment));
+            return Ok();
         }
 
         /// <summary>
@@ -90,20 +91,7 @@ namespace TEAMModelOS.Controllers
                 }
             }
 
-            return Ok(new { comments});
-            // request.TryAdd("PartitionKey", request.lang);
-            /*ResponseBuilder builder = ResponseBuilder.custom();
-
-            List<Comment> data = new List<Comment>();
-            if (StringHelper.getKeyCount(request) > 0)
-            {
-                data = await _azureCosmos.FindByDict<Comment>(request);
-            }
-            else
-            {
-                return builder.Error(ResponseCode.PARAMS_ERROR, "参数异常!").build();
-            }
-            return builder.Data(data).build();*/
+            return Ok(new { comments});           
         }
         /// <summary>
         /// 更新保存教师评语罐头,如果评语列表为空则删除

+ 1 - 1
TEAMModelOS/Controllers/xTest/BlobController.cs

@@ -19,7 +19,7 @@ namespace TEAMModelOS.Controllers.Core
 {
     [Route("api/[controller]")]
     [ApiController]
-    public class BlobController : BaseController
+    public class BlobController : ControllerBase
     {
 
         private readonly AzureStorageFactory _azureStorage;

+ 0 - 1
TEAMModelOS/TEAMModelOS.csproj

@@ -43,7 +43,6 @@
   </ItemGroup>
 
   <ItemGroup>
-    <Folder Include="Controllers\Common\" />
     <Folder Include="JwtRsaFile\" />
     <Folder Include="Services\Evaluation\" />
     <Folder Include="wwwroot\" />