ItemInfoController.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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.Models.CommonInfo;
  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. namespace TEAMModelOS.Controllers
  20. {
  21. [ProducesResponseType(StatusCodes.Status200OK)]
  22. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  23. //[Authorize(Roles = "IES5")]
  24. [Route("common/item")]
  25. //[Route("api/[controller]")]
  26. [ApiController]
  27. public class ItemInfoController : ControllerBase
  28. {
  29. private readonly SnowflakeId _snowflakeId;
  30. private readonly AzureCosmosFactory _azureCosmos;
  31. public ItemInfoController(AzureCosmosFactory azureCosmos, SnowflakeId snowflakeId)
  32. {
  33. _azureCosmos = azureCosmos;
  34. _snowflakeId = snowflakeId;
  35. }
  36. /// <summary>
  37. /// 批量保存题目
  38. /// </summary>
  39. /// <param name="request"></param>
  40. /// <returns></returns>
  41. [ProducesDefaultResponseType]
  42. [HttpPost("upsert-all")]
  43. public async Task<IActionResult> UpsertAll(List<ItemInfo> request)
  44. {
  45. ResponseBuilder builder = ResponseBuilder.custom();
  46. request.ForEach(x => {
  47. if (string.IsNullOrEmpty(x.id)) {
  48. x.id = _snowflakeId.NextId()+"";
  49. x.code = typeof(ItemInfo).Name + "-" + x.code;
  50. };
  51. x.createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  52. });
  53. return Ok(await _azureCosmos.SaveOrUpdateAll(request));
  54. }
  55. [ProducesDefaultResponseType]
  56. [HttpPost("upsert")]
  57. public async Task<IActionResult> Upsert(ItemInfo request)
  58. {
  59. ResponseBuilder builder = ResponseBuilder.custom();
  60. if (string.IsNullOrEmpty(request.id))
  61. {
  62. request.id = _snowflakeId.NextId() + "";
  63. request.code = typeof(ItemInfo).Name + "-" + request.code;
  64. };
  65. request.createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  66. return Ok(await _azureCosmos.SaveOrUpdate(request));
  67. }
  68. /// <summary>
  69. //获取题目摘要信息
  70. /// </summary>
  71. /// <param name="request"></param>
  72. /// <returns></returns>
  73. [ProducesDefaultResponseType]
  74. //[AuthToken(Roles = "teacher")]
  75. [HttpPost("find-summary")]
  76. public async Task<IActionResult> FindSummary(JsonElement requert)
  77. {
  78. var client = _azureCosmos.GetCosmosClient();
  79. StringBuilder sql = new StringBuilder();
  80. sql.Append("select c.id, c.question,c.usageCount,c.level,c.field,c.points,c.type,c.option,c.createTime from c ");
  81. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  82. if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  83. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();
  84. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  85. List<object> summary = new List<object>();
  86. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(requert,sql);
  87. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ItemInfo-{code}") }))
  88. {
  89. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  90. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  91. {
  92. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  93. {
  94. summary.Add(obj.ToObject<object>());
  95. }
  96. }
  97. }
  98. ResponseBuilder builder = ResponseBuilder.custom();
  99. Dictionary<string, object> dict = new Dictionary<string, object>();
  100. /*var emobj = requert.EnumerateObject();
  101. while (emobj.MoveNext())
  102. {
  103. dict[emobj.Current.Name] = emobj.Current.Value;
  104. }
  105. //if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  106. List<string> props = new List<string> {
  107. "question", "id", "code", "usageCount",
  108. "level","field","points","type","option","createTime"
  109. };
  110. List<ItemInfo> items = new List<ItemInfo>();
  111. if (dict.Keys.Count > 0)
  112. {
  113. items = await _azureCosmos.FindByDict<ItemInfo>(requert, propertys: props);
  114. }*/
  115. return Ok(new { summary });
  116. //return builder.Data(items).Extend(new Dictionary<string, object> { { "props", props } }).build();
  117. }
  118. /// <summary>
  119. /// 手动挑题
  120. /// </summary>
  121. /// <param name="request"></param>
  122. /// <returns></returns>
  123. [ProducesDefaultResponseType]
  124. //[AuthToken(Roles = "teacher")]
  125. [HttpPost("find-by-ids")]
  126. public async Task<IActionResult> FindByIds(List<string> request)
  127. {
  128. ResponseBuilder builder = ResponseBuilder.custom();
  129. List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
  130. return Ok(items);
  131. }
  132. /// <summary>
  133. /// 删除
  134. /// </summary>
  135. /// <param name="request"></param>
  136. /// <returns></returns>
  137. [ProducesDefaultResponseType]
  138. //[AuthToken(Roles = "teacher")]
  139. [HttpPost("delete")]
  140. public async Task<IActionResult> Delete(IdPk request)
  141. {
  142. ResponseBuilder builder = ResponseBuilder.custom();
  143. IdPk idPk = await _azureCosmos.DeleteAsync<ItemInfo>( request );
  144. return Ok(idPk);
  145. }
  146. /// <summary>
  147. /// 删除
  148. /// </summary>
  149. /// <param name="request"></param>
  150. /// <returns></returns>
  151. [ProducesDefaultResponseType]
  152. //[AuthToken(Roles = "teacher")]
  153. [HttpPost("delete-all")]
  154. public async Task<IActionResult> DeleteAll(JsonElement request)
  155. {
  156. ResponseBuilder builder = ResponseBuilder.custom();
  157. List<IdPk> idPk = await _azureCosmos.DeleteAll<ItemInfo>(request);
  158. return Ok(idPk);
  159. }
  160. /// <summary>
  161. /// 手动挑题
  162. /// </summary>
  163. /// <param name="request"></param>
  164. /// <returns></returns>
  165. [ProducesDefaultResponseType]
  166. //[AuthToken(Roles = "teacher")]
  167. [HttpPost("find")]
  168. public async Task<IActionResult> Find(JsonElement requert)
  169. {
  170. var client = _azureCosmos.GetCosmosClient();
  171. StringBuilder sql = new StringBuilder();
  172. sql.Append("select c.id, c.question,c.usageCount,c.level,c.field,c.points,c.type,c.option,c.createTime,c.answer,c.explain,c.children,c.score,c.order,c.gradeCode from c ");
  173. if (!requert.TryGetProperty("code", out JsonElement code)) return BadRequest();
  174. if (!requert.TryGetProperty("@CURRPAGE", out JsonElement page)) return BadRequest();
  175. if (!requert.TryGetProperty("@PAGESIZE", out JsonElement size)) return BadRequest();
  176. if (!requert.TryGetProperty("@DESC", out JsonElement desc)) return BadRequest();
  177. AzureCosmosQuery cosmosDbQuery = SQLHelper.GetSQL(requert, sql);
  178. List<object> items = new List<object>();
  179. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryDefinition: cosmosDbQuery.CosmosQueryDefinition, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ItemInfo-{code}") }))
  180. {
  181. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  182. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  183. {
  184. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  185. {
  186. items.Add(obj.ToObject<object>());
  187. }
  188. }
  189. }
  190. //ResponseBuilder builder = ResponseBuilder.custom();
  191. /* List<ItemInfo> items = new List<ItemInfo>();
  192. if (StringHelper.getKeyCount(requert) > 0)
  193. {
  194. items = await _azureCosmos.FindByDict<ItemInfo>(requert);
  195. }*/
  196. return Ok(new { items });
  197. //return builder.Data(items).build();
  198. }
  199. /// <summary>
  200. /// 手动挑题
  201. /// </summary>
  202. /// <param name="request"></param>
  203. /// <returns></returns>
  204. [ProducesDefaultResponseType]
  205. //[AuthToken(Roles = "teacher")]
  206. [HttpPost("Find-cache-shell")]
  207. public async Task<IActionResult> FindCacheShell(JsonElement requert)
  208. {
  209. var client = _azureCosmos.GetCosmosClient();
  210. if (!requert.TryGetProperty("school_code", out JsonElement school_code)) return BadRequest();
  211. if (!requert.TryGetProperty("ids", out JsonElement id)) return BadRequest();
  212. //List<string> ids = new List<string>();
  213. string info = "";
  214. for (int i = 0; i < id.GetArrayLength(); i++) {
  215. //ids.Add(id[i].ToJsonString());
  216. info += id[i].ToJsonString() + ",";
  217. }
  218. List<object> items = new List<object>();
  219. var query = $"select c.id, c.question,c.usageCount,c.level,c.field,c.points,c.type,c.option,c.createTime from c where c.id in ({info[0..^1]})";
  220. await foreach (var item in client.GetContainer("TEAMModelOS", "Common").GetItemQueryStreamIterator(queryText: query, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"ItemInfo-{school_code}") }))
  221. {
  222. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  223. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  224. {
  225. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  226. {
  227. items.Add(obj.ToObject<object>());
  228. }
  229. }
  230. }
  231. return Ok(new { items });
  232. /* ResponseBuilder builder = ResponseBuilder.custom();
  233. List<ItemInfo> items = await _azureCosmos.FindByIds<ItemInfo>(request);
  234. //List<string> ps = new List<string>() { "6f705b1b-8221-5307-18da-13da05adf91e", "c3e1e95a-561e-fabf-cce3-3a564782e443" };
  235. //
  236. //
  237. //Random random = new Random();
  238. //items.ForEach(x => { x.usageCount = random.Next(0, 300);x.createTime = random.Next(1426668584, 1584521384);x.order = random.Next(1, items.Count); });
  239. //await cosmosDBV3Repository.SaveOrUpdateAll(items);
  240. return builder.Data(items).build();*/
  241. }
  242. /// <summary>
  243. /// 自动组题
  244. /// </summary>
  245. /// <param name="request"></param>
  246. /// <returns></returns>
  247. [HttpPost("Automatic")]
  248. public async Task<IActionResult> Automatic(Compose request)
  249. {
  250. ResponseBuilder builder = ResponseBuilder.custom();
  251. ///处理知识点均分问题
  252. int avg = 0;
  253. Dictionary<string, int> point = new Dictionary<string, int>();
  254. if (request.points.IsNotEmpty())
  255. {
  256. avg = (int)Math.Ceiling(request.count * 1.0 / request.points.Count);
  257. foreach (string p in request.points)
  258. {
  259. point.TryAdd(p, avg);
  260. }
  261. }
  262. List<ItemInfo> retnInfos = new List<ItemInfo>();
  263. List<ItemInfo> itemInfos = new List<ItemInfo>();
  264. List<TempItem> tempItems = new List<TempItem>();
  265. if (request.quInfos.IsNotEmpty())
  266. {
  267. List<string> types = new List<string>();
  268. List<int> levels = new List<int>();
  269. foreach (QuInfo quInfo in request.quInfos)
  270. {
  271. // 自定义
  272. if (quInfo.custom.IsNotEmpty() && quInfo.policy.Equals("custom"))
  273. {
  274. foreach (Custom custom in quInfo.custom)
  275. {
  276. for (int i = 0; i < custom.count; i++)
  277. {
  278. tempItems.Add(new TempItem { level = custom.level, type = quInfo.type });
  279. }
  280. Dictionary<string, object> dict = new Dictionary<string, object>();
  281. if (request.code.IsNotEmpty())
  282. {
  283. dict.Add("code", request.code.ToArray());
  284. }
  285. if (request.period.IsNotEmpty())
  286. {
  287. dict.Add("period", request.period.ToArray());
  288. }
  289. if (request.points.IsNotEmpty())
  290. {
  291. dict.Add("points[*]", request.points.ToArray());
  292. }
  293. dict.Add("lite", false);
  294. ///
  295. dict.Add("type", quInfo.type);
  296. dict.Add("level", custom.level);
  297. List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  298. //id去重
  299. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  300. ////均分知识点题目
  301. itemInfos.AddRange(items);
  302. }
  303. }
  304. else
  305. {
  306. Dictionary<string, object> dict = new Dictionary<string, object>();
  307. if (request.code.IsNotEmpty())
  308. {
  309. dict.Add("code", request.code.ToArray());
  310. }
  311. if (request.period.IsNotEmpty())
  312. {
  313. dict.Add("period", request.period.ToArray());
  314. }
  315. if (request.points.IsNotEmpty())
  316. {
  317. dict.Add("points[*]", request.points.ToArray());
  318. }
  319. dict.Add("lite", false);
  320. dict.Add("type", quInfo.type);
  321. List<ItemInfo> items = await _azureCosmos.FindByDict<ItemInfo>(dict);
  322. //id去重
  323. items = items.Where((x, i) => items.FindIndex(z => z.id == x.id) == i).ToList();
  324. itemInfos.AddRange(items);
  325. //均分
  326. if (quInfo.policy.Equals("average"))
  327. {
  328. //按等级去重 获取所有等级
  329. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  330. foreach (int i in lvls)
  331. {
  332. int count = quInfo.count / lvls.Count;
  333. for (int j = 0; j < count; j++)
  334. {
  335. tempItems.Add(new TempItem { level = i, type = quInfo.type });
  336. }
  337. }
  338. // 余数 取模 随机处理
  339. if (lvls.Count != 0)
  340. {
  341. int mod = quInfo.count % lvls.Count;
  342. for (int m = 0; m < mod; m++)
  343. {
  344. int lv = lvls.OrderBy(x => Guid.NewGuid()).Take(1).FirstOrDefault();
  345. tempItems.Add(new TempItem { level = lv, type = quInfo.type });
  346. lvls.Remove(lv);
  347. }
  348. }
  349. }
  350. //随机
  351. if (quInfo.policy.Equals("random"))
  352. {
  353. List<int> lvls = items.Where((x, i) => items.FindIndex(z => z.level == x.level) == i).Select(x => x.level).ToList();
  354. for (int n = 0; n < quInfo.count; n++)
  355. {
  356. int lv = lvls.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  357. tempItems.Add(new TempItem { level = lv, type = quInfo.type });
  358. }
  359. }
  360. }
  361. }
  362. }
  363. itemInfos = itemInfos.OrderBy(x => Guid.NewGuid()).ToList();
  364. tempItems = tempItems.OrderBy(x => Guid.NewGuid()).ToList();
  365. foreach (TempItem temp in tempItems)
  366. {
  367. ItemInfo itemInfo = itemInfos.Where(x => x.level == temp.level && x.type == temp.type).OrderBy(x => Guid.NewGuid()).FirstOrDefault();
  368. if (itemInfo != null)
  369. {
  370. retnInfos.Add(itemInfo);
  371. itemInfos.Remove(itemInfo);
  372. }
  373. }
  374. List<List<ItemInfo>> listInfo = new List<List<ItemInfo>>();
  375. foreach (IGrouping<string, ItemInfo> group in retnInfos.GroupBy(c => c.type))
  376. {
  377. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  378. listInfo.Add(group.ToList());
  379. }
  380. List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
  381. foreach (List<ItemInfo> infos in listInfo)
  382. {
  383. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  384. foreach (IGrouping<int, ItemInfo> group in infos.GroupBy(c => c.level))
  385. {
  386. Dictionary<string, object> dictInfo = new Dictionary<string, object>();
  387. dictInfo.Add("level", group.Key);
  388. dictInfo.Add("count", group.Count());
  389. dict.Add(dictInfo);
  390. }
  391. Dictionary<string, object> typeDict = new Dictionary<string, object>();
  392. typeDict.Add("info", dict);
  393. typeDict.Add("item", infos);
  394. typeDict.Add("count", infos.Count);
  395. typeDict.Add("type", infos.FirstOrDefault().type);
  396. list.Add(typeDict);
  397. }
  398. //return builder.Data(list).build();
  399. return Ok(list);
  400. }
  401. }
  402. public class TempItem
  403. {
  404. public string type { get; set; }
  405. public int level { get; set; }
  406. public ItemInfo itemInfo { get; set; }
  407. }
  408. public class Compose
  409. {
  410. /// <summary>
  411. /// 科目
  412. /// </summary>
  413. public string subject { get; set; }
  414. /// <summary>
  415. /// 来源,个人题库,校本题库
  416. /// </summary>
  417. public List<string> code { get; set; }
  418. /// <summary>
  419. /// 适用学段,小学,初中,高中
  420. /// </summary>
  421. public List<string> period { get; set; }
  422. /// <summary>
  423. /// 关联知识点
  424. /// </summary>
  425. public List<string> points { get; set; }
  426. /// <summary>
  427. /// 题目组合
  428. /// </summary>
  429. public List<QuInfo> quInfos { get; set; }
  430. /// <summary>
  431. /// 题目总数
  432. /// </summary>
  433. public int count { get; set; }
  434. }
  435. public class QuInfo
  436. {
  437. /// <summary>
  438. /// 题目类型,单选,多选,判断,填空,问答,综合 Single单选,Multiple多选,Judge判断,Complete填空,Subjective问答,Compose综合
  439. /// </summary>
  440. public string type { get; set; }
  441. /// <summary>
  442. /// 随机 random 平均的 average ,自定义 custom
  443. /// </summary>
  444. public string policy { get; set; }
  445. /// <summary>
  446. /// 自定义题目类型
  447. /// </summary>
  448. public List<Custom> custom { get; set; }
  449. /// <summary>
  450. /// 总题
  451. /// </summary>
  452. public int count { get; set; }
  453. }
  454. public class Custom
  455. {
  456. /// <summary>
  457. /// 难易程度
  458. /// </summary>
  459. public int level { get; set; }
  460. /// <summary>
  461. /// 数量
  462. /// </summary>
  463. public int count { get; set; }
  464. }
  465. }