DataMigrationController.cs 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. using Microsoft.Azure.Cosmos;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Newtonsoft.Json;
  5. using StackExchange.Redis;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Http;
  12. using System.Net.Http.Json;
  13. using System.Text;
  14. using System.Text.Json;
  15. using System.Threading.Tasks;
  16. using TEAMModelOS.SDK.DI;
  17. using TEAMModelOS.SDK.Extension;
  18. using TEAMModelOS.SDK;
  19. using TEAMModelOS.SDK.Models;
  20. using TEAMModelOS.SDK.Models.Cosmos;
  21. using TEAMModelOS.SDK.Models.Service;
  22. using Azure;
  23. namespace TEAMModelOS.Controllers
  24. {
  25. [Route("data-migration")]
  26. [ApiController]
  27. public class DataMigrationController : ControllerBase
  28. {
  29. ///Teacher表
  30. ///
  31. /// 复制的数据
  32. /// Base ==>>Student //IES5&教研中心
  33. /// 迁移的数据 StuCourse ==>> Student //IES5
  34. /// Activity ==>> Student //IES5
  35. ///
  36. private readonly AzureStorageFactory _azureStorage;
  37. private readonly AzureRedisFactory _azureRedis;
  38. private readonly AzureCosmosFactory _azureCosmos;
  39. private readonly DingDing _dingDing;
  40. private readonly CoreAPIHttpService _coreAPIHttpService;
  41. public DataMigrationController(CoreAPIHttpService coreAPIHttpService, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, DingDing dingDing)
  42. {
  43. _azureCosmos = azureCosmos;
  44. _azureRedis = azureRedis;
  45. _azureStorage = azureStorage;
  46. _dingDing = dingDing;
  47. _coreAPIHttpService=coreAPIHttpService;
  48. }
  49. /// <summary>
  50. ///
  51. /// </summary>
  52. /// <param name="request"></param>
  53. /// <returns></returns>
  54. [ProducesDefaultResponseType]
  55. [HttpPost("data-course-to-class-for-global")]
  56. public async Task<IActionResult> DataMigrationToClassForGlobal(JsonElement request)
  57. {
  58. //参数 schoolId periodId(可选) 是否迁移历史数据 history=0;
  59. try
  60. {
  61. //if(!request.TryGetProperty("schoolId", out JsonElement _schoolId)) return BadRequest();
  62. //string schoolId = _schoolId.GetString();
  63. List<Course> schoolCourses = new List<Course>();
  64. HashSet<string> schoolIds = new HashSet<string>();
  65. StringBuilder sql = new StringBuilder($"select value c from c where c.pk='Course' ");
  66. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  67. .GetItemQueryIteratorSql<Course>(queryText: sql.ToString()))
  68. {
  69. if (!string.IsNullOrWhiteSpace(item.school))
  70. {
  71. schoolCourses.Add(item);
  72. schoolIds.Add(item.school);
  73. }
  74. }
  75. List<School> schools = new List<School>();
  76. if (schoolIds.Count>0)
  77. {
  78. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>($"select value c from c where c.id in ({string.Join(",", schoolIds.Select(z => $"'{z}'"))})", "Base");
  79. if (result.list.IsNotEmpty())
  80. {
  81. schools.AddRange(result.list);
  82. }
  83. }
  84. List<CourseDto> schoolCourseDtos = new List<CourseDto>();
  85. foreach (var course in schoolCourses)
  86. {
  87. var school = schools.Find(z => z.id.Equals(course.school));
  88. if (school==null) { continue; }
  89. var period = school.period.Find(z => z.id.Equals(course.period?.id));
  90. if (period==null)
  91. {
  92. continue;
  93. }
  94. var subject = period.subjects.Find(z => z.id.Equals(course.subject.id) ||z.name.Equals(course.subject.name));
  95. if (subject== null)
  96. {
  97. subject=new Subject { id =course.subject.id, name=course.subject.name, type=1 };
  98. period.subjects.Add(subject);
  99. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(school, new PartitionKey(school.code));
  100. }
  101. //ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(course.id, new PartitionKey($"CourseBase-{school.id}"));
  102. //if (response.StatusCode==System.Net.HttpStatusCode.OK)
  103. //{
  104. // CourseBase courseBase = JsonDocument.Parse(response.Content).RootElement.ToObject<CourseBase>();
  105. // if (courseBase!= null)
  106. // {
  107. // for (int grade = 0; grade<period.grades.Count; grade++)
  108. // {
  109. // if (courseBase.grade==grade)
  110. // {
  111. // continue;
  112. // }
  113. // string sqlBaseData = $"select value c from c where c.name ='{course.name}' and c.grade={grade} and c.period.id='{period.id}' and c.subject.id='{subject.id}'";
  114. // var resultBaseData = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlBaseData, $"CourseBase-{school.id}");
  115. // if (!resultBaseData.list.IsNotEmpty())
  116. // {
  117. // CourseBase courseBaseNew = new CourseBase()
  118. // {
  119. // id= Guid.NewGuid().ToString(),
  120. // code=$"CourseBase-{school.id}",
  121. // pk="CourseBase",
  122. // ttl=-1,
  123. // name=course.name,
  124. // subject= new IdName { id=subject?.id, name=subject?.name },
  125. // period= new IdName { id= course.period?.id, name =course.period?.name },
  126. // school=school.id,
  127. // scope="school",
  128. // creatorId=course.creatorId,
  129. // desc=course.desc,
  130. // status=1,
  131. // grade=grade,
  132. // };
  133. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseBaseNew, new PartitionKey(courseBaseNew.code));
  134. // }
  135. // }
  136. // }
  137. //}
  138. string sqlCourseBase = $"select value c from c where c.period.id='{period.id}' and c.subject.id='{subject.id}' ";
  139. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourseBase, $"CourseBase-{school.id}");
  140. List<CourseBase> courseBases = result.list.OrderBy(z => z.grade).ToList();
  141. var subjectIndex = period.subjects.FindIndex(z => z.id.Equals(subject.id));
  142. if (subjectIndex>=0)
  143. {
  144. subjectIndex=subjectIndex+1;
  145. int index = 1;
  146. foreach (var couresBase in courseBases)
  147. {
  148. string no = $"{subjectIndex}0{index}";
  149. if (index>=10)
  150. {
  151. no = $"{subjectIndex}{index}";
  152. }
  153. index++;
  154. couresBase.no=no;
  155. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(couresBase, new PartitionKey(couresBase.code));
  156. }
  157. }
  158. //当前学年
  159. var semester = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  160. List<ScheduleTask> schedules = new List<ScheduleTask>();
  161. foreach (var schedule in course.schedule)
  162. {
  163. ScheduleTask scheduleSave = null;
  164. int grade = -1;
  165. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.classId))
  166. {
  167. scheduleSave =new ScheduleTask() { type="class", groupId=schedule.classId, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id };
  168. try
  169. {
  170. Class clazz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(schedule.classId, new PartitionKey($"Class-{school.id}"));
  171. if (semester.studyYear- clazz.year>=period.grades.Count)
  172. {
  173. grade=-1;
  174. }
  175. else
  176. {
  177. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { clazz.year }, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  178. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  179. {
  180. int.TryParse(gradeData.grades.First(), out grade);
  181. }
  182. }
  183. }
  184. catch { }
  185. }
  186. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.stulist))
  187. {
  188. scheduleSave = new ScheduleTask() { type="teach", groupId=schedule.stulist, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id };
  189. if (grade==-1)
  190. {
  191. _coreAPIHttpService.check=false;
  192. var groups = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, new List<string> { schedule.stulist }, school.id);
  193. if (groups.rmembers.IsNotEmpty())
  194. {
  195. var a = groups.rmembers.Where(z => z.type==2 && z.year>0).GroupBy(z => z.year).Select(z => new { key = z.Key, list = z.ToList() }).OrderByDescending(y => y.list.Count).FirstOrDefault();
  196. if (a!=null)
  197. {
  198. if (semester.studyYear- a.key>=period.grades.Count)
  199. {
  200. grade=-1;
  201. }
  202. else
  203. {
  204. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { a.key }, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  205. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  206. {
  207. int.TryParse(gradeData.grades.First(), out grade);
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. if (grade>-1)
  215. {
  216. List<CourseBase> courseBasesExsit = new List<CourseBase>();
  217. string sqlCourse = $"select value c from c where c.name ='{course.name}' and c.grade={grade} and c.period.id='{period.id}' and c.subject.id='{course.subject?.id}' ";
  218. var resultCourseBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourse, $"CourseBase-{school.id}");
  219. if (!resultCourseBase.list.IsNotEmpty())
  220. {
  221. CourseBase courseBaseNew = new CourseBase()
  222. {
  223. id= Guid.NewGuid().ToString(),
  224. code=$"CourseBase-{school.id}",
  225. pk="CourseBase",
  226. ttl=-1,
  227. name=course.name,
  228. subject= new IdName { id=subject?.id, name=subject?.name },
  229. period= new IdName { id= course.period?.id, name =course.period?.name },
  230. school=school.id,
  231. scope="school",
  232. creatorId=course.creatorId,
  233. desc=course.desc,
  234. status=1,
  235. grade=grade,
  236. };
  237. courseBasesExsit.Add(courseBaseNew);
  238. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseBaseNew, new PartitionKey(courseBaseNew.code));
  239. {
  240. //重新处理编号
  241. string sqlCourseBaseNo = $"select value c from c where c.period.id='{period.id}' and c.subject.id='{subject.id}' ";
  242. var resultNo = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourseBase, $"CourseBase-{school.id}");
  243. List<CourseBase> courseBasesNo = resultNo.list.OrderBy(z => z.grade).ToList();
  244. var subjectIndexNo = period.subjects.FindIndex(z => z.id.Equals(subject.id));
  245. if (subjectIndexNo>=0)
  246. {
  247. subjectIndexNo=subjectIndexNo+1;
  248. int index = 1;
  249. foreach (var couresBase in courseBasesNo)
  250. {
  251. string no = $"{subjectIndexNo}0{index}";
  252. if (index>=10)
  253. {
  254. no = $"{subjectIndexNo}{index}";
  255. }
  256. index++;
  257. couresBase.no=no;
  258. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(couresBase, new PartitionKey(couresBase.code));
  259. }
  260. }
  261. }
  262. }
  263. else {
  264. courseBasesExsit.AddRange(resultCourseBase.list);
  265. }
  266. foreach (var item in courseBasesExsit)
  267. {
  268. if (semester.currSemester!=null)
  269. {
  270. string id = $"{semester.studyYear}-{semester.currSemester.id}-{item.id}";
  271. string code = $"CourseTask-{school.id}";
  272. ResponseMessage responseTask = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(id, new PartitionKey(code));
  273. CourseTask courseTask = null;
  274. if (responseTask.StatusCode==System.Net.HttpStatusCode.OK)
  275. {
  276. courseTask = JsonDocument.Parse(responseTask.Content).RootElement.ToObject<CourseTask>();
  277. var scheduleExsit = courseTask.schedules.Find(z => z.groupId.Equals(scheduleSave.groupId));
  278. if (scheduleExsit==null)
  279. {
  280. courseTask.schedules.Add(scheduleSave);
  281. }
  282. else
  283. {
  284. scheduleExsit.teacherId=scheduleSave.teacherId;
  285. }
  286. }
  287. else
  288. {
  289. courseTask = new CourseTask
  290. {
  291. id = id,
  292. code = code,
  293. pk="CourseTask",
  294. ttl=-1,
  295. courseId=item.id,
  296. year= semester.studyYear,
  297. expire= semester.nextSemester.AddDays(-1).ToUnixTimeMilliseconds(),
  298. semesterId=semester.currSemester.id,
  299. schedules=new List<ScheduleTask>() { scheduleSave }
  300. };
  301. }
  302. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseTask, new PartitionKey(code));
  303. }
  304. }
  305. }
  306. }
  307. }
  308. return Ok(new { schoolCourseDtos });
  309. }
  310. catch (Exception ex) { return Ok($"{ex.Message},{ex.StackTrace}"); }
  311. }
  312. /// <summary>
  313. ///
  314. /// </summary>
  315. /// <param name="request"></param>
  316. /// <returns></returns>
  317. [ProducesDefaultResponseType]
  318. [HttpPost("data-course-to-class")]
  319. public async Task<IActionResult> DataMigrationToClass(JsonElement request)
  320. {
  321. //参数 schoolId periodId(可选) 是否迁移历史数据 history=0;
  322. try
  323. {
  324. List<Course> schoolCourses = new List<Course>();
  325. HashSet<string> schoolIds = new HashSet<string>();
  326. int history = 0;
  327. if (request.TryGetProperty("history", out JsonElement _history) && $"{_history}".Equals("1"))
  328. {
  329. history=1;
  330. }
  331. StringBuilder sql = new StringBuilder($"select value c from c where c.pk='Course' ");
  332. if (request.TryGetProperty("periodId", out JsonElement periodId) && !string.IsNullOrWhiteSpace($"{periodId}"))
  333. {
  334. sql.Append($" and c.period.id ='{periodId}'");
  335. }
  336. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<Course>(queryText: sql.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey= new PartitionKey($"Course-{request.GetProperty("schoolId")}") }))
  337. {
  338. schoolCourses.Add(item);
  339. if (!string.IsNullOrWhiteSpace(item.school))
  340. {
  341. if (item.school.Equals("ydzt") ||item.school.Equals("xcfx") ||item.school.Equals("hlgj") ||item.school.Equals("hbcn") ||item.school.Equals("kjyxx") ||item.school.Equals("bjgsex") || item.school.Equals("cdxxps") ||item.school.Equals("pclxxx"))
  342. {
  343. //大陆站强制不处理的学校
  344. }
  345. else
  346. {
  347. schoolCourses.Add(item);
  348. schoolIds.Add(item.school);
  349. }
  350. }
  351. }
  352. List<School> schools = new List<School>();
  353. if (schoolIds.Count>0)
  354. {
  355. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>($"select value c from c where c.id in ({string.Join(",", schoolIds.Select(z => $"'{z}'"))})", "Base");
  356. if (result.list.IsNotEmpty())
  357. {
  358. schools.AddRange(result.list);
  359. }
  360. }
  361. List<CourseDto> schoolCourseDtos = new List<CourseDto>();
  362. foreach (var course in schoolCourses)
  363. {
  364. var school = schools.Find(z => z.id.Equals(course.school));
  365. if (school==null) { continue; }
  366. var period = school.period.Find(z => z.id.Equals(course.period?.id));
  367. if (period==null)
  368. {
  369. continue;
  370. }
  371. var subject = period.subjects.Find(z => z.id.Equals(course.subject.id) ||z.name.Equals(course.subject.name));
  372. if (subject== null)
  373. {
  374. subject=new Subject { id =course.subject.id, name=course.subject.name, type=1 };
  375. period.subjects.Add(subject);
  376. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(school, new PartitionKey(school.code));
  377. }
  378. ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(course.id, new PartitionKey($"CourseBase-{school.id}"));
  379. if (response.StatusCode==System.Net.HttpStatusCode.OK)
  380. {
  381. CourseBase courseBase = JsonDocument.Parse(response.Content).RootElement.ToObject<CourseBase>();
  382. if (courseBase!= null)
  383. {
  384. for (int grade = 0; grade<period.grades.Count; grade++)
  385. {
  386. if (courseBase.grade==grade)
  387. {
  388. continue;
  389. }
  390. string sqlBaseData = $"select value c from c where c.name ='{course.name}' and c.grade={grade} and c.period.id='{period.id}' and c.subject.id='{subject.id}'";
  391. var resultBaseData = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlBaseData, $"CourseBase-{school.id}");
  392. if (!resultBaseData.list.IsNotEmpty())
  393. {
  394. CourseBase courseBaseNew = new CourseBase()
  395. {
  396. id= Guid.NewGuid().ToString(),
  397. code=$"CourseBase-{school.id}",
  398. pk="CourseBase",
  399. ttl=-1,
  400. name=course.name,
  401. subject= new IdName { id=subject?.id, name=subject?.name },
  402. period= new IdName { id= course.period?.id, name =course.period?.name },
  403. school=school.id,
  404. scope="school",
  405. creatorId=course.creatorId,
  406. desc=course.desc,
  407. status=1,
  408. grade=grade,
  409. };
  410. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseBaseNew, new PartitionKey(courseBaseNew.code));
  411. }
  412. }
  413. }
  414. }
  415. string sqlCourseBase = $"select value c from c where c.name ='{course.name}' and c.period.id='{period.id}' and c.subject.id='{subject.id}' ";
  416. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourseBase, $"CourseBase-{school.id}");
  417. List<CourseBase> courseBases = result.list.OrderBy(z => z.grade).ToList();
  418. var subjectIndex = period.subjects.FindIndex(z => z.id.Equals(subject.id));
  419. if (subjectIndex>=0)
  420. {
  421. subjectIndex=subjectIndex+1;
  422. int index = 1;
  423. foreach (var couresBase in courseBases)
  424. {
  425. string no = $"{subjectIndex}0{index}";
  426. if (index>=10)
  427. {
  428. no = $"{subjectIndex}{index}";
  429. }
  430. index++;
  431. couresBase.no=no;
  432. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(couresBase, new PartitionKey(couresBase.code));
  433. }
  434. }
  435. if (history==1)
  436. {
  437. //当前学年
  438. // var semester = SchoolService.GetSemester(period, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  439. var semester = SchoolService.GetSemester(period, 1714492800000);//2024-05-01
  440. List<ScheduleTask> schedules = new List<ScheduleTask>();
  441. foreach (var schedule in course.schedule)
  442. {
  443. ScheduleTask scheduleSave = null;
  444. int grade = -1;
  445. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.classId))
  446. {
  447. scheduleSave =new ScheduleTask() { type="class", groupId=schedule.classId, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id };
  448. try
  449. {
  450. Class clazz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(schedule.classId, new PartitionKey($"Class-{school.id}"));
  451. if (semester.studyYear- clazz.year>=period.grades.Count)
  452. {
  453. grade=-1;
  454. }
  455. else
  456. {
  457. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { clazz.year }, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  458. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  459. {
  460. int.TryParse(gradeData.grades.First(), out grade);
  461. }
  462. }
  463. }
  464. catch { }
  465. }
  466. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.stulist))
  467. {
  468. scheduleSave = new ScheduleTask() { type="teach", groupId=schedule.stulist, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id };
  469. if (grade==-1)
  470. {
  471. _coreAPIHttpService.check=false;
  472. var groups = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, new List<string> { schedule.stulist }, school.id);
  473. if (groups.rmembers.IsNotEmpty())
  474. {
  475. var a = groups.rmembers.Where(z => z.type==2 && z.year>0).GroupBy(z => z.year).Select(z => new { key = z.Key, list = z.ToList() }).OrderByDescending(y => y.list.Count).FirstOrDefault();
  476. if (a!=null)
  477. {
  478. if (semester.studyYear- a.key>=period.grades.Count)
  479. {
  480. grade=-1;
  481. }
  482. else
  483. {
  484. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { a.key }, DateTimeOffset.Now.ToUnixTimeMilliseconds());
  485. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  486. {
  487. int.TryParse(gradeData.grades.First(), out grade);
  488. }
  489. }
  490. }
  491. }
  492. }
  493. }
  494. if (grade>-1)
  495. {
  496. string sqlCourse = $"select value c from c where c.name ='{course.name}' and c.grade={grade} and c.period.id='{period.id}' and c.subject.id='{course.subject?.id}' ";
  497. var resultCourseBase = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<CourseBase>(sqlCourse, $"CourseBase-{school.id}");
  498. foreach (var item in resultCourseBase.list)
  499. {
  500. if (semester.currSemester!=null)
  501. {
  502. string id = $"{semester.studyYear}-{semester.currSemester.id}-{item.id}";
  503. string code = $"CourseTask-{school.id}";
  504. ResponseMessage responseTask = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(id, new PartitionKey(code));
  505. CourseTask courseTask = null;
  506. if (responseTask.StatusCode==System.Net.HttpStatusCode.OK)
  507. {
  508. courseTask = JsonDocument.Parse(responseTask.Content).RootElement.ToObject<CourseTask>();
  509. var scheduleExsit = courseTask.schedules.Find(z => z.groupId.Equals(scheduleSave.groupId));
  510. if (scheduleExsit==null)
  511. {
  512. courseTask.schedules.Add(scheduleSave);
  513. }
  514. else
  515. {
  516. scheduleExsit.teacherId=scheduleSave.teacherId;
  517. }
  518. }
  519. else
  520. {
  521. courseTask = new CourseTask
  522. {
  523. id = id,
  524. code = code,
  525. pk="CourseTask",
  526. ttl=-1,
  527. courseId=item.id,
  528. year= semester.studyYear,
  529. expire= semester.nextSemester.AddDays(-1).ToUnixTimeMilliseconds(),
  530. semesterId=semester.currSemester.id,
  531. schedules=new List<ScheduleTask>() { scheduleSave }
  532. };
  533. }
  534. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseTask, new PartitionKey(code));
  535. }
  536. }
  537. }
  538. }
  539. }
  540. }
  541. return Ok(new { schoolCourseDtos });
  542. }
  543. catch (Exception ex) { return Ok($"{ex.Message},{ex.StackTrace}"); }
  544. }
  545. /// <summary>
  546. ///
  547. /// </summary>
  548. /// <param name="request"></param>
  549. /// <returns></returns>
  550. [ProducesDefaultResponseType]
  551. [HttpPost("data-migration")]
  552. public async Task<IActionResult> DataMigration(JsonElement request)
  553. {
  554. try
  555. {
  556. List<Course> schoolCourses = new List<Course>();
  557. HashSet<string> schoolIds = new HashSet<string>();
  558. string sql = "select value c from c where c.pk='Course' ";
  559. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetItemQueryIteratorSql<Course>(queryText: sql))
  560. {
  561. if (!string.IsNullOrWhiteSpace(item.school))
  562. {
  563. List<string> ignores = new List<string>();
  564. if (request.TryGetProperty("ignores", out JsonElement _ignores))
  565. {
  566. ignores= _ignores.ToObject<List<string>>();
  567. }
  568. if (item.school.Equals("ydzt") ||item.school.Equals("xcfx") ||item.school.Equals("hlgj") ||item.school.Equals("hbcn")
  569. ||item.school.Equals("kjyxx") ||item.school.Equals("bjgsex") || item.school.Equals("cdxxps") ||item.school.Equals("pclxxx"))
  570. {
  571. //大陆站强制不处理的学校
  572. }
  573. else
  574. {
  575. if (!ignores.Contains(item.school))
  576. {
  577. schoolCourses.Add(item);
  578. schoolIds.Add(item.school);
  579. }
  580. }
  581. }
  582. }
  583. List<School> schools = new List<School>();
  584. if (schoolIds.Count>0)
  585. {
  586. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>($"select value c from c where c.id in ({string.Join(",", schoolIds.Select(z => $"'{z}'"))})", "Base");
  587. if (result.list.IsNotEmpty())
  588. {
  589. schools.AddRange(result.list);
  590. }
  591. }
  592. List<CourseDto> schoolCourseDtos = new List<CourseDto>();
  593. foreach (var course in schoolCourses)
  594. {
  595. var school = schools.Find(z => z.id.Equals(course.school));
  596. if (school==null) { continue; }
  597. var period = school.period.Find(z => z.id.Equals(course.period?.id));
  598. if (period==null)
  599. {
  600. continue;
  601. }
  602. var semester = SchoolService.GetSemester(period, time: "2023-07-01");
  603. CourseBase courseBase = null;
  604. ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemStreamAsync(course.id, new PartitionKey($"CourseBase-{school.id}"));
  605. if (response.StatusCode==System.Net.HttpStatusCode.OK)
  606. {
  607. courseBase = JsonDocument.Parse(response.Content).RootElement.ToObject<CourseBase>();
  608. }
  609. else
  610. {
  611. courseBase = new CourseBase()
  612. {
  613. id= course.id,
  614. code=$"CourseBase-{school.id}",
  615. pk="CourseBase",
  616. ttl=-1,
  617. name=course.name,
  618. subject= new IdName { id=course.subject?.id, name=course.subject?.name },
  619. period= new IdName { id= course.period?.id, name =course.period?.name },
  620. school=school.id,
  621. scope="school",
  622. no=course.no,
  623. creatorId=course.creatorId,
  624. desc=course.desc,
  625. status=1,
  626. grade=0,
  627. };
  628. }
  629. List<ScheduleTask> schedules = new List<ScheduleTask>();
  630. int grade = -1;
  631. foreach (var schedule in course.schedule)
  632. {
  633. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.classId))
  634. {
  635. schedules.Add(new ScheduleTask() { type="class", groupId=schedule.classId, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id });
  636. try
  637. {
  638. Class clazz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(schedule.classId, new PartitionKey($"Class-{school.id}"));
  639. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { clazz.year }, 1688140800000);
  640. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  641. {
  642. int.TryParse(gradeData.grades.First(), out grade);
  643. }
  644. }
  645. catch { }
  646. }
  647. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.stulist))
  648. {
  649. schedules.Add(new ScheduleTask() { type="teach", groupId=schedule.stulist, teacherId=schedule.teacherId, roomId= schedule.room, school=school.id });
  650. if (grade==-1)
  651. {
  652. _coreAPIHttpService.check=false;
  653. var groups = await GroupListService.GetMemberByListids(_coreAPIHttpService, _azureCosmos.GetCosmosClient(), _dingDing, new List<string> { schedule.stulist }, school.id);
  654. if (groups.rmembers.IsNotEmpty())
  655. {
  656. var a = groups.rmembers.Where(z => z.type==2 && z.year>0).GroupBy(z => z.year).Select(z => new { key = z.Key, list = z.ToList() }).OrderByDescending(y => y.list.Count).FirstOrDefault();
  657. if (a!=null)
  658. {
  659. var gradeData = SchoolService.GetGrades(school, period.id, new List<int>() { a.key }, 1688140800000);
  660. if (gradeData.grades.Any() && gradeData.grades.Count>0)
  661. {
  662. int.TryParse(gradeData.grades.First(), out grade);
  663. }
  664. }
  665. }
  666. }
  667. }
  668. }
  669. if (grade>-1)
  670. {
  671. courseBase.grade=grade;
  672. }
  673. //补全丢失的科目信息
  674. var subject = period.subjects.Find(z => z.id.Equals(courseBase.subject.id) ||z.name.Equals(courseBase.subject.name));
  675. if (subject== null)
  676. {
  677. period.subjects.Add(new Subject { id =courseBase.subject.id, name=courseBase.subject.name, type=1 });
  678. }
  679. int subjectIndex = period.subjects.FindIndex(z => z.id.Equals(courseBase.subject.id) ||z.name.Equals(courseBase.subject.name));
  680. if (subjectIndex>=0)
  681. {
  682. int index = subjectIndex+1;
  683. courseBase.no= $"{index}01";
  684. }
  685. CourseDto courseDto = new CourseDto();
  686. courseDto.courseBase=courseBase;
  687. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseBase, new PartitionKey(courseBase.code));
  688. if (schedules.IsNotEmpty())
  689. {
  690. if (semester.currSemester!=null)
  691. {
  692. string id = $"{semester.studyYear}-{semester.currSemester.id}-{courseBase.id}";
  693. string code = $"CourseTask-{school.id}";
  694. CourseTask courseTask = new CourseTask
  695. {
  696. id = id,
  697. code = code,
  698. pk="CourseTask",
  699. ttl=-1,
  700. courseId=courseBase.id,
  701. year= semester.studyYear,
  702. expire= semester.nextSemester.AddDays(-1).ToUnixTimeMilliseconds(),
  703. semesterId=semester.currSemester.id,
  704. schedules=schedules
  705. };
  706. courseDto.courseTasks.Add(new CourseTaskDto { courseTask=courseTask, type="school" });
  707. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(courseTask, new PartitionKey(code));
  708. }
  709. }
  710. schoolCourseDtos.Add(courseDto);
  711. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).UpsertItemAsync(school, new PartitionKey(school.code));
  712. }
  713. List<CourseDto> teacherCourseDtos = new List<CourseDto>();
  714. if (request.TryGetProperty("private", out JsonElement _private) && $"{_private}".Equals("1"))
  715. {
  716. List<Course> teacherCourses = new List<Course>();
  717. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<Course>(sql))
  718. {
  719. teacherCourses.Add(item);
  720. }
  721. foreach (var course in teacherCourses)
  722. {
  723. CourseBase courseBase = new CourseBase()
  724. {
  725. id= course.id,
  726. code=$"CourseBase",
  727. pk="CourseBase",
  728. ttl=-1,
  729. name=course.name,
  730. scope="private",
  731. no=course.no,
  732. creatorId=course.creatorId,
  733. desc=course.desc,
  734. status=1,
  735. };
  736. List<ScheduleTask> schedules = new List<ScheduleTask>();
  737. foreach (var schedule in course.schedule)
  738. {
  739. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.classId))
  740. {
  741. schedules.Add(new ScheduleTask() { type="class", groupId=schedule.classId, teacherId=schedule.teacherId, roomId= schedule.room });
  742. }
  743. if (!string.IsNullOrWhiteSpace(schedule.teacherId) && !string.IsNullOrWhiteSpace(schedule.stulist))
  744. {
  745. schedules.Add(new ScheduleTask() { type="teach", groupId=schedule.stulist, teacherId=schedule.teacherId, roomId= schedule.room });
  746. }
  747. }
  748. CourseDto courseDto = new CourseDto();
  749. courseDto.courseBase=courseBase;
  750. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(courseBase, new PartitionKey(courseBase.code));
  751. if (schedules.IsNotEmpty())
  752. {
  753. string id = $"{courseBase.id}";
  754. string code = $"CourseTask";
  755. CourseTask courseTask = new CourseTask
  756. {
  757. id = id,
  758. code = code,
  759. pk="CourseTask",
  760. ttl=-1,
  761. courseId=courseBase.id,
  762. schedules=schedules
  763. };
  764. courseDto.courseTasks.Add(new CourseTaskDto { courseTask=courseTask, type="private" });
  765. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(courseTask, new PartitionKey(code));
  766. }
  767. teacherCourseDtos.Add(courseDto);
  768. }
  769. }
  770. return Ok(new { schoolCourseDtos, teacherCourseDtos });
  771. }
  772. catch (Exception ex) { return Ok($"{ex.Message},{ex.StackTrace}"); }
  773. }
  774. [ProducesDefaultResponseType]
  775. [HttpPost("restore-video-record")]
  776. public async Task<IActionResult> RestoreVideoRecord(JsonElement json)
  777. {
  778. try
  779. {
  780. var client = _azureCosmos.GetCosmosClient();
  781. List<School> schools = new List<School>(0);
  782. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<School>(queryText: "SELECT value(c) FROM c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  783. {
  784. schools.Add(item);
  785. }
  786. List<SchoolTeacher> tmdids = new List<SchoolTeacher>();
  787. foreach (var school in schools)
  788. {
  789. if (!string.IsNullOrEmpty(school.standard))
  790. {
  791. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<SchoolTeacher>(queryText: "SELECT value(c) FROM c",
  792. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"Teacher-{school.id}") }))
  793. {
  794. tmdids.Add(item);
  795. }
  796. }
  797. }
  798. List<(SchoolTeacher Teacher, List<AbilitySub> abilitySubs)> ps = new List<(SchoolTeacher Teacher, List<AbilitySub> abilitySubs)>();
  799. await foreach ((SchoolTeacher tmdid, List<AbilitySub> subs) a in GetSubsAsyn(tmdids, client))
  800. {
  801. if (a.subs.IsNotEmpty())
  802. {
  803. ps.Add(a);
  804. }
  805. }
  806. List<dynamic> datas = new List<dynamic>();
  807. List<TeacherFile> teacherFiles = new List<TeacherFile>();
  808. foreach (var p in ps)
  809. {
  810. Dictionary<string, FileRecord> dict = new Dictionary<string, FileRecord>();
  811. School school = schools.Find(x => p.Teacher.code.Replace("Teacher-", "").Equals(x.id));
  812. if (school != null && !string.IsNullOrEmpty(school.standard))
  813. {
  814. var rcds = p.abilitySubs.SelectMany(x => x.videoRcds);
  815. foreach (var c in rcds)
  816. {
  817. try
  818. {
  819. AbilityTask abilityTask = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AbilityTask>(c.abilityTaskId, new PartitionKey($"AbilityTask-{school.standard}"));
  820. Rnode rnode = null;
  821. Tnode tnode = null;
  822. if (!string.IsNullOrEmpty(c.tnodeId))
  823. {
  824. foreach (var node in abilityTask.children)
  825. {
  826. rnode = node.rnodes.Find(y => y.link.Equals(c.url));
  827. if (rnode != null)
  828. {
  829. tnode = node;
  830. break;
  831. }
  832. }
  833. }
  834. else
  835. {
  836. tnode = abilityTask.children.Find(x => x.id.Equals(c.tnodeId));
  837. if (tnode == null)
  838. {
  839. foreach (var node in abilityTask.children)
  840. {
  841. rnode = node.rnodes.Find(y => y.link.Equals(c.url));
  842. if (rnode != null)
  843. {
  844. tnode = node;
  845. break;
  846. }
  847. }
  848. }
  849. else
  850. {
  851. rnode = tnode.rnodes.Find(y => y.link.Equals(c.url));
  852. }
  853. }
  854. if (rnode != null)
  855. {
  856. if (dict.ContainsKey(rnode.hash))
  857. {
  858. FileRecord fileRecord = dict[rnode.hash];
  859. if (!c.done)
  860. {
  861. if (fileRecord.type.Equals("video") && c.time * 60 > fileRecord.view)
  862. {
  863. fileRecord.view = (long)c.time * 60;
  864. }
  865. var file = fileRecord.files.Find(x => x.abilityId.Equals(abilityTask.abilityId)
  866. && x.taskId.Equals(abilityTask.id) && x.nodeId.Equals(tnode.id) && x.url.Equals(rnode.link));
  867. if (file == null)
  868. {
  869. fileRecord.files.Add(new FileAbility()
  870. {
  871. abilityId = abilityTask.abilityId,
  872. taskId = abilityTask.id,
  873. nodeId = tnode.id,
  874. url = rnode.link
  875. });
  876. }
  877. }
  878. else
  879. {
  880. var file = fileRecord.files.Find(x => x.abilityId.Equals(abilityTask.abilityId)
  881. && x.taskId.Equals(abilityTask.id) && x.nodeId.Equals(tnode.id) && x.url.Equals(rnode.link));
  882. if (file == null)
  883. {
  884. fileRecord.files.Add(new FileAbility()
  885. {
  886. abilityId = abilityTask.abilityId,
  887. taskId = abilityTask.id,
  888. nodeId = tnode.id,
  889. url = rnode.link
  890. });
  891. }
  892. fileRecord.done = true;
  893. fileRecord.view = (long)fileRecord.duration;
  894. }
  895. }
  896. else
  897. {
  898. FileRecord teacherFileRcd = new FileRecord();
  899. FileAbility fileAbility = new FileAbility()
  900. {
  901. abilityId = abilityTask.abilityId,
  902. taskId = abilityTask.id,
  903. nodeId = tnode.id,
  904. url = rnode.link
  905. };
  906. teacherFileRcd.files.Add(fileAbility);
  907. teacherFileRcd.hash = rnode.hash;
  908. teacherFileRcd.duration = rnode.duration;
  909. teacherFileRcd.type = rnode.type;
  910. teacherFileRcd.size = rnode.size != null ? rnode.size.Value : 0;
  911. teacherFileRcd.done = c.done;
  912. if (teacherFileRcd.done)
  913. {
  914. teacherFileRcd.view = (long)teacherFileRcd.duration;
  915. }
  916. else
  917. {
  918. teacherFileRcd.view = (long)(c.time * 60);
  919. }
  920. dict.Add(rnode.hash, teacherFileRcd);
  921. }
  922. }
  923. }
  924. catch (CosmosException ex)
  925. {
  926. Console.WriteLine(c.abilityTaskId);
  927. }
  928. }
  929. TeacherFile teacherFile = null;
  930. try
  931. {
  932. teacherFile = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<TeacherFile>(p.Teacher.id, new PartitionKey($"TeacherFile-{school.id}"));
  933. foreach (var ds in dict)
  934. {
  935. var file = teacherFile.fileRecords.Find(x => x.hash.Equals(ds.Key));
  936. if (file != null)
  937. {
  938. if (!file.done)
  939. {
  940. if (file.type.Equals("video") && file.view < ds.Value.view)
  941. {
  942. file.view = ds.Value.view;
  943. }
  944. }
  945. var nofiles = ds.Value.files.FindAll(x =>
  946. !file.files.Exists(y => x.abilityId.Equals(y.abilityId)
  947. && x.taskId.Equals(y.taskId)
  948. && x.nodeId.Equals(y.nodeId)
  949. && x.url.Equals(y.url)
  950. ));
  951. if (nofiles.IsNotEmpty())
  952. {
  953. file.files.AddRange(ds.Value.files);
  954. }
  955. }
  956. else
  957. {
  958. teacherFile.fileRecords.Add(ds.Value);
  959. }
  960. }
  961. teacherFile = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherFile>(teacherFile, teacherFile.id, new PartitionKey($"TeacherFile-{school.id}"));
  962. teacherFiles.Add(teacherFile);
  963. }
  964. catch (CosmosException ex)
  965. {
  966. teacherFile = new TeacherFile
  967. {
  968. id = p.Teacher.id,
  969. code = $"TeacherFile-{school.id}",
  970. fileRecords = dict.Values.ToList(),
  971. pk = "TeacherFile"
  972. };
  973. teacherFiles.Add(teacherFile);
  974. teacherFile = await client.GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<TeacherFile>(teacherFile, new PartitionKey($"TeacherFile-{school.id}"));
  975. }
  976. datas.Add(new { teacher = p.Teacher, school = school, dict });
  977. }
  978. }
  979. return Ok(new { datas, teacherFiles });
  980. }
  981. catch (Exception ex)
  982. {
  983. }
  984. return Ok();
  985. }
  986. private async IAsyncEnumerable<(SchoolTeacher, List<AbilitySub>)> GetSubsAsyn(List<SchoolTeacher> tmdids, CosmosClient client)
  987. {
  988. foreach (var tmdid in tmdids)
  989. {
  990. List<AbilitySub> abilitySubs = new List<AbilitySub>();
  991. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<AbilitySub>(queryText: "SELECT value(c) FROM c",
  992. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilitySub-{tmdid.code.Replace("Teacher-", "")}-{tmdid.id}") }))
  993. {
  994. abilitySubs.Add(item);
  995. }
  996. var abilitys = abilitySubs.FindAll(x => x.videoRcds.IsNotEmpty());
  997. yield return (tmdid, abilitys);
  998. }
  999. }
  1000. /// <summary>
  1001. ///迁移Stulist数据至GroupList
  1002. /// </summary>
  1003. /// <param name="data"></param>
  1004. /// <returns></returns>
  1005. [ProducesDefaultResponseType]
  1006. //[AuthToken(Roles = "teacher")]
  1007. [HttpGet("restore-stulist")]
  1008. public async Task<IActionResult> RestoreStulist()
  1009. {
  1010. try
  1011. {
  1012. var client = _azureCosmos.GetCosmosClient();
  1013. List<School> schools = new List<School>(0);
  1014. //await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<School>(queryText: "SELECT value(c) FROM c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1015. //{
  1016. // schools.Add(item);
  1017. //}
  1018. /*
  1019. foreach (var school in schools)
  1020. {
  1021. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<StuList>(queryText: "SELECT value(c) FROM c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StuList-{school.id}") }))
  1022. {
  1023. List<Member> members = new List<Member>();
  1024. if (item.students.IsNotEmpty())
  1025. {
  1026. item.students.ForEach(x =>
  1027. {
  1028. members.Add(new Member { id = x.id, code = x.code.Replace("Base-", ""), type = 2, });
  1029. });
  1030. }
  1031. if (item.tmids.IsNotEmpty())
  1032. {
  1033. item.tmids.ForEach(x =>
  1034. {
  1035. members.Add(new Member { id = x, type = 1 });
  1036. });
  1037. }
  1038. GroupList group = new GroupList
  1039. {
  1040. year = DateTimeOffset.UtcNow.Year,
  1041. pk = "GroupList",
  1042. id = item.id,
  1043. code = $"GroupList-{school.id}",
  1044. name = item.name,
  1045. ttl = -1,
  1046. no = item.no,
  1047. periodId = string.IsNullOrEmpty(item.periodId) ? school.period[0]?.id : item.periodId,
  1048. scope = "school",
  1049. creatorId = item.creatorId,
  1050. type = "teach",
  1051. members = members,
  1052. tcount = members.FindAll(x => x.type == 1).Count,
  1053. scount = members.FindAll(x => x.type == 2).Count,
  1054. school = school.id
  1055. };
  1056. await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync(group, new PartitionKey(group.code));
  1057. }
  1058. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<TchList>(queryText: "SELECT value(c) FROM c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"TchList-{school.id}") }))
  1059. {
  1060. List<Member> members = new List<Member>();
  1061. if (item.teachers.IsNotEmpty())
  1062. {
  1063. item.teachers.ForEach(x =>
  1064. {
  1065. members.Add(new Member { id = x, type = 1 });
  1066. });
  1067. }
  1068. GroupList group = new GroupList
  1069. {
  1070. year = DateTimeOffset.UtcNow.Year,
  1071. pk = "GroupList",
  1072. id = item.id,
  1073. code = $"GroupList-{school.id}",
  1074. name = item.name,
  1075. ttl = -1,
  1076. no = item.no,
  1077. scope = "school",
  1078. creatorId = item.creatorId,
  1079. type = "research",
  1080. members = members,
  1081. tcount = members.FindAll(x => x.type == 1).Count,
  1082. scount = members.FindAll(x => x.type == 2).Count,
  1083. school = school.id
  1084. };
  1085. await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync(group, new PartitionKey(group.code));
  1086. }
  1087. }*/
  1088. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<StuList>(queryText: "SELECT value(c) FROM c", requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"StuList") }))
  1089. {
  1090. List<Member> members = new List<Member>();
  1091. if (item.students.IsNotEmpty())
  1092. {
  1093. item.students.ForEach(x => {
  1094. members.Add(new Member { id = x.id, code = x.code.Replace("Base-", ""), type = 2 });
  1095. });
  1096. }
  1097. if (item.tmids.IsNotEmpty())
  1098. {
  1099. item.tmids.ForEach(x => {
  1100. members.Add(new Member { id = x, type = 1 });
  1101. });
  1102. }
  1103. GroupList group = new GroupList
  1104. {
  1105. expire=0,
  1106. year = DateTimeOffset.UtcNow.Year,
  1107. pk = "GroupList",
  1108. id = item.id,
  1109. code = $"GroupList",
  1110. name = item.name,
  1111. ttl = -1,
  1112. no = item.no,
  1113. scope = "private",
  1114. creatorId = item.creatorId,
  1115. type = "teach",
  1116. tcount = members.FindAll(x => x.type == 1).Count,
  1117. scount = members.FindAll(x => x.type == 2).Count,
  1118. members = members,
  1119. };
  1120. await client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync(group, new PartitionKey(group.code));
  1121. }
  1122. }
  1123. catch (Exception ex)
  1124. {
  1125. await _dingDing.SendBotMsg($"OS,restore-stulist()\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1126. }
  1127. return Ok();
  1128. }
  1129. /// <summary>
  1130. /// 迁移教师基础信息,并处理历史数据。
  1131. /// </summary>
  1132. /// <param name="data"></param>
  1133. /// <returns></returns>
  1134. [ProducesDefaultResponseType]
  1135. //[AuthToken(Roles = "teacher")]
  1136. [HttpGet("restore-tmduser")]
  1137. public async Task<IActionResult> RestoreTmdUser()
  1138. {
  1139. var client = _azureCosmos.GetCosmosClient();
  1140. List<TmdUser> users = new List<TmdUser>();
  1141. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<Teacher>(queryText:"select value c from c ", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1142. {
  1143. ///修复历史数据
  1144. if (item.size > 0)
  1145. {
  1146. if (item.pk == null)
  1147. {
  1148. item.pk = "Teacher";
  1149. await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(item, item.id, partitionKey: new PartitionKey("Base"));
  1150. }
  1151. try
  1152. {
  1153. TmdUser user = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<TmdUser>(item.id, partitionKey: new PartitionKey("Base"));
  1154. item.schools.ForEach(x => {
  1155. if (user.schools.Find(y => y.schoolId.Equals(x.schoolId)) == null)
  1156. {
  1157. user.schools.Add(new TmdUser.School { name = x.name, schoolId = x.schoolId, time = x.time, status = x.status });
  1158. }
  1159. });
  1160. users.Add(user);
  1161. await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync<TmdUser>(user, user.id, partitionKey: new PartitionKey("Base"));
  1162. }
  1163. catch (CosmosException ex)
  1164. {
  1165. if (ex.StatusCode == HttpStatusCode.NotFound)
  1166. {
  1167. TmdUser user = item.ToJsonString().ToObject<TmdUser>();
  1168. await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync<TmdUser>(user, partitionKey: new PartitionKey("Base"));
  1169. users.Add(user);
  1170. }
  1171. }
  1172. }
  1173. else
  1174. {
  1175. await client.GetContainer(Constant.TEAMModelOS, "Teacher").DeleteItemAsync<Teacher>(item.id, partitionKey: new PartitionKey("Base"));
  1176. }
  1177. }
  1178. return Ok(new { users });
  1179. }
  1180. }
  1181. }