ItemController.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. using Microsoft.AspNetCore.Mvc;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using TEAMModelOS.Models;
  7. using TEAMModelOS.SDK;
  8. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  9. using TEAMModelOS.SDK.DI;
  10. using System.Text.Json;
  11. using TEAMModelOS.SDK.Helper.Common.StringHelper;
  12. using TEAMModelOS.SDK.Models;
  13. using Microsoft.AspNetCore.Http;
  14. using TEAMModelOS.SDK.Extension;
  15. using Azure.Cosmos;
  16. using Microsoft.AspNetCore.Authentication;
  17. using System.Text;
  18. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  19. using Microsoft.Extensions.Options;
  20. using Azure.Messaging.ServiceBus;
  21. using Microsoft.Extensions.Configuration;
  22. using TEAMModelOS.Services.Common;
  23. namespace TEAMModelOS.Controllers
  24. {
  25. [ProducesResponseType(StatusCodes.Status200OK)]
  26. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  27. //[Authorize(Roles = "IES5")]
  28. [Route("item")]
  29. //[Route("api/[controller]")]
  30. [ApiController]
  31. public class ItemController : ControllerBase
  32. {
  33. private readonly SnowflakeId _snowflakeId;
  34. private readonly AzureCosmosFactory _azureCosmos;
  35. private readonly DingDing _dingDing;
  36. private readonly Option _option;
  37. private readonly AzureStorageFactory _azureStorage;
  38. private readonly AzureServiceBusFactory _serviceBus;
  39. public IConfiguration _configuration { get; set; }
  40. public ItemController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId, DingDing dingDing, IOptionsSnapshot<Option> option, AzureStorageFactory azureStorage, AzureServiceBusFactory serviceBus, IConfiguration configuration)
  41. {
  42. _azureCosmos = azureCosmos;
  43. _snowflakeId = snowflakeId;
  44. _dingDing = dingDing;
  45. _option = option?.Value;
  46. _azureStorage = azureStorage;
  47. _serviceBus = serviceBus;
  48. _configuration = configuration;
  49. }
  50. /// <summary>
  51. /// 参数{"periodId":"学段id","schoolCode":"学校编码"} 其中periodId 不填则是全部学段的。
  52. /// </summary>
  53. /// <param name="request"></param>
  54. /// <returns></returns>
  55. [ProducesDefaultResponseType]
  56. [HttpPost("cond-count")]
  57. public async Task<IActionResult> CondCount(JsonElement request) {
  58. try
  59. {
  60. var client = _azureCosmos.GetCosmosClient();
  61. request.TryGetProperty("periodId", out JsonElement periodId);
  62. if (!request.TryGetProperty("schoolCode", out JsonElement schoolCode)) return BadRequest();
  63. if (periodId.ValueKind.Equals(JsonValueKind.String) && !string.IsNullOrEmpty(periodId.GetString()))
  64. {
  65. ItemCond itemCond = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemCond>($"{periodId}", new PartitionKey($"ItemCond-{schoolCode}"));
  66. return Ok(new { itemConds = new List<ItemCond>() { itemCond } });
  67. }
  68. else {
  69. List<ItemCond> items = new List<ItemCond>();
  70. var queryslt = $"SELECT value(c) FROM c ";
  71. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<ItemCond>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ItemCond-{schoolCode}") }))
  72. {
  73. items.Add(item);
  74. }
  75. return Ok(new { itemConds = items });
  76. }
  77. } catch (Exception ex) {
  78. await _dingDing.SendBotMsg($"OS,{_option.Location},item/cond-count()\n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  79. return BadRequest();
  80. }
  81. }
  82. [ProducesDefaultResponseType]
  83. [HttpPost("upsert")]
  84. public async Task<IActionResult> Upsert(JsonElement request)
  85. {
  86. /* if (string.IsNullOrEmpty(request.id))
  87. {
  88. request.id = _snowflakeId.NextId() + "";
  89. request.code = typeof(ItemInfo).Name + "-" + request.code;
  90. };
  91. request.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  92. return Ok(await _azureCosmos.SaveOrUpdate(request));*/
  93. var client = _azureCosmos.GetCosmosClient();
  94. if (!request.TryGetProperty("itemInfo", out JsonElement item)) return BadRequest();
  95. if (!request.TryGetProperty("option", out JsonElement option)) return BadRequest();
  96. try
  97. {
  98. ItemInfo itemInfo;
  99. itemInfo = item.ToObject<ItemInfo>();
  100. itemInfo.size = await _azureStorage.GetBlobContainerClient(itemInfo.code).GetBlobsSize($"item/{itemInfo.id}");
  101. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "update", root = $"item/{itemInfo.id}", name = $"{itemInfo.code}" }.ToJsonString());
  102. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  103. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  104. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  105. if (option.ToString().Equals("insert"))
  106. {
  107. itemInfo.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  108. //DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  109. if (!itemInfo.code.Contains("Item"))
  110. {
  111. itemInfo.code = "Item-" + itemInfo.code;
  112. // itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  113. }
  114. var response = await client.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  115. if (response.Status == 200)
  116. {
  117. return Ok();
  118. }
  119. else
  120. {
  121. if (itemInfo.scope.Equals("private"))
  122. {
  123. itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").UpsertItemAsync(itemInfo, new PartitionKey($"{itemInfo.code}"));
  124. }
  125. else
  126. {
  127. // itemInfo.periodId
  128. itemInfo = await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync(itemInfo, new PartitionKey($"{itemInfo.code}"));
  129. ItemCond itemCond = null;
  130. try {
  131. itemCond = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemCond>(itemInfo.periodId, new PartitionKey($"ItemCond-{itemInfo.code.Replace("Item-", "")}"));
  132. } catch (Exception ex) {
  133. itemCond = new ItemCond() { id = itemInfo.periodId, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, conds = new Dictionary<string, List<CondCount>>() };
  134. };
  135. ItemService.CountItemCond(itemInfo, null, itemCond);
  136. await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ItemCond>(itemCond, new PartitionKey(itemCond.code));
  137. }
  138. }
  139. }
  140. else
  141. {
  142. itemInfo.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  143. if (itemInfo.scope.Equals("private"))
  144. {
  145. if (!itemInfo.code.Contains("Item"))
  146. {
  147. itemInfo.code = "Item-" + itemInfo.code;
  148. }
  149. itemInfo = await client.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  150. }
  151. else
  152. {
  153. if (!itemInfo.code.Contains("Item"))
  154. {
  155. itemInfo.code = "Item-" + itemInfo.code;
  156. }
  157. ItemInfo olditemInfo = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemInfo>( itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  158. itemInfo = await client.GetContainer("TEAMModelOS", "School").ReplaceItemAsync(itemInfo, itemInfo.id, new PartitionKey($"{itemInfo.code}"));
  159. //更新题目数量
  160. ItemCond itemCond = null;
  161. try
  162. {
  163. itemCond = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemCond>(itemInfo.periodId, new PartitionKey($"ItemCond-{itemInfo.code.Replace("Item-", "")}"));
  164. }
  165. catch (Exception ex)
  166. {
  167. itemCond = new ItemCond() { id = itemInfo.periodId, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, conds = new Dictionary<string, List<CondCount>>() };
  168. };
  169. ItemService.CountItemCond(itemInfo, olditemInfo, itemCond);
  170. await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ItemCond>(itemCond, new PartitionKey(itemCond.code));
  171. }
  172. }
  173. return Ok(new { itemInfo });
  174. }
  175. catch (Exception ex)
  176. {
  177. await _dingDing.SendBotMsg($"OS,{_option.Location},item/upsert()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  178. return BadRequest();
  179. }
  180. }
  181. /// <summary>
  182. //获取题目摘要信息
  183. /// </summary>
  184. /// <param name="request"></param>
  185. /// <returns></returns>
  186. [ProducesDefaultResponseType]
  187. //[AuthToken(Roles = "teacher")]
  188. [HttpPost("find-summary")]
  189. public async Task<IActionResult> FindSummary(JsonElement requert)
  190. {
  191. try
  192. {
  193. var client = _azureCosmos.GetCosmosClient();
  194. StringBuilder sql = new StringBuilder();
  195. sql.Append("select c.id, c.question,c.useCount,c.level,c.field,c.knowledge,c.type,c.option,c.createTime from c ");
  196. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  197. /* if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  198. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();*/
  199. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  200. if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  201. List<object> summary = new List<object>();
  202. Dictionary<string, object> dict = new Dictionary<string, object>();
  203. /* dict.Add("@CURRPAGE", page.GetInt32());
  204. dict.Add("@PAGESIZE", size.GetInt32());*/
  205. dict.Add("@DESC", desc.ToString());
  206. if (requert.TryGetProperty("periodId", out JsonElement periodId))
  207. {
  208. dict.Add("periodId", periodId);
  209. }
  210. if (requert.TryGetProperty("subjectId", out JsonElement subjectId))
  211. {
  212. dict.Add("subjectId", subjectId);
  213. }
  214. if (requert.TryGetProperty("level", out JsonElement level))
  215. {
  216. dict.Add("level", level);
  217. }
  218. if (requert.TryGetProperty("type", out JsonElement type))
  219. {
  220. dict.Add("type", type);
  221. }
  222. if (requert.TryGetProperty("field", out JsonElement field))
  223. {
  224. dict.Add("field", field);
  225. }
  226. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  227. //List<object> items = new List<object>();
  228. if (scope.ToString().Equals("private"))
  229. {
  230. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  231. {
  232. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  233. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  234. {
  235. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  236. {
  237. summary.Add(obj.ToObject<object>());
  238. }
  239. }
  240. }
  241. }
  242. if (scope.ToString().Equals("school"))
  243. {
  244. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  245. {
  246. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  247. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  248. {
  249. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  250. {
  251. summary.Add(obj.ToObject<object>());
  252. }
  253. }
  254. }
  255. }
  256. return Ok(new { summary });
  257. }
  258. catch (Exception ex)
  259. {
  260. await _dingDing.SendBotMsg($"OS,{_option.Location},item/FindSummary()\n{ex.Message}", GroupNames.醍摩豆服務運維群組);
  261. return BadRequest();
  262. }
  263. }
  264. /// <summary>
  265. /// 删除
  266. /// </summary>
  267. /// <param name="request"></param>
  268. /// <returns></returns>
  269. [ProducesDefaultResponseType]
  270. //[AuthToken(Roles = "teacher")]
  271. [HttpPost("delete")]
  272. public async Task<IActionResult> Delete(JsonElement request)
  273. {
  274. try
  275. {
  276. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  277. if (!request.TryGetProperty("code", out JsonElement code)) return BadRequest();
  278. if (!request.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  279. var client = _azureCosmos.GetCosmosClient();
  280. //删除blob 相关资料
  281. await _azureStorage.GetBlobServiceClient().DelectBlobs(code.ToString().Replace("Item-",""), $"item/{id}");
  282. //通知删除信息
  283. var messageBlob = new ServiceBusMessage(new { id = Guid.NewGuid().ToString(), progress = "delete", root = $"item/{id}", name = code.ToString().Replace("Item-", "") }.ToJsonString());
  284. messageBlob.ApplicationProperties.Add("name", "BlobRoot");
  285. var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  286. await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageBlob);
  287. if (scope.ToString().Equals("school"))
  288. {
  289. ItemInfo itemInfo = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemInfo>(id.ToString(), new PartitionKey($"{code}"));
  290. var response = await client.GetContainer("TEAMModelOS", "School").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
  291. //更新题目数量
  292. ItemCond itemCond = null;
  293. try
  294. {
  295. itemCond = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemCond>(itemInfo.periodId, new PartitionKey($"ItemCond-{itemInfo.code.Replace("Item-", "")}"));
  296. }
  297. catch (Exception ex)
  298. {
  299. itemCond = new ItemCond() { id = itemInfo.periodId, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, conds = new Dictionary<string, List<CondCount>>() };
  300. };
  301. ItemService.CountItemCond(null, itemInfo, itemCond);
  302. await client.GetContainer("TEAMModelOS", "School").UpsertItemAsync<ItemCond>(itemCond, new PartitionKey(itemCond.code));
  303. return Ok(new { code = response.Status });
  304. }
  305. else
  306. {
  307. var response = await client.GetContainer("TEAMModelOS", "Teacher").DeleteItemStreamAsync(id.ToString(), new PartitionKey($"{code}"));
  308. return Ok(new { code = response.Status });
  309. }
  310. }
  311. catch (Exception e)
  312. {
  313. await _dingDing.SendBotMsg($"OS,{_option.Location},item/delete()\n{e.Message},{e.StackTrace}", GroupNames.醍摩豆服務運維群組);
  314. return BadRequest();
  315. }
  316. /* ResponseBuilder builder = ResponseBuilder.custom();
  317. IdPk idPk = await _azureCosmos.DeleteAsync<ItemInfo>( request );
  318. return Ok(idPk);*/
  319. }
  320. /// <summary>
  321. /// 手动挑题
  322. /// </summary>
  323. /// <param name="request"></param>
  324. /// <returns></returns>
  325. [ProducesDefaultResponseType]
  326. //[AuthToken(Roles = "teacher")]
  327. [HttpPost("find")]
  328. public async Task<IActionResult> Find(JsonElement requert)
  329. {
  330. try
  331. {
  332. var client = _azureCosmos.GetCosmosClient();
  333. StringBuilder sql = new StringBuilder();
  334. sql.Append("select c.id,c.code,c.repairResource, c.periodId,c.question,c.useCount,c.level,c.field,c.knowledge,c.type,c.option,c.createTime,c.answer,c.explain,c.children,c.score,c.gradeIds,c.subjectId,c.blob,c.scope from c ");
  335. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  336. /* if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  337. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();*/
  338. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  339. if (!requert.TryGetProperty("scope", out JsonElement scope)) return BadRequest();
  340. Dictionary<string, object> dict = new Dictionary<string, object>();
  341. /*var emobj = requert.EnumerateObject();
  342. while (emobj.MoveNext())
  343. {
  344. dict[emobj.Current.Name] = emobj.Current.Value;
  345. }
  346. //处理code
  347. if (dict.TryGetValue("code", out object _))
  348. {
  349. dict.Remove("code");
  350. }*/
  351. /* dict.Add("@CURRPAGE", page.GetInt32());
  352. dict.Add("@PAGESIZE", size.GetInt32());*/
  353. dict.Add("@DESC", desc.ToString());
  354. if (requert.TryGetProperty("periodId", out JsonElement periodId))
  355. {
  356. dict.Add("periodId", periodId);
  357. }
  358. if (requert.TryGetProperty("subjectId", out JsonElement subjectId))
  359. {
  360. dict.Add("subjectId", subjectId);
  361. }
  362. if (requert.TryGetProperty("level", out JsonElement level))
  363. {
  364. dict.Add("level", level);
  365. }
  366. if (requert.TryGetProperty("type", out JsonElement type))
  367. {
  368. dict.Add("type", type);
  369. }
  370. if (requert.TryGetProperty("field", out JsonElement field))
  371. {
  372. dict.Add("field", field);
  373. }
  374. if (requert.TryGetProperty("gradeIds[*]", out JsonElement gradeIds))
  375. {
  376. dict.Add("gradeIds[*]", gradeIds);
  377. }
  378. if (requert.TryGetProperty("pid", out JsonElement pd))
  379. {
  380. if (pd.ValueKind != JsonValueKind.Null)
  381. {
  382. dict.Add("pid", pd.ToString());
  383. }
  384. else
  385. {
  386. dict.Add("pid", null);
  387. }
  388. }
  389. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  390. List<object> items = new List<object>();
  391. if (scope.ToString().Equals("private"))
  392. {
  393. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  394. {
  395. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  396. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  397. {
  398. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  399. {
  400. items.Add(obj.ToObject<object>());
  401. }
  402. }
  403. }
  404. }
  405. if (scope.ToString().Equals("school"))
  406. {
  407. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{code}") }))
  408. {
  409. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  410. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  411. {
  412. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  413. {
  414. items.Add(obj.ToObject<object>());
  415. }
  416. }
  417. }
  418. }
  419. //ResponseBuilder builder = ResponseBuilder.custom();
  420. /* List<ItemInfo> items = new List<ItemInfo>();
  421. if (StringHelper.getKeyCount(requert) > 0)
  422. {
  423. items = await _azureCosmos.FindByDict<ItemInfo>(requert);
  424. }*/
  425. return Ok(new { items });
  426. //return builder.Data(items).build();
  427. }
  428. catch (Exception e)
  429. {
  430. await _dingDing.SendBotMsg($"OS,{_option.Location},item/Find()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  431. return BadRequest(e.StackTrace);
  432. }
  433. }
  434. /// <summary>
  435. /// 手动挑题
  436. /// </summary>
  437. /// <param name="request"></param>
  438. /// <returns></returns>
  439. [ProducesDefaultResponseType]
  440. //[AuthToken(Roles = "teacher")]
  441. [HttpPost("Find-cache-shell")]
  442. public async Task<IActionResult> FindCacheShell(JsonElement requert)
  443. {
  444. var client = _azureCosmos.GetCosmosClient();
  445. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  446. if (!requert.TryGetProperty("ids", out JsonElement id)) return BadRequest();
  447. //List<string> ids = new List<string>();
  448. string info = "";
  449. for (int i = 0; i < id.GetArrayLength(); i++)
  450. {
  451. //ids.Add(id[i].ToJsonString());
  452. info += id[i].ToJsonString() + ",";
  453. }
  454. List<object> items = new List<object>();
  455. var query = $"select c.id, c.question,c.useCount,c.level,c.field,c.knowledge,c.type,c.option,c.createTime from c where c.id in ({info[0..^1]})";
  456. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-{school_code}") }))
  457. {
  458. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  459. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  460. {
  461. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  462. {
  463. items.Add(obj.ToObject<object>());
  464. }
  465. }
  466. }
  467. return Ok(new { items });
  468. }
  469. /// <summary>
  470. /// 自动组题
  471. /// </summary>
  472. /// <param name="request"></param>
  473. /// <returns></returns>
  474. [HttpPost("Automatic")]
  475. public async Task<IActionResult> Automatic(List<Compose> request)
  476. {
  477. try
  478. {
  479. //ResponseBuilder builder = ResponseBuilder.custom();
  480. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  481. var client = _azureCosmos.GetCosmosClient();
  482. for (int i = 0; i < request.Count; i++)
  483. {
  484. ///处理知识点均分问题
  485. int avg = 0;
  486. Dictionary<string, int> point = new Dictionary<string, int>();
  487. if (request[i].points.IsNotEmpty())
  488. {
  489. avg = (int)Math.Ceiling(request[i].count * 1.0 / request[i].points.Count);
  490. foreach (string p in request[i].points)
  491. {
  492. point.TryAdd(p, avg);
  493. }
  494. }
  495. List<ItemInfo> retnInfos = new List<ItemInfo>();
  496. List<ItemInfo> itemInfos = new List<ItemInfo>();
  497. List<TempItem> tempItems = new List<TempItem>();
  498. if (request[i].quInfos.IsNotEmpty())
  499. {
  500. List<string> types = new List<string>();
  501. List<int> levels = new List<int>();
  502. foreach (QuInfo quInfo in request[i].quInfos)
  503. {
  504. StringBuilder sql = new StringBuilder();
  505. sql.Append("select c.id,c.code,c.repairResource, c.periodId,c.question,c.useCount,c.level,c.field,c.knowledge,c.type,c.option,c.createTime,c.answer,c.explain,c.children,c.score,c.gradeIds,c.subjectId,c.blob,c.scope from c ");
  506. // 自定义
  507. if (quInfo.custom.IsNotEmpty() && quInfo.policy.Equals("custom"))
  508. {
  509. foreach (Custom custom in quInfo.custom)
  510. {
  511. for (int j = 0; j < custom.count; j++)
  512. {
  513. tempItems.Add(new TempItem { level = custom.level, type = quInfo.type });
  514. }
  515. Dictionary<string, object> dict = new Dictionary<string, object>();
  516. if (!string.IsNullOrEmpty(request[i].code))
  517. {
  518. dict.Add("code", request[i].code);
  519. }
  520. if (!string.IsNullOrEmpty(request[i].period))
  521. {
  522. dict.Add("periodId", request[i].period);
  523. }
  524. if (request[i].points.IsNotEmpty())
  525. {
  526. dict.Add("knowledge[*]", request[i].points.ToArray());
  527. }
  528. //dict.Add("lite", false);
  529. dict.Add("pid", null);
  530. ///
  531. dict.Add("type", quInfo.type);
  532. dict.Add("level", custom.level);
  533. List<ItemInfo> items = new List<ItemInfo>();
  534. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  535. if (request[i].scope.Equals("school"))
  536. {
  537. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  538. {
  539. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  540. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  541. {
  542. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  543. {
  544. items.Add(obj.ToObject<ItemInfo>());
  545. }
  546. }
  547. }
  548. }
  549. else
  550. {
  551. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  552. {
  553. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  554. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  555. {
  556. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  557. {
  558. items.Add(obj.ToObject<ItemInfo>());
  559. }
  560. }
  561. }
  562. }
  563. //List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  564. //id去重
  565. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  566. ////均分知识点题目
  567. itemInfos.AddRange(items);
  568. }
  569. }
  570. else
  571. {
  572. Dictionary<string, object> dict = new Dictionary<string, object>();
  573. if (!string.IsNullOrEmpty(request[i].code))
  574. {
  575. dict.Add("code", request[i].code);
  576. }
  577. if (!string.IsNullOrEmpty(request[i].period))
  578. {
  579. dict.Add("periodId", request[i].period);
  580. }
  581. if (request[i].points.IsNotEmpty())
  582. {
  583. dict.Add("knowledge[*]", request[i].points.ToArray());
  584. }
  585. if (!string.IsNullOrEmpty(request[i].subject))
  586. {
  587. dict.Add("subjectId", request[i].subject);
  588. }
  589. //dict.Add("lite", false);
  590. dict.Add("pid", null);
  591. dict.Add("type", quInfo.type);
  592. List<ItemInfo> items = new List<ItemInfo>();
  593. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(dict, sql);
  594. if (request[i].scope.Equals("school"))
  595. {
  596. await foreach (var item in client.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  597. {
  598. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  599. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  600. {
  601. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  602. {
  603. items.Add(obj.ToObject<ItemInfo>());
  604. }
  605. }
  606. }
  607. }
  608. else
  609. {
  610. await foreach (var item in client.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"{request[i].code}") }))
  611. {
  612. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  613. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  614. {
  615. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  616. {
  617. items.Add(obj.ToObject<ItemInfo>());
  618. }
  619. }
  620. }
  621. }
  622. //List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  623. //id去重
  624. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  625. itemInfos.AddRange(items);
  626. //均分
  627. if (quInfo.policy.Equals("average"))
  628. {
  629. //按等级去重 获取所有等级
  630. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  631. foreach (int k in lvls)
  632. {
  633. int count = quInfo.count / lvls.Count;
  634. for (int j = 0; j < count; j++)
  635. {
  636. tempItems.Add(new TempItem { level = k, type = quInfo.type });
  637. }
  638. }
  639. // 余数 取模 随机处理
  640. if (lvls.Count != 0)
  641. {
  642. int mod = quInfo.count % lvls.Count;
  643. for (int m = 0; m < mod; m++)
  644. {
  645. int lv = lvls.OrderBy(x => Guid.NewGuid()).Take(1).FirstOrDefault();
  646. tempItems.Add(new TempItem { level = lv, type = quInfo.type });
  647. lvls.Remove(lv);
  648. }
  649. }
  650. }
  651. //随机
  652. if (quInfo.policy.Equals("random"))
  653. {
  654. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  655. for (int n = 0; n < quInfo.count; n++)
  656. {
  657. int lv = lvls.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  658. tempItems.Add(new TempItem { level = lv, type = quInfo.type, policy = "random" });
  659. }
  660. }
  661. }
  662. }
  663. }
  664. itemInfos = itemInfos.OrderBy(x => Guid.NewGuid()).ToList();
  665. tempItems = tempItems.OrderBy(x => Guid.NewGuid()).ToList();
  666. foreach (TempItem temp in tempItems)
  667. {
  668. ItemInfo itemInfo = new ItemInfo();
  669. if (temp.policy != null && temp.policy.Equals("random"))
  670. {
  671. itemInfo = itemInfos.Where(x => x.type == temp.type).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  672. }
  673. else
  674. {
  675. itemInfo = itemInfos.Where(x => x.level == temp.level && x.type == temp.type).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  676. }
  677. if (itemInfo != null)
  678. {
  679. retnInfos.Add(itemInfo);
  680. itemInfos.Remove(itemInfo);
  681. }
  682. }
  683. List<ItemInfo> restItem = new List<ItemInfo>();
  684. //处理综合题问题
  685. foreach (var item in retnInfos)
  686. {
  687. if (!string.IsNullOrWhiteSpace(item.pid))
  688. {
  689. if (item.scope == "school")
  690. {
  691. var iteme = await client.GetContainer("TEAMModelOS", "School").ReadItemAsync<ItemInfo>(item.id, new PartitionKey(item.code));
  692. if (iteme != null)
  693. {
  694. restItem.Add(iteme.Value);
  695. }
  696. }
  697. else if (item.scope == "private")
  698. {
  699. var iteme = await client.GetContainer("TEAMModelOS", "Teacher").ReadItemAsync<ItemInfo>(item.id, new PartitionKey(item.code));
  700. if (iteme != null)
  701. {
  702. restItem.Add(iteme.Value);
  703. }
  704. }
  705. }
  706. else
  707. {
  708. restItem.Add(item);
  709. }
  710. }
  711. List<List<ItemInfo>> listInfo = new List<List<ItemInfo>>();
  712. //处理综合题id重复
  713. restItem = restItem.Where((x, i) => restItem.FindIndex(z => z.id == x.id) == i).ToList();
  714. foreach (IGrouping<string, ItemInfo> group in restItem.GroupBy(c => c.type))
  715. {
  716. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  717. listInfo.Add(group.ToList());
  718. }
  719. foreach (List<ItemInfo> infos in listInfo)
  720. {
  721. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  722. foreach (IGrouping<int, ItemInfo> group in infos.GroupBy(c => c.level))
  723. {
  724. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  725. dictInfo.Add("level", group.Key);
  726. dictInfo.Add("count", group.Count());
  727. dict.Add(dictInfo);
  728. }
  729. Dictionary<string, object> typeDict = new Dictionary<string, object>();
  730. typeDict.Add("info", dict);
  731. typeDict.Add("item", infos);
  732. typeDict.Add("count", infos.Count);
  733. typeDict.Add("type", infos.FirstOrDefault().type);
  734. list.Add(typeDict);
  735. }
  736. }
  737. //return builder.Data(list).build();
  738. return Ok(list);
  739. }
  740. catch (Exception e)
  741. {
  742. await _dingDing.SendBotMsg($"OS,{_option.Location},item/Automatic()\n{e.Message}", GroupNames.醍摩豆服務運維群組);
  743. return BadRequest();
  744. }
  745. }
  746. }
  747. public class TempItem
  748. {
  749. public string type { get; set; }
  750. public int level { get; set; }
  751. public ItemInfo itemInfo { get; set; }
  752. public string policy { get; set; }
  753. }
  754. public class Compose
  755. {
  756. /// <summary>
  757. /// 科目
  758. /// </summary>
  759. public string subject { get; set; }
  760. /// <summary>
  761. /// 来源,个人题库,校本题库
  762. /// </summary>
  763. public string code { get; set; }
  764. /// <summary>
  765. /// 适用学段,小学,初中,高中
  766. /// </summary>
  767. public string period { get; set; }
  768. /// <summary>
  769. /// 关联知识点
  770. /// </summary>
  771. public List<string> points { get; set; }
  772. /// <summary>
  773. /// 题目组合
  774. /// </summary>
  775. public List<QuInfo> quInfos { get; set; }
  776. /// <summary>
  777. /// 题目总数
  778. /// </summary>
  779. public int count { get; set; }
  780. public string scope { get; set; }
  781. }
  782. public class QuInfo
  783. {
  784. /// <summary>
  785. /// 题目类型,单选,多选,判断,填空,问答,综合 Single单选,Multiple多选,Judge判断,Complete填空,Subjective问答,Compose综合
  786. /// </summary>
  787. public string type { get; set; }
  788. /// <summary>
  789. /// 随机 random 平均的 average ,自定义 custom
  790. /// </summary>
  791. public string policy { get; set; }
  792. /// <summary>
  793. /// 自定义题目类型
  794. /// </summary>
  795. public List<Custom> custom { get; set; }
  796. /// <summary>
  797. /// 总题
  798. /// </summary>
  799. public int count { get; set; }
  800. }
  801. public class Custom
  802. {
  803. /// <summary>
  804. /// 难易程度
  805. /// </summary>
  806. public int level { get; set; }
  807. /// <summary>
  808. /// 数量
  809. /// </summary>
  810. public int count { get; set; }
  811. }
  812. }