TestController.cs 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089
  1. using Azure;
  2. using Microsoft.Azure.Cosmos;
  3. using Azure.Storage.Blobs.Models;
  4. using DinkToPdf;
  5. using DinkToPdf.Contracts;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.Options;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Net.Http;
  18. using System.Net.Http.Json;
  19. using System.Text;
  20. using System.Text.Json;
  21. using System.Threading.Tasks;
  22. using TEAMModelOS.Controllers.Third.LePei;
  23. using TEAMModelOS.Filter;
  24. using TEAMModelOS.Models;
  25. using TEAMModelOS.SDK;
  26. using TEAMModelOS.SDK.DI;
  27. using TEAMModelOS.SDK.DI.Mail;
  28. using TEAMModelOS.SDK.Extension;
  29. using TEAMModelOS.SDK.Models;
  30. using TEAMModelOS.SDK.Models.Cosmos;
  31. using TEAMModelOS.SDK.Models.Service;
  32. using TEAMModelOS.SDK.Services;
  33. using static TEAMModelOS.SDK.Models.Teacher;
  34. using static TEAMModelOS.SDK.SchoolService;
  35. namespace TEAMModelOS.Controllers
  36. {
  37. [Route("test")]
  38. [ApiController]
  39. public class TestController : ControllerBase
  40. {
  41. private readonly IHttpClientFactory _httpClient;
  42. public IWebHostEnvironment _environment { get; set; }
  43. private readonly AzureStorageFactory _azureStorage;
  44. private readonly AzureRedisFactory _azureRedis;
  45. private readonly AzureCosmosFactory _azureCosmos;
  46. private readonly DingDing _dingDing;
  47. private readonly AzureServiceBusFactory _serviceBus;
  48. private readonly CoreAPIHttpService _coreAPIHttpService;
  49. private readonly Option _option;
  50. private readonly IPSearcher _searcher;
  51. public IConfiguration _configuration { get; set; }
  52. private readonly IConverter _converter;
  53. private readonly HttpTrigger _httpTrigger;
  54. private readonly AzureServiceBusFactory _azureService;
  55. private readonly SnowflakeId _snowflakeId;
  56. private readonly MailFactory _mailFactory;
  57. public TestController(MailFactory mailFactory,HttpTrigger httpTrigger, IConverter converter, IPSearcher searcher, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory httpClient, IWebHostEnvironment environment, AzureCosmosFactory azureCosmos, AzureRedisFactory azureRedis, AzureStorageFactory azureStorage, IConfiguration configuration, AzureServiceBusFactory serviceBus, DingDing dingDing, AzureServiceBusFactory azureService, SnowflakeId snowflakeId)
  58. {
  59. _converter = converter;
  60. _azureCosmos = azureCosmos;
  61. _azureRedis = azureRedis;
  62. _azureStorage = azureStorage;
  63. _dingDing = dingDing;
  64. _serviceBus = serviceBus; _configuration = configuration;
  65. _environment = environment;
  66. _httpClient = httpClient;
  67. _option = option.Value;
  68. _coreAPIHttpService = coreAPIHttpService;
  69. _searcher = searcher;
  70. _httpTrigger = httpTrigger;
  71. _azureService=azureService;
  72. _snowflakeId=snowflakeId;
  73. _mailFactory = mailFactory;
  74. }
  75. //
  76. /// <summary>
  77. /// 移除已经废弃的StuCourse 数据
  78. /// </summary>
  79. /// <param name="file"></param>
  80. /// <param name="periodId"></param>
  81. /// <returns></returns>
  82. [HttpGet("test-str")]
  83. [RequestSizeLimit(102_400_000_00)] //最大10000m左右
  84. public async Task<IActionResult> Tes1t() {
  85. string sql= "select * from c where c.code='Base-sdztbx' and c.year =2019";
  86. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).GetList<Student>(sql, "Base-sdztbx");
  87. if (result.list.IsNotEmpty())
  88. {
  89. foreach (var item in result.list)
  90. {
  91. item.graduate=0;
  92. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS,Constant.Student).UpsertItemAsync<Student>(item, new PartitionKey(item.code));
  93. }
  94. }
  95. return Ok( );
  96. }
  97. /// <summary>
  98. /// 移除已经废弃的StuCourse 数据
  99. /// </summary>
  100. /// <param name="file"></param>
  101. /// <param name="periodId"></param>
  102. /// <returns></returns>
  103. [HttpPost("test-accumulate")]
  104. [RequestSizeLimit(102_400_000_00)] //最大10000m左右
  105. public async Task<IActionResult> RemoveStuCourse(JsonElement json)
  106. {
  107. json.TryGetProperty("am", out JsonElement _am);
  108. json.TryGetProperty("pm", out JsonElement _pm);
  109. int am = 0;
  110. int pm = 0;
  111. _am.TryGetInt32(out am);
  112. _pm.TryGetInt32(out pm);
  113. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  114. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  115. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  116. string location = "";
  117. if (_option.Location.Contains("China"))
  118. {
  119. location = "China";
  120. }
  121. else if (_option.Location.Contains("Global"))
  122. {
  123. location = "Global";
  124. }
  125. var client = _httpClient.CreateClient();
  126. var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location).Result;
  127. if (client.DefaultRequestHeaders.Contains("Authorization"))
  128. {
  129. client.DefaultRequestHeaders.Remove("Authorization");
  130. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  131. }
  132. else
  133. {
  134. client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  135. }
  136. List<CodeValue> notifys= await SystemService.AccumulateDaily(_configuration, _azureRedis,_azureCosmos,_azureStorage, _coreAPIHttpService,_dingDing,client, _snowflakeId, url,am ,pm );
  137. return Ok(new { notifys });
  138. }
  139. /*
  140. [
  141. {
  142. "id": "99a4a33b-e21b-44ac-80a1-b31dc40496e0",
  143. "name": "蒲江县提升工程2.0研训平台"
  144. },
  145. {
  146. "id": "f35e0031-a53f-45e5-b307-1cd39446a2cf",
  147. "name": "金牛区直属学校提升工程2.0研训平台"
  148. },
  149. {
  150. "id": "2c1b01fe-3641-464f-8499-7be95a489b7c",
  151. "name": "峨边彝族自治县提升工程2.0研训平台"
  152. },
  153. {
  154. "id": "870a5a6b-1ab3-461a-bdeb-baec19780ddb",
  155. "name": "金牛区非直属学校提升工程2.0研训平台"
  156. },
  157. {
  158. "id": "dd15017a-f361-4346-852e-8eee71d027ad",
  159. "name": "峨眉山提升工程2.0研训平台"
  160. },
  161. {
  162. "id": "3b5a9b06-a9ec-4bac-b1dd-f73f5519f637",
  163. "name": "乐山市井研县提升工程2.0研训平台"
  164. },
  165. {
  166. "id": "1680c1c5-14e4-4bc2-b4cb-1749a537a01f",
  167. "name": "宜宾市筠连县提升工程2.0研训平台"
  168. },
  169. {
  170. "id": "e6fb5d40-bd85-7327-cea8-ea5c642836d2",
  171. "name": "广安市岳池县提升工程2.0研训平台"
  172. },
  173. {
  174. "id": "b14668be-d2f0-4923-8bf6-a27d9cc9111d",
  175. "name": "犍为县提升工程2.0研训平台"
  176. },
  177. {
  178. "id": "f49a83de-6156-448a-93b1-f03d0da967d6",
  179. "name": "宜宾市屏山县提升工程2.0研训平台"
  180. },
  181. {
  182. "id": "4a37997a-12b1-4f21-876b-3d9ba940fe54",
  183. "name": "宜宾市屏山县提升工程2.0研训平台(非一线)"
  184. },
  185. {
  186. "id": "6104c377-f48f-4d4c-9b38-509f9ccb54db",
  187. "name": "武胜县提升工程2.0研训平台"
  188. }
  189. ]
  190. */
  191. /// <summary>
  192. /// 将区级下所以学校的研修数据封存
  193. /// </summary>
  194. /// <param name="data"></param>
  195. /// <returns></returns>
  196. [HttpPost("change-blob-to-archive")]
  197. [RequestSizeLimit(102_400_000_00)] //最大10000m左右
  198. public async Task<IActionResult> Change(JsonElement data)
  199. {
  200. IdName area = null;
  201. if (data.TryGetProperty("area", out JsonElement _area))
  202. {
  203. area= _area.ToObject<IdName>();
  204. }
  205. List<ScTeacher> teachers = new List<ScTeacher>();
  206. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  207. List<int> pids = new List<int>();
  208. if (data.TryGetProperty("pids", out JsonElement _pids))
  209. {
  210. pids=_pids.ToObject<List<int>>();
  211. }
  212. if (pids.IsNotEmpty()) {
  213. foreach (var p in pids)
  214. {
  215. List<ScTeacher> teachersTable= await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "ProjectItemID", p } });
  216. if (teachersTable.IsNotEmpty()) {
  217. teachers.AddRange(teachersTable);
  218. }
  219. }
  220. }
  221. HashSet<string> ids = teachers.Where(v => !string.IsNullOrWhiteSpace(v.tmdid)).Select(z => z.tmdid).ToHashSet();
  222. List<SchoolEconomy> economies = new List<SchoolEconomy>(0);
  223. if (area!= null)
  224. {
  225. string sql = $"select value c from c where c.areaId ='{area.id}'";
  226. List<School> schools = new List<School>();
  227. var result = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(sql, "Base");
  228. if (result.list.IsNotEmpty())
  229. {
  230. schools.AddRange(result.list);
  231. }
  232. foreach (var school in schools)
  233. {
  234. double? ScoresYxpt = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{school.id}", "yxpt");
  235. double? ScoresTrain = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:{school.id}", "train");
  236. double total = ((ScoresYxpt.HasValue ? ScoresYxpt.Value : 0)+(ScoresTrain.HasValue ? ScoresTrain.Value : 0))*1.0 /1073741824; //GB
  237. List<string> yxpts = await _azureStorage.GetBlobContainerClient(school.id).List("yxpt");
  238. HashSet<string> archive = new HashSet<string>();
  239. if (yxpts.IsNotEmpty()) {
  240. foreach (var uri in yxpts)
  241. {
  242. if (ids!=null && ids.Count>0)
  243. {
  244. bool has = false;
  245. foreach (var id in ids)
  246. {
  247. if (uri.Contains(id))
  248. {
  249. has = true;
  250. break;
  251. }
  252. }
  253. if (!has)
  254. {
  255. archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
  256. }
  257. }
  258. else
  259. {
  260. archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
  261. }
  262. }
  263. }
  264. List<string> trains = await _azureStorage.GetBlobContainerClient(school.id).List("train");
  265. if (trains.IsNotEmpty())
  266. {
  267. foreach (var uri in trains)
  268. {
  269. if (ids!=null && ids.Count>0)
  270. {
  271. bool has = false;
  272. foreach (var id in ids)
  273. {
  274. if (uri.Contains(id))
  275. {
  276. has = true;
  277. break;
  278. }
  279. }
  280. if (!has)
  281. {
  282. archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
  283. }
  284. }
  285. else
  286. {
  287. archive.Add($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/{uri}");
  288. }
  289. }
  290. }
  291. if (archive.Count==0)
  292. {
  293. economies.Add(new SchoolEconomy { schoolId= school.id, schoolName= school.name, areaId=area.id, areaName=area.name, total=0, count=(yxpts!=null ? yxpts.Count : 0)+(trains!=null ? trains.Count : 0), archive=archive.Count });
  294. }
  295. else
  296. {
  297. //var pages = archive.Page(100);
  298. //foreach (var page in pages) {
  299. // if (page.Count()==0) { continue; }
  300. // try
  301. // {
  302. // await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(blobUris: page.Select(z => new Uri(z)), accessTier: AccessTier.Archive);
  303. // }
  304. // catch (Exception ex1)
  305. // {
  306. // var p20s = page.Page(20);
  307. // foreach (var p20 in p20s)
  308. // {
  309. // if (p20.Count()==0) { continue; }
  310. // try
  311. // {
  312. // await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(blobUris: p20.Select(z => new Uri(z)), accessTier: AccessTier.Archive);
  313. // }
  314. // catch (Exception ex2)
  315. // {
  316. // var p1s = p20.Page(1);
  317. // foreach (var p1 in p1s) {
  318. // if (p1.Count()==0) { continue; }
  319. // try
  320. // {
  321. // string path = p1.First().Replace($"https://teammodeltest.blob.core.chinacloudapi.cn/{school.id}/", "");
  322. // await _azureStorage.GetBlobContainerClient(school.id).GetBlobClient(path).SetAccessTierAsync(AccessTier.Archive);
  323. // }
  324. // catch (Exception ex3)
  325. // {
  326. // await _dingDing.SendBotMsg($"错误的链接地址:{p1.ToJsonString()}", GroupNames.成都开发測試群組);
  327. // }
  328. // }
  329. // }
  330. // }
  331. // }
  332. //}
  333. economies.Add(new SchoolEconomy { schoolId= school.id, schoolName= school.name, areaId=area.id, areaName=area.name, total=total, count=(yxpts!=null ? yxpts.Count : 0)+(trains!=null ? trains.Count : 0), archive=archive.Count });
  334. }
  335. }
  336. AreaEconomy economy = new AreaEconomy {id = area.id ,name = area.name, pk="AreaEconomy",code="AreaEconomy", economies= economies, sum= economies.Select(z => z.total).Sum(), count= economies.Select(z => z.count).Sum(), teachers= ids.ToList() };
  337. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).UpsertItemAsync(economy, new PartitionKey("AreaEconomy"));
  338. return Ok(new { economy });
  339. }
  340. else { return Ok(); }
  341. }
  342. public class AreaEconomy : CosmosEntity
  343. {
  344. public AreaEconomy(){
  345. pk="AreaEconomy";
  346. code="AreaEconomy";
  347. }
  348. public List<int> pids = new List<int>();
  349. public string name { get; set; }
  350. public List<SchoolEconomy> economies { get; set; } = new List<SchoolEconomy>();
  351. public double sum { get; set; }
  352. public long count { get; set; }
  353. /// <summary>
  354. /// 未被封存的教师
  355. /// </summary>
  356. public List<string> teachers = new List<string>();
  357. }
  358. public class SchoolEconomy {
  359. public string schoolId { get; set; }
  360. public string schoolName { get; set; }
  361. public string areaId { get; set; }
  362. public string areaName { get; set; }
  363. public double total { get; set; }
  364. public long count { get; set; }
  365. public long archive { get; set; }
  366. }
  367. [ProducesDefaultResponseType]
  368. [HttpPost("test-ru")]
  369. public async Task<IActionResult> FixSemester(JsonElement json)
  370. {
  371. await _azureStorage.GetBlobContainerClient("hscjzx").GetBlobClient("yxpt/standard3/jyzx/1639448922/691a16ca-b45a-4426-8e2d-162484af5d1d/B2-曹-微课方案.pdf").SetAccessTierAsync(AccessTier.Archive);
  372. await _azureStorage.GetBlobContainerClient("jlstcz").GetBlobClient("yxpt/standard14/jyzx/1657242924/b5625069-b8b7-431b-ab2a-643d9e2f80be/14岁少年沉迷网络,妈妈苦口婆心不起作用,偷偷躲在角落痛哭! 480P(标清)_format_2 (1).mp4").SetAccessTierAsync(AccessTier.Archive);
  373. //string url1 = HttpUtility.UrlPathEncode("https://teammodeltest.blob.core.chinacloudapi.cn/hscjzx/yxpt/standard3/jyzx/1639448922/691a16ca-b45a-4426-8e2d-162484af5d1d/B2-曹-微课方案.pdf");
  374. //string url2 = HttpUtility.UrlPathEncode("https://teammodeltest.blob.core.chinacloudapi.cn/jlstcz/yxpt/standard14/jyzx/1657242924/b5625069-b8b7-431b-ab2a-643d9e2f80be/14岁少年沉迷网络,妈妈苦口婆心不起作用,偷偷躲在角落痛哭! 480P(标清)_format_2 (1).mp4");
  375. //await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(
  376. // blobUris: new Uri[] { new Uri(url1),
  377. // new Uri(url2) }, accessTier: AccessTier.Archive);
  378. double? Scores = await _azureRedis.GetRedisClient(8).SortedSetScoreAsync($"Blob:Catalog:ssjxx", "yxpt");
  379. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "yxpt", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  380. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "train", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  381. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "survey", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  382. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "records", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  383. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "homework", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  384. //await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = "exam", name = $"ssjxx" }, _serviceBus, _configuration, _azureRedis);
  385. string topicName= "dep-active-task";
  386. List< string> msgStrs = new List< string>();
  387. //var client = new ServiceBusAdministrationClient("Endpoint=sb://teammodelos.servicebus.chinacloudapi.cn/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=Sy4h4EQ8zP+7w/lOLi1X3tGord/7ShFHimHs1vC50Dc=");
  388. //var subsPages = client.GetSubscriptionsAsync(topicName);
  389. //await foreach (var page in subsPages.AsPages()) {
  390. // var subs= page.Values;
  391. // foreach (var sub in subs) {
  392. // var receiver = _azureService.GetServiceBusClient().CreateReceiver( topicName, sub.SubscriptionName, new ServiceBusReceiverOptions
  393. // {
  394. // ReceiveMode = ServiceBusReceiveMode.PeekLock
  395. // });
  396. // var scheduledMessages = await receiver.PeekMessagesAsync(100);
  397. // foreach (var message in scheduledMessages)
  398. // {
  399. // Console.WriteLine($"Scheduled Message: {message.Body}");
  400. // Console.WriteLine($"Scheduled Enqueue Time: {message.ScheduledEnqueueTime}");
  401. // Console.WriteLine("--------------------");
  402. // }
  403. // await receiver.CloseAsync();
  404. // }
  405. //}
  406. return Ok(msgStrs);
  407. //await _azureStorage.GetBlobContainerClient("0-public").GetBlobClient("winteach.cn_nginx.zip").SetAccessTierAsync(AccessTier.Archive);
  408. //await _azureStorage.GetBlobServiceClient().GetBlobBatchClient().SetBlobsAccessTierAsync(
  409. // blobUris: new Uri[] { new Uri("https://teammodeltest.blob.core.chinacloudapi.cn/0-public/test.md"),
  410. // new Uri("https://teammodeltest.blob.core.chinacloudapi.cn/0-public/pay.html") },accessTier:AccessTier.Archive);
  411. //var cm = _azureRedis.GetConnectionMultiplexer();
  412. //var keys = cm.GetServer(cm.GetEndPoints()[0]).Keys(cm.GetDatabase(8).Database,"Blob:Catalog*");
  413. //List<string> ks = new List<string>();
  414. //foreach (var key in keys)
  415. //{
  416. // ks.Add(key.ToString());
  417. //}
  418. //var result4 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam'and c.owner='teacher'", null, pageSize: 200);
  419. //var result0 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam'and c.owner='teacher' and STARTSWITH(c.code,'Exam-')", null, pageSize: 200);
  420. //var result1 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='teacher' and contains(c.code,'Exam-')", null, pageSize: 200);
  421. //var result2 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='school' and contains(c.code,'Exam-hbc')", null, pageSize: 200);
  422. //var result3 = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Common).GetList<ExamInfo>($"select value c from c where c.pk='Exam' and c.owner='school' ", "Exam-hbcn", pageSize: 200);
  423. //return Ok(new { ru4 = result4.ru, count4 = result4.list.Count, ru0 = result0.ru, count0 = result0.list.Count(), ru1 = result1.ru, count1 = result1.list.Count(), ru2 = result2.ru, count2 = result2.list.Count(), ru3 = result3.ru, count3 = result3.list.Count() });
  424. }
  425. /// <summary>
  426. /// 测试五育画像数据推送
  427. /// </summary>
  428. /// <param name="json"></param>
  429. /// <returns></returns>
  430. [ProducesDefaultResponseType]
  431. [HttpPost("period")]
  432. public async Task<IActionResult> period(JsonElement json)
  433. {
  434. List<string> names = new List<string>();
  435. if (json.TryGetProperty("names", out JsonElement _names))
  436. {
  437. names= _names.ToObject<List<string>>();
  438. }
  439. List<Period> periods = new List<Period>();
  440. if (json.TryGetProperty("period", out JsonElement _period))
  441. {
  442. foreach (var name in names) {
  443. Period period = _period.ToObject<Period>();
  444. period.name= name;
  445. period.id= Guid.NewGuid().ToString();
  446. period.semesters.ForEach(z => z.id= Guid.NewGuid().ToString());
  447. period.analysis.type.ForEach(z => z.id= Guid.NewGuid().ToString());
  448. period.subjectCount=0;
  449. periods.Add(period);
  450. }
  451. }
  452. return Ok(periods);
  453. }
  454. /// <summary>
  455. /// 测试五育画像数据推送
  456. /// </summary>
  457. /// <param name="json"></param>
  458. /// <returns></returns>
  459. [ProducesDefaultResponseType]
  460. [HttpPost("import-table")]
  461. public async Task<IActionResult> ImportTable(JsonElement json)
  462. {
  463. List<LPSchool> schools = json.ToObject<List<LPSchool>>();
  464. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  465. await table.BatchInsertAsync (schools);
  466. return Ok(schools);
  467. }
  468. /// <summary>
  469. /// 测试五育画像数据推送
  470. /// </summary>
  471. /// <param name="json"></param>
  472. /// <returns></returns>
  473. [ProducesDefaultResponseType]
  474. [HttpPost("test-upsert-student-portrait")]
  475. public async Task<IActionResult> TestUpsertStudentPortrait(JsonElement json) {
  476. var data = await _httpTrigger.RequestHttpTrigger(json, _option.Location, "upsert-student-portrait");
  477. return Ok(data.json.ToObject<JsonElement>());
  478. }
  479. /// <summary>
  480. ///
  481. /// </summary>
  482. /// <param name="json"></param>
  483. /// <returns></returns>
  484. [ProducesDefaultResponseType]
  485. [HttpPost("transform-lessonrecord-overalleducation")]
  486. public async Task<IActionResult> TransformLessonrecordOveralleducation(JsonElement json) {
  487. //string msg = json.ToString();
  488. //var ActiveTask = _configuration.GetValue<string>("Azure:ServiceBus:ActiveTask");
  489. //var messageChange = new ServiceBusMessage(msg);
  490. //messageChange.ApplicationProperties.Add("name", "LessonRecordEvent");
  491. //await _serviceBus.GetServiceBusClient().SendMessageAsync(ActiveTask, messageChange);
  492. string sql = "select value c from c where c.pk='StudentScoreRecord' and c.userType='student' and c.school<>null and c.school<>'' ";
  493. List<StudentScoreRecord> studentScores = new List<StudentScoreRecord>();
  494. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIteratorSql<StudentScoreRecord>(sql)) {
  495. studentScores.Add(item);
  496. }
  497. var group = studentScores.GroupBy(z => z.school);
  498. string schoolSql = $"select value c from c where c.id in ({string.Join(",",group.Select(x=>$"'{x.Key}'"))})";
  499. var resultScool= await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).GetList<School>(schoolSql,"Base");
  500. foreach(var item in group)
  501. {
  502. var list = item.ToList();
  503. var stuids = list.Select(z => z.stuid);
  504. string studentSql = $"select value c from c where c.id in ({string.Join(",", stuids.Select(x => $"'{x}'"))})";
  505. var resultStuden = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetList<Student>(studentSql, $"Base-{item.Key}");
  506. foreach (var sturecord in list) {
  507. HashSet<OverallEducation> overallEducations = new HashSet<OverallEducation>();
  508. var studentBase = resultStuden.list.Find(x => x.id.Equals(sturecord.stuid, StringComparison.OrdinalIgnoreCase));
  509. var schoolBase = resultScool.list.Find(x => x.id.Equals(sturecord.school, StringComparison.OrdinalIgnoreCase));
  510. if (studentBase == null) {
  511. continue;
  512. }
  513. var period = schoolBase.period.Find(x => x.id.Equals($"{studentBase.periodId}"));
  514. foreach (var record in sturecord.lessonRecords) {
  515. if (record.time > 1000000000000) {
  516. (Semester currSemester, int studyYear, DateTimeOffset currSemesterDate, DateTimeOffset date, DateTimeOffset nextSemester) dataSemester = SchoolService.GetSemester(period, record.time);
  517. string oid = $"{dataSemester.studyYear}-{dataSemester.currSemester.id}-{sturecord.stuid}";
  518. string ocode = $"OverallEducation-{sturecord.school}";
  519. OverallEducation overallEducation = overallEducations.Where(o => o.id.Equals(oid, StringComparison.OrdinalIgnoreCase) && o.code.Equals(ocode, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
  520. if (overallEducation != null)
  521. {
  522. var hasrecord = overallEducation.lessonScore.Find(x => x.lessonId.Equals(record.lessonId));
  523. if (hasrecord != null)
  524. {
  525. hasrecord.gscore = record.gscore;
  526. hasrecord.pscore = record.pscore;
  527. hasrecord.tscore = record.tscore;
  528. hasrecord.tmdid = record.tmdid;
  529. hasrecord.school = record.school;
  530. hasrecord.scope = record.scope;
  531. hasrecord.lessonId = record.lessonId;
  532. hasrecord.courseId = record.courseId;
  533. hasrecord.periodId = record.periodId;
  534. hasrecord.subjectId = record.subjectId;
  535. hasrecord.time = record.time;
  536. }
  537. else
  538. {
  539. overallEducation.lessonScore.Add(
  540. new StudentLessonRecord
  541. {
  542. gscore = record.gscore,
  543. pscore = record.pscore,
  544. tscore = record.tscore,
  545. tmdid = record.tmdid,
  546. school = record.school,
  547. scope = record.scope,
  548. lessonId = record.lessonId,
  549. courseId = record.courseId,
  550. periodId = record.periodId,
  551. subjectId = record.subjectId,
  552. time = record.time
  553. }
  554. );
  555. }
  556. }
  557. else {
  558. ResponseMessage response = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).ReadItemStreamAsync(oid, new PartitionKey(ocode));
  559. if (response.StatusCode != HttpStatusCode.OK)
  560. {
  561. overallEducation = new OverallEducation
  562. {
  563. id = oid,
  564. code = $"OverallEducation-{sturecord.school}",
  565. pk = "OverallEducation",
  566. ttl = -1,
  567. name = studentBase.name,
  568. classId = studentBase?.classId,
  569. schoolCode = $"{sturecord.school}",
  570. semesterId = dataSemester.currSemester.id,
  571. year = dataSemester.studyYear,
  572. periodId = $"{period.id}",
  573. stuYear = studentBase.year,
  574. studentId = studentBase.id,
  575. lessonScore = new List<StudentLessonRecord>
  576. {
  577. new StudentLessonRecord
  578. {
  579. gscore = record.gscore,
  580. pscore = record.pscore,
  581. tscore = record.tscore,
  582. tmdid = record.tmdid,
  583. school = record.school,
  584. scope = record.scope,
  585. lessonId = record.lessonId,
  586. courseId = record.courseId,
  587. periodId = record.periodId,
  588. subjectId = record.subjectId,
  589. time= record.time
  590. }
  591. }
  592. };
  593. }
  594. else
  595. {
  596. overallEducation = JsonDocument.Parse(response.Content).RootElement.ToObject<OverallEducation>();
  597. var hasrecord = overallEducation.lessonScore.Find(x => x.lessonId.Equals(record.lessonId));
  598. if (hasrecord != null)
  599. {
  600. hasrecord.gscore = record.gscore;
  601. hasrecord.pscore = record.pscore;
  602. hasrecord.tscore = record.tscore;
  603. hasrecord.tmdid = record.tmdid;
  604. hasrecord.school = record.school;
  605. hasrecord.scope = record.scope;
  606. hasrecord.lessonId = record.lessonId;
  607. hasrecord.courseId = record.courseId;
  608. hasrecord.periodId = record.periodId;
  609. hasrecord.subjectId = record.subjectId;
  610. hasrecord.time = record.time;
  611. }
  612. else
  613. {
  614. overallEducation.lessonScore.Add(
  615. new StudentLessonRecord
  616. {
  617. gscore = record.gscore,
  618. pscore = record.pscore,
  619. tscore = record.tscore,
  620. tmdid = record.tmdid,
  621. school = record.school,
  622. scope = record.scope,
  623. lessonId = record.lessonId,
  624. courseId = record.courseId,
  625. periodId = record.periodId,
  626. subjectId = record.subjectId,
  627. time = record.time
  628. }
  629. );
  630. }
  631. }
  632. overallEducations.Add(overallEducation);
  633. }
  634. }
  635. }
  636. foreach (var overallEducation in overallEducations) {
  637. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).UpsertItemAsync(overallEducation, partitionKey: new PartitionKey(overallEducation.code));
  638. }
  639. }
  640. }
  641. return Ok();
  642. }
  643. /// <summary>
  644. ///
  645. /// </summary>
  646. /// <param name="json"></param>
  647. /// <returns></returns>
  648. [ProducesDefaultResponseType]
  649. [HttpPost("check-art-result")]
  650. public async Task<IActionResult> CheckArtResult(JsonElement json)
  651. {
  652. List<StudentArtResult> art_idNames = new List<StudentArtResult>();
  653. string sqlSchool = "select value c from c where c.areaId='7a51072f-b329-4e74-99e0-ba0407ba8926'";
  654. List<School> schools = new List<School>();
  655. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School)
  656. .GetItemQueryIteratorSql<School>(sqlSchool, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  657. {
  658. schools.Add(item);
  659. }
  660. string sql = @"SELECT value c FROM c where c.pk='ArtResult' and c.artId in('770fbaaa-a9e8-4d45-a322-3c6d6e50a8f7',
  661. '1e59bb5f-984f-406d-83a2-48ef1ce60a75',
  662. '33fc9276-60c1-4663-8c42-2e44a138a874',
  663. '4eada95b-a408-4a66-bd6c-c61c6057d505',
  664. 'f61b32c6-2f86-4ae6-ac25-1961df0f443a',
  665. '4d974b69-e104-45db-8047-b4cbc43ebc98',
  666. 'efb8f6ed-74b9-43b7-b8e5-c61d92441ed9',
  667. '070d8ce5-253c-404b-80b7-12cbc234ddae',
  668. 'fdd6c34b-44c2-42e9-9cd4-66c01b7103da',
  669. 'b1cf6fed-a4ea-4d06-b15d-3941fba973de',
  670. '67cd2be9-e307-4d35-8249-6d4e7380d15c',
  671. 'f0481d0e-ab74-4117-8600-a375a206e283',
  672. '7a809ab3-4081-4a23-8127-9a362f9af8ff',
  673. '673684e2-1dc3-48d9-a21f-207cc40a68ba',
  674. '35e4da67-0fb9-4683-9fac-9c9b1c197f24',
  675. '893b9871-8518-4f70-97e5-58ceb4c1b504',
  676. '0cd4ea92-4697-468a-a2fd-2f0e1cd53525',
  677. 'd9fec69f-2532-408b-bc25-98a33edf7200',
  678. '02b68eed-29f2-49c1-a91f-c1e35dd8ce64',
  679. 'edaf8c12-9b0b-4b31-baff-3e9b926b401a',
  680. '472bbdc9-c287-4b18-9502-7f34d15172a8',
  681. '41f67e3c-6c7f-46e9-bc39-ec8d6ae9a495',
  682. 'ffea1c6b-3fb7-40d4-921b-e1dc46d15410',
  683. '079fa190-fc18-46b9-bcb9-a4b6e2cd902d',
  684. 'a0e778e8-2590-431e-b761-4929fa143762',
  685. '374a571a-6d5c-4a8a-ab57-6e79b8b8ff0a',
  686. '1db3838e-d7cd-4c77-af70-d3854262d33e',
  687. '7b8a2f53-3b90-48f1-bd0b-bb5be843656a',
  688. 'e5c24756-1ea3-46cf-8f0f-357ec280e42c',
  689. '1b713f31-7e0b-4cb5-84f1-0342db618a6d',
  690. '1794bc46-d0fb-4ea9-8ff8-2f813affe495',
  691. 'b9d54179-7eaf-426b-a44f-9018e6c4ffa7',
  692. '3145e47a-21e5-4cdf-a992-72b9e47c7bad',
  693. 'bdaab0b2-f8d0-4c1b-821c-95b4a2371c42',
  694. 'd39f74df-dc65-44d4-8463-41af1a4b186d',
  695. '79e83de1-4e64-4ef3-b24e-fe4e877e683b',
  696. 'bf3aaff3-1a86-42c8-89d7-4b9d6147d37f',
  697. 'ad3742eb-9e46-43f8-9644-ecb498082810',
  698. '66a3d74b-3946-42c3-a2d2-0bc6704c86ec',
  699. 'ec75e499-f432-41d4-b6dd-5548358b657d',
  700. '70ef5724-f875-4e2e-bda8-58fd2457c2a7',
  701. '60c03852-8c97-4cb0-a232-e0734eaebe96',
  702. '4eefe05d-3df9-4f27-804b-53dd7bc5f4ab',
  703. 'b82ff879-5474-4b31-b3e6-3174361a4fd0',
  704. '09489fef-5490-4b5e-802b-74d1be2c5515',
  705. '1a7d8d51-f828-4f15-9859-33937b41b9e4',
  706. '9e591e75-538e-426d-862d-b043c13e822a',
  707. '71cd894a-e82d-49ff-a204-a64a2eb6f332',
  708. '70103a11-095b-4d01-b3ea-0ed2e388445f',
  709. 'b40d4952-396d-49f3-ba2d-6aeba1d940d9',
  710. '149a12ae-7c5d-444c-ac34-17af88cf653e',
  711. '8c1b2180-4a81-4f6b-989a-b971dbeae082',
  712. '079107f5-7bf5-4955-a39c-85dec9715e60',
  713. 'f9abe967-dbce-46d7-a60f-d9a2e6866ec6',
  714. 'b4684520-cf0c-473c-aa3a-ea5ba5d398d3',
  715. '0839abf0-07e7-4c0d-b818-54d451a6265a',
  716. '6abc82c7-928b-43bf-8c5d-f5a5d7c55a4d',
  717. '544577d3-c4b0-491f-a041-18cc07e711ca',
  718. '2efddd68-0bbc-4dba-a594-f7f8532f519d',
  719. '725f2665-1015-4563-9044-f4061accdf67',
  720. '739aa426-a359-4515-85ef-1efe605c0b73',
  721. '8dcde32c-3a77-4bf5-84a3-ec4d7a78413d',
  722. '4a396e8b-babb-47ee-b6ed-db2124d5c39d',
  723. '55f4594b-c13b-48b8-82f1-563751d48e9e',
  724. '3cc1bd57-bf4e-4933-ac6b-7cdb0e8e2dc1',
  725. '380511bf-2b15-4b90-b8c8-3464c2c6e18c',
  726. '12378c30-0c1d-4c84-8deb-5aaffaa2b45c',
  727. 'e247abc3-7083-4de5-a492-46e09e9bb341',
  728. 'ef826295-7a00-483d-945b-589c8fc0baf9',
  729. 'c1b056c5-0ebf-454a-bb56-3f6024e837d2',
  730. 'c513fe45-767c-4632-b6d3-9631c9bf8854',
  731. '9f7d087e-ba53-4167-9776-1e33a9a1cb61',
  732. 'b5f1a3f0-975f-441c-b6d0-3b8513b96d24',
  733. '92560ac8-a3a5-4aff-85e6-b7f72fc7e2fb',
  734. '898a7705-47f3-4f3b-a01e-1ec609ad4abf',
  735. '4c4349a0-ade4-4793-a435-15de7f3c299e',
  736. '473707f1-6f43-4611-adca-263604aa8e58',
  737. '88ee65ec-ec5c-4c5a-8539-8a8e931508ce',
  738. '4b12c255-5f44-4056-8ab6-d33721394ab2',
  739. '1f2f9ad3-e465-4152-afce-26715e3902af',
  740. 'bba7590c-735a-41c3-a501-ab4285fc36e8',
  741. '51c7426f-934f-4a18-bc1f-053e994969cc',
  742. '9ec15578-a78b-4f9d-ae8c-f15677d03d0a',
  743. '6fc632fe-5833-4c26-a079-70f9a3fa1957',
  744. '86a886f5-e540-4f57-abfd-cee4e3d328ab',
  745. '66e50efa-c3c4-4e3e-8892-5ebdec85a008',
  746. '2b66ee3b-e74a-446a-a92d-9cdc11a43123',
  747. '09533510-ec3a-4c45-8220-097a2a7e4237',
  748. 'be879d1f-1ccd-4e5f-9871-449a736a9279',
  749. '2371ba86-0598-44eb-99de-c73b7cca15db',
  750. '77f87528-e5c0-4ddf-80ea-43d383f5e58e',
  751. '9b7aa0c9-6393-4337-95cd-2bf0c57a662c',
  752. '93811e7f-fa3f-4487-9310-ef28ba3530f4',
  753. '43ecedc4-45fa-4ab7-b87b-357be07b19fa',
  754. 'a7fa4f17-9a9e-4d0b-bca7-2edfdcd75afb',
  755. '3682bc09-96ab-4d17-9010-b9fc31dc72bd',
  756. '04eff65e-3e19-4b57-b3ba-f1f63f52b8ba',
  757. '9eaea71a-97c8-456d-afc4-97d00e2e83bd',
  758. 'e3d846fd-c9e7-44b1-966d-ba74b4953f54',
  759. '2db6561b-3657-418a-ba18-b726a86d1fb1',
  760. '93b32d4b-a918-4940-bcef-00fbeceff525',
  761. '18e6f96a-c4d3-4cca-9248-f7c9099c6706',
  762. '3e1866ed-c9d0-415f-a080-ed1b34704110',
  763. 'd4ee5661-646b-4a58-b2b8-ad309666d64e',
  764. 'b678edb6-4717-423f-a8ac-6abc80eeab97',
  765. 'e8d68e11-d1e9-4bc7-8e22-e426f50f70a2',
  766. '8e96efbd-b990-4e2e-ad43-49e9dae73794',
  767. '72793b29-c939-4201-82b8-7ded1e6c6fe5',
  768. '59b5a6bc-ae2a-4157-b262-bf7a4858aace',
  769. 'e6b642ef-4239-4063-b471-da5b987b6aeb',
  770. 'f5ebf426-b4bc-4744-a2f3-a35a22c6c326',
  771. 'a7e80ecb-2a53-4879-a0f4-d313f78d3c01',
  772. 'cf32535a-b754-4cee-a51d-be4dc2220a2f',
  773. '521c66d6-00cc-4ec6-b391-0d9ce1995c42',
  774. '523b17d0-629f-44de-8f24-0c3915493fb0',
  775. '771b45c4-dde0-4d6a-ba69-6d8f537e4c1f',
  776. 'f9b374fd-1af4-4623-b117-c75fa4e7f4f8',
  777. '479f343e-51b7-49bd-8ebb-cb81af8ae7b0',
  778. 'cc992aae-2942-4836-9351-cedbd1cc4e61',
  779. '3f5d1192-4c56-43a6-9140-18043d6c41e5',
  780. 'dffad9b6-f3f2-4470-be45-94c81af04a02',
  781. '39289aa9-2506-4d04-866e-e6eec9b4d9db',
  782. '243299ec-6a98-43ac-b3db-272f5abbbd78',
  783. '9f715766-ef6a-479d-895d-945952a8ff6e',
  784. '2ff9bd86-8621-4f04-b560-abff5a202232',
  785. '75da24ed-8196-4eb1-8413-3916d7b271a3',
  786. '6adc96f3-c6e5-4a8d-a33f-5bbcbb92b296',
  787. '0b2dcfbc-d334-4032-b354-f6fa98a57d99',
  788. 'e2110a26-3af6-4c53-8b38-51ed4b415d48',
  789. '85e4c259-f531-43dd-a2b8-76cb750f8604',
  790. '1a6731a3-cc57-4463-84e1-bca0917c2399',
  791. 'd574dac8-4440-48f0-af37-b982db545ea3',
  792. '753ca661-d930-4f33-bce3-5385c310744f',
  793. 'e70800f3-836b-43e9-aa8c-c5e789d7054e',
  794. '32a94a0c-c14c-4208-8bd1-0d84c69d690e',
  795. 'f5d242b3-db25-4877-8a63-4d4dcf8f8f2c',
  796. '87399fcb-34fb-494b-b74f-02979a665dc0',
  797. '85796371-1079-4fff-947d-671720377e72',
  798. '40f04a01-e373-430a-a1f5-cbb8fbcff4cb',
  799. '6e6a3d09-c65d-4996-bd96-035f5d19e634',
  800. 'd340ea8f-e869-46d5-8813-5cce7991edea',
  801. '8a72592b-09fb-4910-b4e9-c76ef039b44f',
  802. '740b8b24-c7f5-4df5-a13a-92a1c37619bc',
  803. 'c19ef79f-d3f3-4125-8e1a-83cee110e03b',
  804. '1894992c-2575-4949-971d-c84669fcfd06',
  805. '4d51ace2-9f18-4f01-be7b-1ab4694e62dd',
  806. 'c1564967-890f-49e2-983a-933df4cbf8d0',
  807. 'aff088da-91e6-400a-ab84-c6cf300b361f',
  808. 'b0557e5e-41c5-4273-b793-dcb8a0613e6f',
  809. 'd0317e30-bcc4-4b03-9417-4dba3a216105',
  810. '86a28ef8-f3fc-44ef-942b-a9a658bb0731',
  811. '53623415-70e8-44f6-9ea6-bd709e40984c',
  812. '9ee23eee-850c-4cb0-8147-829ae0502705',
  813. 'd6fbfc1e-6093-4e70-8432-453246c80eb3',
  814. 'ac0e96dd-ec15-4b39-834d-1000ac3aa4c4',
  815. '1e8c9744-8054-405b-997c-de13e58967a4',
  816. 'c87c282c-6a83-40d1-86bc-af3045c0c41a',
  817. '4c221226-f490-4657-bd98-cf24bba48d7e',
  818. 'fd218bdd-7c18-41d6-a592-59a4c3ee98fe',
  819. '0c916db0-f7fa-4abc-a548-ca81cb416e59',
  820. '9f3c9615-3066-45d8-99a9-eacc8f6d692d',
  821. '6ed5074e-c7df-49f1-84c8-bb6276db9d1d',
  822. 'c2eb2c78-60d3-4616-9215-5ca810c58e4d',
  823. '4aef197d-5c62-4bce-aab2-804c87db5b28',
  824. '3231a06f-118a-437f-b863-4ffcba56d03a',
  825. 'a827a795-f86e-46eb-8369-f63b061d87d9',
  826. 'd4fd8c14-81d1-41b3-b652-f1dfb107d0d6',
  827. 'a0f2b207-0ef7-4ca4-b595-12f46b4b8434',
  828. '115f8e21-ebdb-4241-9c34-91fbef1b6fb9',
  829. '34c8923a-0230-448a-9d06-a8f2922520a3',
  830. '04803687-4689-45a6-b19e-4d3a39ccc348',
  831. '8bb657c9-7638-4ab9-af92-a4370d53960e',
  832. '1e766445-9971-4358-86be-fba295460866',
  833. '367c0575-b150-44eb-b447-5468d4d833fe',
  834. '2a379010-1f57-43f7-8f99-1f254ad93c26',
  835. '496adcc6-2897-4f16-9e9b-75fbcfd313a0',
  836. 'c32a4e86-637f-4c68-8824-2d4370eea5ee',
  837. 'b03b9f85-6d51-4c9c-a354-22bd3aa67462',
  838. '829a1242-f1e0-4154-aacf-362c021172f2',
  839. '4a451d51-b96c-4740-9018-7d22bbd842cf',
  840. '497a3b9a-55da-4991-af53-657c04edd0b3',
  841. 'b89b915f-f4ea-44f6-ae3a-e45af1942022',
  842. '781c4777-a869-4857-b052-71cbecbf6e35',
  843. '16a1d9aa-4bba-4c6f-86e5-7f7a281e7cd2',
  844. 'a5125445-cd2c-44b1-af19-addd25b8eeef',
  845. '81f574b9-9da2-43ae-ac6c-54ceb637c1fa',
  846. '1d469b5a-386c-4ace-9477-826c2d9d2b5d',
  847. '4fb0c252-5df1-44f9-a6e4-40078740a4e8',
  848. '1d7574e8-cf7c-460f-aad9-b4eec908121c',
  849. 'b0d23d24-a66f-4fb7-badc-980bebe0118d',
  850. 'e9570402-e4db-4a7c-9d5c-c5f95ad8ed0a',
  851. 'b08a57bc-6f1a-491c-a126-490ad5c8f90c',
  852. '583f3908-5caf-4703-84c6-e32cbbafca1e',
  853. '271cf872-cc61-493d-a595-be644bb2e098',
  854. 'a031cf56-0aa1-40c1-a325-14f6f1204cad',
  855. '3f492d1f-d95d-4947-8944-1e47fbe6abb4',
  856. '44d282b7-413f-4f1a-b5cf-5b9b81acbb6a',
  857. 'cef3a415-dc3f-4143-b905-5b1bac1b10c9',
  858. '37fe497b-1ba6-46e7-a9b9-fd70993b9753',
  859. 'c0db0c30-590c-42bd-bac7-d065a05843cd',
  860. '19532426-9ee6-4cc0-8d7b-7c5753b95b64',
  861. '7421dcb4-14d3-4656-9257-a2b287ff41a8',
  862. 'bd5805f7-a7eb-4189-8e48-9b3978d22362',
  863. '012861ec-8bbb-42e2-9e39-349a5b172c21',
  864. '731daff9-ccf2-48d3-88bc-ff02ec7ff2f9',
  865. '5b47d6c3-df81-4456-a165-4af6ee34c375',
  866. '2129126a-838f-4e3d-a8a4-1bf9e8d70ce8',
  867. 'acb84287-1cf7-4aa5-8892-e92beb6f6871',
  868. 'b2d337e4-16b4-459d-9d7f-922458e2671c',
  869. 'c63b9cd7-bce4-4c80-91c2-c305916d3d22',
  870. '1a7d052b-97b6-40ab-9b45-3e163710ea10',
  871. 'bd096e5e-0dc3-4b2e-9e4a-ffc3ac2a8e8b',
  872. '1afbab3e-193c-408c-b024-3365730d1698',
  873. '6e268ebe-aa65-4fa0-8fc1-877d0688cf8d',
  874. '89675ae3-9773-4b37-bc69-6a926f608b0e',
  875. 'd96a0716-89e1-4b5b-b02a-0cb438bd4933',
  876. '693e024a-1b71-4c9e-868e-ad9524728988',
  877. '5fb1ad4b-7a79-4a55-b627-3d1354a22754',
  878. 'c050b6d6-5f1a-4f3f-9385-521d9f992f11',
  879. '62051b3d-1a64-4509-914c-a382f573c050',
  880. '8b6c6a22-3a4c-48f4-bba4-57db1af2ec2e',
  881. 'ca5d3896-35ad-4848-ad2a-beb04263999d',
  882. '1bac6904-2f36-45f5-9e8e-894e28a5674d',
  883. '89f1a5f6-3c29-4338-8a00-5645dbaa80ad',
  884. 'def9d072-fee5-44f6-bc18-5b2750d4efc5',
  885. '032e2e84-6154-49ee-8d4d-e3b3b631595b',
  886. '6cb4e7ba-9be8-4c8a-bf4a-437faf96c084',
  887. 'd6df2ed5-8963-42c0-8832-537a210e900e',
  888. 'ec647fea-a650-4b18-b267-3f8d9d104c23',
  889. '10374436-b76b-4d73-853e-abe12b8f0079',
  890. '8b87190e-3fd1-40d3-9a7f-efb986cd7fa5',
  891. '30803959-1b88-4b8a-8716-d74e58f2eacd',
  892. 'b7c69c8d-b4c0-4523-ac73-f9629d2b5c37',
  893. 'da21dd7d-fe43-474f-bcd0-e2819b71ab40',
  894. 'ae97438f-afc8-4f01-90da-da5fbbc7b759',
  895. '95920cea-040e-40a0-a9fa-ea7e48945e5e',
  896. 'bf0ec2c2-b1b5-41a4-990b-ebd32e64bcc5',
  897. '06add3e9-8566-44b0-8962-6f1377410b48',
  898. '1a56021a-b4e5-45e0-83e5-7ec707097271',
  899. 'd35c54ea-3985-484f-9a3a-abc4be8fc774',
  900. 'a7c3bd26-ac43-4a61-99fe-428ea141a826',
  901. '414a46cb-4e88-4217-adfd-395f3f4cb12c',
  902. '241729ee-cfe7-4ee2-868e-3f617fd62bba',
  903. 'c05c28db-8b03-4d0c-8a37-c0e36c6fd0e8',
  904. '5b72fe37-3bc6-4563-9a1e-bfd62b692980',
  905. '73609b0e-1bc7-4c64-a39e-df52a34a5325',
  906. '477bba0c-d64f-4543-90eb-481183874bf8',
  907. 'd2d5be63-6e49-46d5-ae96-3b106b907902',
  908. '9091e31c-28c6-4a31-9958-36d0875ef8d7',
  909. '4fedd41a-d3d2-475d-8804-8c716ac4e160',
  910. '5d322e5c-ad86-42b2-a20d-1fa0e3279361',
  911. '99297e99-3b10-4353-a691-02492f2b88d1',
  912. '5b1206de-1b99-4b96-8e98-5c85ca630cea',
  913. '65d501e8-4663-4ae8-a07e-59b30b75a645',
  914. 'b53311e3-5276-45d6-87a1-36bf28b653be',
  915. '6bd75463-1dec-4001-ab24-cd2e07986759',
  916. '9b3201a9-ce44-41a7-8ad5-6769f726c2d0',
  917. '0acf8a5d-0feb-4497-9a0a-e95f86138157',
  918. '522597e8-bada-4c5b-bdf2-06af764a4bfe',
  919. '1fca91fb-3e03-438e-8f1b-a9b77b14634c',
  920. 'c8bd6ef8-ff2e-40c5-8f15-973caea0ed58',
  921. 'ba318882-7eeb-42a0-bfcb-09ac71fc0046',
  922. '0e1d09bd-f176-4e21-9f55-b821703a7b24',
  923. '3f58f289-a206-4fbd-93c6-0752d3d0a250',
  924. 'fd23121d-959d-443c-ac22-4cf7cac3751c',
  925. 'd3b4384a-290e-4cb0-bfda-b34097d5ca72',
  926. '2d7b5467-0e74-40ae-ab21-bf29ee3fe02c',
  927. 'd3db6faa-4b07-460a-bcbd-48dcc109fbc4',
  928. 'e5d14fe7-a5a0-4610-b1b7-87c9d936c7ff',
  929. 'f386b6f5-1fd2-4a2e-8ec0-6762ddd5c477',
  930. '60c09883-dff1-49ee-bafb-1991aab238aa',
  931. '6664e420-91ad-4c89-9955-313b163f722e',
  932. 'b81724c3-c045-436b-9d55-f528918de742',
  933. '5de09e10-e4bd-4df2-8628-9e432b17ec65',
  934. 'af93606e-5dbc-4401-99e6-adea66903418',
  935. 'fe7998e5-0a31-45a8-aab0-1867092d855c',
  936. 'd64bdffe-8388-4a9c-a3f9-bbd1b75ea224',
  937. 'c8845227-73ea-45fe-920c-be3e166b04c3',
  938. '6087c06a-10fc-4c92-adb3-95f85423fe2e',
  939. '6c64f697-21cf-4d58-8810-d0306e0c5dc4',
  940. 'bc2ee64e-cb01-4101-9d2d-fd37f31fd881',
  941. 'c076b996-1f81-4f4a-8c04-a1a69348863f',
  942. 'f2fab9c5-2a57-4f0a-8b48-000fc08eec98',
  943. 'b496b620-713e-4312-8d80-4f89d10187de',
  944. '6995deff-b9e8-479b-84fc-d981efab4d3b',
  945. 'cd7e8c81-231f-42ab-a30d-7665e9097a71',
  946. '38452e41-1ec3-40ca-ac3a-2579e47e5f16',
  947. '16e904e2-b77b-4723-86ee-ba85a9d3762f',
  948. '9e5e308a-c291-4feb-a225-336f0f949489',
  949. '8391694a-dccb-48eb-8d3b-56401e5fb030',
  950. 'f210dd0a-e288-477a-9a16-d622cc92a818',
  951. '17908451-473c-4fd8-848c-23ef7846fa43',
  952. 'cea1ec2e-02e6-4777-b931-b2042b3f1230',
  953. '70fd95b8-be8c-4545-a46f-6c050449a822',
  954. '057d4f31-3338-4d7b-869c-98fcb114153d',
  955. '8d032ab5-c7db-4ceb-9a37-f55f8a59416c',
  956. '5e8a8ffe-73ac-4a29-9bcc-a03c06b25b2e',
  957. '55fd11e2-047f-4acf-9533-22023684dd58',
  958. '45a4b0c1-dbbf-423e-b287-d44c71089f69',
  959. 'c52cd0d3-4385-4efb-8f33-f947564a70cb',
  960. '07d593c2-9ad7-4ae5-b471-b3e2622c940b',
  961. 'adf77ae2-63f7-4732-82d0-29d434f83445',
  962. 'bdee46ba-fab6-485d-ad89-fda5578859cc',
  963. 'f8b9bccc-1c4f-433d-9917-f4ad007f7105',
  964. '7d2bd01e-5435-4dbd-8e9b-897e777691f6',
  965. '56cacfd9-aeef-4477-abb9-2a22e0a92ae7',
  966. '891c7363-60c7-4aa5-846e-e7e3913e37d4',
  967. '376c26d3-8ebc-4c10-a5c1-aef9606318a8',
  968. '3efc8c68-3cee-4bc6-bdcd-ffc4c1a3437b',
  969. '1a7e5fda-eb4c-4f62-ad2d-b3e04e0e725a',
  970. 'dd4b0cd7-73d4-46fa-bf19-12e35f64be43',
  971. 'ccf206a1-fcc8-4552-b12f-ebed670cff73',
  972. 'c275d71f-cdb3-443c-82ab-821dd80500ea',
  973. 'e269c78b-2b0c-4fd1-bc0f-2ff671151030',
  974. '41e4371e-7495-4008-9951-7b3ab843429e',
  975. 'c54ac4b5-9267-4087-b724-6b0d44713162',
  976. 'e43fb790-aa3f-4209-838d-d830a9c5fd53',
  977. '982f3d88-bfe1-46c8-ac95-7adbd06a98f1',
  978. '8ded07a1-1dda-4dea-8e0d-05475693642c',
  979. 'edb7d6b2-4d86-486f-b4b6-bac71fe6c460',
  980. 'c3416899-550b-4e1a-93f5-690dcf67cd6b',
  981. '89a915cf-aee4-4472-91e6-7f33d5ef490b',
  982. 'c3587e4c-020a-4bef-8ad5-bcbb9a7ea485',
  983. '91e8d5b4-8b73-470b-b900-7cd8f5508e82'
  984. )";
  985. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).GetItemQueryIteratorSql<StudentArtResult>(sql))
  986. {
  987. art_idNames.Add(item);
  988. }
  989. List<dynamic> unfinish = new List<dynamic>();
  990. ConcurrentDictionary<string, int> schoolFinish = new ConcurrentDictionary<string, int>();
  991. ConcurrentDictionary<string, int> schoolUnFinish = new ConcurrentDictionary<string, int>();
  992. List<Class> classes = new List<Class>();
  993. foreach (var z in art_idNames)
  994. {
  995. var data = z.results.Where(x => (x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_21") && x.score == -1)
  996. || (x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_21") && x.score == -1)
  997. || (x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_22") && x.score == -1)
  998. || (x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_22") && x.files.IsEmpty())
  999. );
  1000. if (data.Any())
  1001. {
  1002. var p21 = z.results.FindAll(x => x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_21"))?.First();
  1003. var p22 = z.results.FindAll(x => x.subjectId.Equals("subject_painting") && x.quotaId.Equals("quota_22"))?.First();
  1004. int p22source = 0, p21source = 0, m21source = 0, m22source = 0;
  1005. if (p21.score > -1)
  1006. {
  1007. p21source = 1;
  1008. }
  1009. if (p22.files.IsNotEmpty())
  1010. {
  1011. p22source = p22.files.Count;
  1012. }
  1013. var m21 = z.results.FindAll(x => x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_21"))?.First();
  1014. if (m21.score > -1)
  1015. {
  1016. m21source = 1;
  1017. }
  1018. var m22 = z.results.FindAll(x => x.subjectId.Equals("subject_music") && x.quotaId.Equals("quota_22"))?.First();
  1019. if (m22.score > -1)
  1020. {
  1021. m22source = 1;
  1022. }
  1023. string className = "";
  1024. string periodName = "";
  1025. string schoolName = "";
  1026. School school = schools.Find(a => a.id.Equals(z.school));
  1027. schoolName = school?.name;
  1028. if (!string.IsNullOrWhiteSpace(z.classIds?.First()))
  1029. {
  1030. var clasz = classes.Find(x => x.id.Equals(z.classIds?.First()));
  1031. if (clasz == null)
  1032. {
  1033. clasz = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).ReadItemAsync<Class>(z.classIds.First(), new PartitionKey($"Class-{z.school}"));
  1034. classes.Add(clasz);
  1035. }
  1036. className = clasz?.name;
  1037. var period = school?.period?.Where(m => m.id.Equals(clasz.periodId));
  1038. if (period.Any())
  1039. {
  1040. periodName = period.First().name + "-" + period.First().periodType;
  1041. }
  1042. }
  1043. unfinish.Add(new { z.school, schoolName = schoolName, z.studentId, z.studentName, z.artId, periodName, classname = className, p21source, p22source, m21source, m22source, taskId = m22?.taskId });
  1044. if (schoolUnFinish.ContainsKey(schoolName))
  1045. {
  1046. schoolUnFinish[schoolName]++;
  1047. }
  1048. else { schoolUnFinish.TryAdd(schoolName, 1); }
  1049. }
  1050. else
  1051. {
  1052. School school = schools.Find(a => a.id.Equals(z.school));
  1053. string schoolName = school?.name;
  1054. if (schoolFinish.ContainsKey(schoolName))
  1055. {
  1056. schoolFinish[schoolName]++;
  1057. }
  1058. else { schoolFinish.TryAdd(schoolName, 1); }
  1059. }
  1060. }
  1061. return Ok(new { unfinish, schoolFinish , schoolUnFinish });
  1062. }
  1063. [ProducesDefaultResponseType]
  1064. [HttpPost("check-ems")]
  1065. public async Task<IActionResult> CheckPjx(JsonElement json)
  1066. {
  1067. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  1068. int itemId = 0;
  1069. if (json.TryGetProperty("itemId", out JsonElement _itemId)) {
  1070. itemId= _itemId.GetInt32();
  1071. }
  1072. List< ScTeacher > teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "ProjectItemID", itemId } });
  1073. List<dynamic> unbind = new List<dynamic>();
  1074. List<dynamic> unupload_rzcl = new List<dynamic>();
  1075. List<dynamic> uploads_rzcl = new List<dynamic>();
  1076. List<dynamic> unupload_video = new List<dynamic>();
  1077. List<dynamic> uploads_video = new List<dynamic>();
  1078. foreach (var teacher in teachers)
  1079. {
  1080. if (!string.IsNullOrWhiteSpace(teacher.schoolCode) && !string.IsNullOrWhiteSpace(teacher.tmdid))
  1081. {
  1082. int upcont = 0;
  1083. string sql = "select value c from c where c.currency=1";
  1084. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1085. .GetItemQueryIteratorSql<AbilitySub>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilitySub-{teacher.schoolCode}-{teacher.tmdid}") }))
  1086. {
  1087. if (item.uploads.IsNotEmpty())
  1088. {
  1089. upcont++;
  1090. uploads_rzcl.Add(new { teacher.TeacherName,teacher.SchoolName,teacher.PXID,time= DateTimeOffset.FromUnixTimeMilliseconds(item.uploads.OrderByDescending(m => m.time).FirstOrDefault().time).ToString("yyyy-MM-dd HH:mm:ss"), teacher?.tmdid });
  1091. }
  1092. }
  1093. if(upcont<3)
  1094. {
  1095. unupload_rzcl.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID ,teacher?.tmdid});
  1096. }
  1097. string sql_video =$"select value c from c where c.id='{teacher.tmdid}'";
  1098. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1099. .GetItemQueryIteratorSql<ClassVideo>(queryText: sql_video, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"ClassVideo-{teacher.schoolCode}") }))
  1100. {
  1101. if (item.files.IsNotEmpty())
  1102. {
  1103. uploads_video.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID, time = DateTimeOffset.FromUnixTimeMilliseconds(item.files.OrderByDescending(m => m.time).FirstOrDefault().time).ToString("yyyy-MM-dd HH:mm:ss"), teacher?.tmdid });
  1104. }
  1105. else
  1106. {
  1107. unupload_video.Add(new { teacher.TeacherName, teacher.SchoolName, teacher.PXID, teacher?.tmdid });
  1108. }
  1109. }
  1110. }
  1111. else {
  1112. unbind.Add(new { teacher.TeacherName,teacher.SchoolName,teacher.PXID});
  1113. }
  1114. }
  1115. Dictionary<string, object> dict = new Dictionary<string, object>();
  1116. var tchs= teachers.GroupBy(z => z.areaId).Select(b => new { areaId = b.Key, schools = b.Select(v=>v.schoolCode).ToHashSet(), pushTeachers = b.Where(c=>!string.IsNullOrWhiteSpace(c.tmdid)).Select(d=>d.tmdid)});
  1117. return Ok(new { unbind , unupload_rzcl, uploads_rzcl, uploads_video, unupload_video , tchs });
  1118. }
  1119. [ProducesDefaultResponseType]
  1120. [HttpPost("sendmsg")]
  1121. public async Task<IActionResult> Sendmsg(JsonElement json)
  1122. {
  1123. byte[] bytes = Encoding.UTF8.GetBytes(json.GetRawText());
  1124. var memoryStream = new MemoryStream(bytes);
  1125. ResponseMessage res = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).CreateItemStreamAsync(memoryStream, new PartitionKey("Base12"));
  1126. if (res.StatusCode == HttpStatusCode.Created)
  1127. {
  1128. return Ok(201);
  1129. }
  1130. //var messageBlobPDF = new ServiceBusMessage(new { userType = "tmdid", bizType = "OfflineRecord" }.ToJsonString());
  1131. //await _serviceBus.GetServiceBusClient().SendMessageAsync("screenpdf", messageBlobPDF);
  1132. return Ok();
  1133. }
  1134. [ProducesDefaultResponseType]
  1135. [HttpPost("get-subTime")]
  1136. public async Task<IActionResult> GetSubTime(JsonElement request) {
  1137. if (!request.TryGetProperty("ids", out JsonElement id)) return BadRequest();
  1138. List<string> ids = id.ToObject<List<string>>();
  1139. var queryClass = $"select c.time from c ";
  1140. var client = _azureCosmos.GetCosmosClient();
  1141. List<(string td, long tt)> ht = new();
  1142. foreach (string tmdId in ids) {
  1143. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryStreamIteratorSql(queryText: queryClass,
  1144. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"HomeworkRecord-{tmdId}") }))
  1145. {
  1146. using var json = await JsonDocument.ParseAsync(item.Content);
  1147. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  1148. {
  1149. var accounts = json.RootElement.GetProperty("Documents").EnumerateArray();
  1150. while (accounts.MoveNext())
  1151. {
  1152. JsonElement account = accounts.Current;
  1153. account.TryGetProperty("time", out JsonElement time);
  1154. ht.Add((tmdId,time.GetInt64()));
  1155. }
  1156. }
  1157. }
  1158. }
  1159. var home = ht.Select(x => new
  1160. {
  1161. id = x.td,
  1162. time = DateTimeOffset.FromUnixTimeMilliseconds(x.tt).ToString("yyyy-MM-dd HH:mm")
  1163. //time = DateTimeHelper.FromUnixTimestampOffSet(x.tt,8).ToString("yyyy-MM-dd HH:mm")
  1164. });
  1165. return Ok(home);
  1166. }
  1167. [ProducesDefaultResponseType]
  1168. [HttpPost("get-semester")]
  1169. public async Task<IActionResult> GetSemester(JsonElement json)
  1170. {
  1171. List<Semester> semesterList = new List<Semester>();
  1172. semesterList.Add(
  1173. new Semester
  1174. {
  1175. id = Guid.NewGuid().ToString(),
  1176. name = "第二学期",
  1177. start = 0,
  1178. month = 3,
  1179. day = 1
  1180. });
  1181. semesterList.Add(
  1182. new Semester
  1183. {
  1184. id = Guid.NewGuid().ToString(),
  1185. name = "第一学期",
  1186. start = 1,
  1187. month = 9,
  1188. day = 1
  1189. });
  1190. //semesterList.Add(
  1191. // new Semester
  1192. // {
  1193. // id = "q",
  1194. // name = "第四学期",
  1195. // start = 0,
  1196. // month = 7,
  1197. // day = 1
  1198. // });
  1199. //semesterList.Add(
  1200. // new Semester
  1201. // {
  1202. // id = "q",
  1203. // name = "第三学期",
  1204. // start = 0,
  1205. // month = 4,
  1206. // day = 1
  1207. // });
  1208. semesterList = SortSemester(semesterList);
  1209. return Ok(semesterList);
  1210. }
  1211. private List<Semester> SortSemester(List<Semester> semesterList)
  1212. {
  1213. int Year = DateTimeOffset.UtcNow.Year;
  1214. List<KeyValuePair<int, Semester>> pairs = new List<KeyValuePair<int, Semester>>();
  1215. semesterList.ForEach(se => {
  1216. string sm = se.month >= 10 ? $"{se.month}" : $"0{se.month}";
  1217. string sd = se.day >= 10 ? $"{se.day}" : $"0{se.day}";
  1218. int order = int.Parse($"{Year}{sm}{sd}");
  1219. pairs.Add(new KeyValuePair<int, Semester>(order, se));
  1220. });
  1221. var orderPairs = pairs.OrderBy(z => z.Key);
  1222. semesterList = orderPairs.Select(z => z.Value).ToList();
  1223. int startIndex = semesterList.FindIndex(z => z.start == 1);
  1224. if (startIndex == -1)
  1225. {
  1226. //未设置学期的情况默认9月份开始的。
  1227. startIndex = semesterList.FindIndex(z => z.month == 9);
  1228. //如果还未找到,就以排序结果为准
  1229. if (startIndex == -1)
  1230. {
  1231. startIndex = 0;
  1232. }
  1233. }
  1234. if (startIndex > 0)
  1235. {
  1236. List<Semester> before = semesterList.Take(startIndex).ToList();
  1237. List<Semester> after = semesterList.Skip(startIndex).ToList();
  1238. semesterList = new List<Semester>();
  1239. semesterList.AddRange(after);
  1240. semesterList.AddRange(before);
  1241. return semesterList;
  1242. }
  1243. else
  1244. {
  1245. return semesterList;
  1246. }
  1247. }
  1248. /*
  1249. [
  1250. {"method":"台北市","params":{"CountryId":"TW","CityId":"30"}},1
  1251. {"method":"新北市","params":{"CountryId":"TW","CityId":"01"}},1
  1252. {"method":"桃园市","params":{"CountryId":"TW","CityId":"03"}},1
  1253. {"method":"台中市","params":{"CountryId":"TW","CityId":"66"}},1
  1254. {"method":"台南市","params":{"CountryId":"TW","CityId":"67"}},1
  1255. {"method":"高雄市","params":{"CountryId":"TW","CityId":"64"}},1
  1256. {"method":"基隆市","params":{"CountryId":"TW","CityId":"17"}},1
  1257. {"method":"新竹市","params":{"CountryId":"TW","CityId":"18"}},1
  1258. {"method":"嘉义市","params":{"CountryId":"TW","CityId":"20"}},1
  1259. {"method":"新竹县","params":{"CountryId":"TW","CityId":"04"}},1
  1260. {"method":"苗栗县","params":{"CountryId":"TW","CityId":"05"}},1
  1261. {"method":"彰化县","params":{"CountryId":"TW","CityId":"07"}},1
  1262. {"method":"南投县","params":{"CountryId":"TW","CityId":"08"}},1
  1263. {"method":"云林县","params":{"CountryId":"TW","CityId":"09"}},1
  1264. {"method":"嘉义县","params":{"CountryId":"TW","CityId":"10"}},1
  1265. {"method":"屏东县","params":{"CountryId":"TW","CityId":"13"}},1
  1266. {"method":"宜兰县","params":{"CountryId":"TW","CityId":"02"}},1
  1267. {"method":"花莲县","params":{"CountryId":"TW","CityId":"15"}},1
  1268. {"method":"台东县","params":{"CountryId":"TW","CityId":"14"}},1
  1269. {"method":"澎湖县","params":{"CountryId":"TW","CityId":"16"}},1
  1270. {"method":"金门县","params":{"CountryId":"TW","CityId":"71"}},
  1271. {"method":"连江县","params":{"CountryId":"TW","CityId":"72"}}
  1272. ]
  1273. */
  1274. /// <summary>
  1275. /// 测试blob多线程写入同一个文件
  1276. /// </summary>
  1277. /// <returns></returns>
  1278. [ProducesDefaultResponseType]
  1279. [HttpPost("get-schools")]
  1280. public async Task<IActionResult> GetSchools(JsonElement json)
  1281. {
  1282. string msg = "{\"standard\":\"standard3\",\"tmdids\":[\"1635136038\"],\"school\":\"pbjyey\",\"update\":[\"TeacherAbility\"],\"statistics\":0}";
  1283. try
  1284. {
  1285. TeacherTrainChange change = msg.ToObject<TeacherTrainChange>();
  1286. var client = _azureCosmos.GetCosmosClient();
  1287. string insql = $"where c.id in ({string.Join(",", change.tmdids.Select(x => $"'{x}'"))})";
  1288. string selsql = $"select value(c) from c {insql} ";
  1289. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  1290. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIteratorSql<TeacherTrain>(queryText: selsql,
  1291. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"TeacherTrain-{change.school}") }))
  1292. {
  1293. teacherTrains.Add(item);
  1294. }
  1295. if (change.statistics != 1)
  1296. {
  1297. List<Task<ItemResponse<TeacherTrain>>> task = new List<Task<ItemResponse<TeacherTrain>>>();
  1298. teacherTrains.ForEach(x =>
  1299. {
  1300. x.update.UnionWith(change.update);
  1301. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<TeacherTrain>(x, x.id, new PartitionKey($"TeacherTrain-{change.school}")));
  1302. });
  1303. await task.TaskPage(5);
  1304. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  1305. if (unchange != null)
  1306. {
  1307. task.Clear();
  1308. unchange.ToList().ForEach(x =>
  1309. {
  1310. TeacherTrain teacherTrain = new TeacherTrain
  1311. {
  1312. pk = "TeacherTrain",
  1313. id = x,
  1314. code = $"TeacherTrain-{change.school}",
  1315. tmdid = x,
  1316. school = change.school,
  1317. update = new HashSet<string> { StatisticsService.TeacherAbility,
  1318. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  1319. };
  1320. teacherTrain.update.UnionWith(change.update);
  1321. task.Add(client.GetContainer(Constant.TEAMModelOS, "Teacher").UpsertItemAsync<TeacherTrain>(teacherTrain, new PartitionKey($"TeacherTrain-{change.school}")));
  1322. });
  1323. await task.TaskPage(1);
  1324. }
  1325. }
  1326. else
  1327. {
  1328. Area area = null;
  1329. string sql = $"select value(c) from c where c.standard='{change.standard}'";
  1330. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIteratorSql<Area>(queryText: sql,
  1331. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base-Area") }))
  1332. {
  1333. area = item;
  1334. }
  1335. AreaSetting setting = null;
  1336. if (area != null)
  1337. {
  1338. try
  1339. {
  1340. //优先找校级
  1341. setting = await client.GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<AreaSetting>(change.school, new PartitionKey("AreaSetting"));
  1342. }
  1343. catch (CosmosException)
  1344. {
  1345. try
  1346. {
  1347. setting = await client.GetContainer(Constant.TEAMModelOS, "Normal").ReadItemAsync<AreaSetting>(area.id, new PartitionKey("AreaSetting"));
  1348. }
  1349. catch (CosmosException)
  1350. {
  1351. setting = null;
  1352. }
  1353. }
  1354. }
  1355. if (setting == null)
  1356. {
  1357. setting = new AreaSetting
  1358. {
  1359. allTime = 50,
  1360. classTime = 5,
  1361. submitTime = 15,
  1362. onlineTime = 20,
  1363. offlineTime = 10,
  1364. lessonMinutes = 45,
  1365. };
  1366. }
  1367. List<Task<TeacherTrain>> task = new List<Task<TeacherTrain>>();
  1368. teacherTrains.ForEach(x =>
  1369. {
  1370. x.update.UnionWith(change.update);
  1371. task.Add(StatisticsService.StatisticsTeacher(x, setting, area, client, null));
  1372. });
  1373. await task.TaskPage(1);
  1374. var unchange = change.tmdids.Except(teacherTrains.Select(x => x.id));
  1375. if (unchange != null)
  1376. {
  1377. task.Clear();
  1378. unchange.ToList().ForEach(x =>
  1379. {
  1380. task.Add(StatisticsService.StatisticsTeacher(new TeacherTrain
  1381. {
  1382. pk = "TeacherTrain",
  1383. id = x,
  1384. code = $"TeacherTrain-{change.school}",
  1385. tmdid = x,
  1386. school = change.school,
  1387. update = new HashSet<string> { StatisticsService.TeacherAbility,
  1388. StatisticsService.TeacherClass, StatisticsService.OfflineRecord }
  1389. }, setting, area, client, null));
  1390. });
  1391. await task.TaskPage(1);
  1392. }
  1393. }
  1394. }
  1395. catch (CosmosException ex)
  1396. {
  1397. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\nCosmosException{ex.StatusCode}", GroupNames.醍摩豆服務運維群組);
  1398. }
  1399. catch (Exception ex)
  1400. {
  1401. await _dingDing.SendBotMsg($"{Environment.GetEnvironmentVariable("Option:Location")}-研修数据变更,重新统计-TeacherTrainChange\n{msg}\n{ex.Message}\n{ex.StackTrace}\n", GroupNames.醍摩豆服務運維群組);
  1402. }
  1403. /*
  1404. string path = $"{_environment.ContentRootPath}/JsonFile/Core/city.json";
  1405. StreamReader streamReader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.UTF8);
  1406. StringBuilder stringBuilder = new StringBuilder();
  1407. string text;
  1408. while ((text = streamReader.ReadLine()) != null)
  1409. {
  1410. stringBuilder.Append(text.ToString());
  1411. }
  1412. streamReader.Close();
  1413. string input = stringBuilder.ToString();
  1414. List<string> region = new List<string>() {
  1415. "110000", "110100", "110200",
  1416. "120000", "120100", "120200",
  1417. "310000", "310100", "310200",
  1418. "500000", "500100", "810100",
  1419. "810200", "810300", "820100",
  1420. "820200", "820300"
  1421. };
  1422. List<string> cityids = new List<string>() {
  1423. "30","01","03","66","67","64","17","18","20","04","05","07","08","09","10","13","02","15","14","16","71","72"
  1424. };
  1425. Dictionary<string, List<CodeName>> regions = input.ToObject<Dictionary<string, List<CodeName>>>();
  1426. List<List<string>> datas = new List<List<string>>() { region };
  1427. foreach (var r in regions)
  1428. {
  1429. if (!region.Contains(r.Key) && !r.Key.StartsWith("71"))
  1430. {
  1431. datas.Add(r.Value.Select(x => x.code).ToList());
  1432. }
  1433. }
  1434. List<Task<List<SchoolInfo>>> tasks = new List<Task<List<SchoolInfo>>>();
  1435. //datas.ForEach(x =>
  1436. //{
  1437. // tasks.Add(GetSchoolAsync(x));
  1438. //});
  1439. List<SchoolInfo> schoolInfos = new List<SchoolInfo>();
  1440. //var schools = await Task.WhenAll(tasks);
  1441. //var schools =await GetSchoolAsync(cityids);
  1442. // schoolInfos.AddRange(schools);
  1443. //foreach (var schs in schools)
  1444. //{
  1445. // schoolInfos.AddRange(schs);
  1446. //}
  1447. List<string> nodatas = new List<string>();
  1448. foreach (var data in datas) {
  1449. (List<SchoolInfo> schoolIn, List<string> nodata) = await GetSchoolAsync(data);
  1450. schoolInfos.AddRange(schoolIn);
  1451. nodatas.AddRange(nodata);
  1452. }
  1453. await _dingDing.SendBotMsg($"os,test,{nodatas.ToJsonString()}", GroupNames.醍摩豆服務運維群組);
  1454. return Ok(schoolInfos);
  1455. */
  1456. return Ok();
  1457. }
  1458. public async Task<(List<SchoolInfo> schoolInfos, List<string> nodata)> GetSchoolAsync(List<string> regions)
  1459. {
  1460. List<SchoolInfo> schools = new List<SchoolInfo>();
  1461. List<string> nodata = new List<string>();
  1462. foreach (var region in regions)
  1463. {
  1464. Dictionary<string, object> data = new Dictionary<string, object>();
  1465. data.Add("method", "api/School/getSchool");
  1466. data.Add("params", new { CountryId = "CN", CityId = region });
  1467. HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("https://contest.teammodel.cn/api/School/getSchool", data);
  1468. if (responseMessage.StatusCode == HttpStatusCode.OK)
  1469. {
  1470. string Content = await responseMessage.Content.ReadAsStringAsync();
  1471. try
  1472. {
  1473. Content.ToObject<JsonElement>().TryGetProperty("result", out JsonElement content);
  1474. if (content.ValueKind.Equals(JsonValueKind.Object) && content.TryGetProperty("data", out JsonElement _data))
  1475. {
  1476. if (_data.ValueKind.Equals(JsonValueKind.Array))
  1477. {
  1478. List<SchoolInfo> infos = _data.ToObject<List<SchoolInfo>>();
  1479. if (infos.IsNotEmpty())
  1480. {
  1481. schools.AddRange(infos.Where(x => x.name != null && x.cityName != null).ToList());
  1482. }
  1483. }
  1484. else
  1485. {
  1486. nodata.Add(data.ToJsonString());
  1487. continue;
  1488. }
  1489. }
  1490. else
  1491. {
  1492. nodata.Add(data.ToJsonString());
  1493. continue;
  1494. }
  1495. }
  1496. catch (Exception ex)
  1497. {
  1498. nodata.Add(data.ToJsonString());
  1499. throw new Exception(ex.Message, ex.InnerException);
  1500. }
  1501. }
  1502. }
  1503. return (schools, nodata);
  1504. }
  1505. public class SchoolInfo
  1506. {
  1507. public string typeName { get; set; }
  1508. public string provinceName { get; set; }
  1509. public string provinceId { get; set; }
  1510. public string id { get; set; }
  1511. public string name { get; set; }
  1512. public string cityId { get; set; }
  1513. public string cityName { get; set; }
  1514. public string address { get; set; }
  1515. }
  1516. public class CodeName
  1517. {
  1518. public string code { get; set; }
  1519. public string name { get; set; }
  1520. }
  1521. /// <summary>
  1522. /// 测试blob多线程写入同一个文件
  1523. /// </summary>
  1524. /// <returns></returns>
  1525. [ProducesDefaultResponseType]
  1526. [HttpPost("generate-school-codes")]
  1527. public async Task<IActionResult> GenerateSchoolCodes(JsonElement json)
  1528. {
  1529. List<SchoolData> schoolss = json.GetProperty("schools").ToObject<List<SchoolData>>();
  1530. dynamic data = await SchoolService.GenerateSchoolCode(schoolss, _dingDing, _environment);
  1531. return Ok(data);
  1532. }
  1533. private async Task<int> SendNotification()
  1534. {
  1535. // _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  1536. var pa = new { grant_type = "device", client_id = "9794e418-c4ef-4fd5-a42d-accaa2d96d6e", client_secret = "ruL?I79h0w1AZaZXtBaZeZuQLQXLa=:-" };
  1537. HttpResponseMessage responseMessage = await _httpClient.CreateClient().PostAsJsonAsync("https://api2-rc.teammodel.net/oauth2/token", pa);
  1538. if (responseMessage.StatusCode == HttpStatusCode.OK)
  1539. {
  1540. return 200;
  1541. }
  1542. else if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
  1543. {
  1544. return 401;
  1545. }
  1546. else
  1547. {
  1548. return 500;
  1549. }
  1550. }
  1551. /// <summary>
  1552. /// 测试redis通配符
  1553. /// </summary>
  1554. /// <param name="request"></param>
  1555. /// <returns></returns>
  1556. [ProducesDefaultResponseType]
  1557. [HttpGet("test-delete-read")]
  1558. public async Task<IActionResult> TestDelete()
  1559. {
  1560. foreach (var cnt in _azureStorage.GetBlobServiceClient().GetBlobContainers())
  1561. {
  1562. Console.WriteLine(cnt.Name);
  1563. }
  1564. await SendNotification();
  1565. var client = _azureCosmos.GetCosmosClient();
  1566. string aaa = "0";
  1567. try
  1568. {
  1569. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  1570. Ok(a.StatusCode);
  1571. }
  1572. catch (CosmosException ex)
  1573. {
  1574. if (ex.StatusCode ==HttpStatusCode.NotFound)
  1575. {
  1576. aaa = "404";
  1577. }
  1578. }
  1579. try
  1580. {
  1581. ItemResponse<Student> a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync<Student>("1111111", new PartitionKey($"Course-111111"));
  1582. Ok(a.StatusCode);
  1583. }
  1584. catch (CosmosException ex)
  1585. {
  1586. if (ex.StatusCode == HttpStatusCode.NotFound)
  1587. {
  1588. aaa = aaa + " 404";
  1589. }
  1590. }
  1591. try
  1592. {
  1593. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").DeleteItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  1594. Ok(a.StatusCode);
  1595. }
  1596. catch (CosmosException ex)
  1597. {
  1598. if (ex.StatusCode == HttpStatusCode.NotFound)
  1599. {
  1600. aaa = "404";
  1601. }
  1602. }
  1603. try
  1604. {
  1605. var a = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemStreamAsync("1111111", new PartitionKey($"Course-111111"));
  1606. Ok(a.StatusCode);
  1607. }
  1608. catch (CosmosException ex)
  1609. {
  1610. if (ex.StatusCode == HttpStatusCode.NotFound)
  1611. {
  1612. aaa = aaa + " 404";
  1613. }
  1614. }
  1615. return Ok(new { aaa });
  1616. }
  1617. /// <summary>
  1618. /// 测试redis通配符
  1619. /// </summary>
  1620. /// <param name="request"></param>
  1621. /// <returns></returns>
  1622. [ProducesDefaultResponseType]
  1623. [HttpGet("test-redis")]
  1624. public async Task<IActionResult> TestRedis()
  1625. {
  1626. try
  1627. {
  1628. var client = _azureCosmos.GetCosmosClient();
  1629. List<ItemInfo> items = new List<ItemInfo>();
  1630. var queryslt = $"SELECT value(c) FROM c where c.pid = null ";
  1631. await foreach (var item in client.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIteratorSql<ItemInfo>(queryText: queryslt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Item-hbcn") }))
  1632. {
  1633. items.Add(item);
  1634. }
  1635. List<ItemCond> itemConds = new List<ItemCond>();
  1636. items.GroupBy(x => x.periodId).Select(y => new { key = y.Key, list = y.ToList() }).ToList().ForEach(z =>
  1637. {
  1638. ItemCond cond = new ItemCond() { id = z.key, code = $"ItemCond-hbcn", pk = "ItemCond", ttl = -1, count = z.list.Count, grades = new List<GradeCount>(), subjects = new List<SubjectItemCount>() };
  1639. z.list.ForEach(y =>
  1640. {
  1641. ItemService.CountItemCond(y, null, cond);
  1642. });
  1643. itemConds.Add(cond);
  1644. });
  1645. itemConds.ForEach(async cond =>
  1646. {
  1647. await client.GetContainer(Constant.TEAMModelOS, "School").UpsertItemAsync<ItemCond>(cond, new PartitionKey(cond.code));
  1648. });
  1649. return Ok(new { itemConds });
  1650. }
  1651. catch (Exception ex) { await _dingDing.SendBotMsg($"TEAMModelFunction,ActivityHttpTrigger,fix-itemcond()\n{ex.Message}\n{ex.StackTrace}", GroupNames.醍摩豆服務運維群組); }
  1652. return Ok(new { });
  1653. }
  1654. /// <summary>
  1655. ///
  1656. /// </summary>
  1657. /// <param name="request"></param>
  1658. /// <returns></returns>
  1659. [ProducesDefaultResponseType]
  1660. //[AuthToken(Roles = "teacher")]
  1661. [HttpPost("get-DownloadContent-item")]
  1662. public async Task<IActionResult> DownloadContentItem(JsonElement request)
  1663. {
  1664. ItemBlob itemBlob = null;
  1665. try
  1666. {
  1667. BlobDownloadInfo blobDownloadResult = await _azureStorage.GetBlobContainerClient($"hbcn").GetBlobClient($"/item/12b865c9-a223-278a-2be1-e336b9ead99e/12b865c9-a223-278a-2be1-e336b9ead99e.json")
  1668. .DownloadAsync();
  1669. if (blobDownloadResult != null)
  1670. {
  1671. var json = JsonDocument.Parse(blobDownloadResult.Content);
  1672. itemBlob = json.RootElement.ToObject<ItemBlob>();
  1673. }
  1674. }
  1675. catch (Exception ex)
  1676. {
  1677. itemBlob = null;
  1678. }
  1679. return Ok(new { itemBlob });
  1680. }
  1681. /// <summary>
  1682. ///
  1683. /// </summary>
  1684. /// <param name="request"></param>
  1685. /// <returns></returns>
  1686. [ProducesDefaultResponseType]
  1687. //[AuthToken(Roles = "teacher")]
  1688. [HttpPost("get-bind-data")]
  1689. public async Task<IActionResult> GetData(JsonElement request)
  1690. {
  1691. var areaId = request.GetProperty("areaId");
  1692. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  1693. List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object> { { "PartitionKey", "ScTeacher" }, { "areaId", $"{areaId}" } });
  1694. return Ok(teachers.Select(x => new { x.areaId, x.PXID, x.TID, x.TeacherName, x.tmdid, x.SchoolName, x.DisName }));
  1695. }
  1696. /// 删除
  1697. /// </summary>
  1698. /// <param name="request"></param>
  1699. /// <returns></returns>
  1700. [ProducesDefaultResponseType]
  1701. [AuthToken(Roles = "admin,teacher")]
  1702. [HttpPost("get-save-log")]
  1703. public async Task<IActionResult> SaveLog(JsonElement request)
  1704. {
  1705. BlobDownloadResult Recording = await _azureStorage.GetBlobContainerClient("1595321354").GetBlobClient($"records/271528531841781760/Record/.Recording.json").DownloadContentAsync();
  1706. var json = Recording.Content.ToString();
  1707. var jsonByte = Encoding.UTF8.GetBytes(json);
  1708. Stream stream = new MemoryStream(jsonByte);
  1709. var doc = JsonDocument.Parse(stream);
  1710. School school = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>("hbcn", new PartitionKey("Base"));
  1711. _ = _azureStorage.SaveLog("find-school", school.ToJsonString(), httpContext: HttpContext, dingDing: _dingDing, scope: "school");
  1712. return Ok(new { doc, school, });
  1713. }
  1714. /// <summary>
  1715. ///
  1716. /// </summary>
  1717. /// <param name="request"></param>
  1718. /// <returns></returns>
  1719. [ProducesDefaultResponseType]
  1720. //[AuthToken(Roles = "teacher")]
  1721. [HttpPost("get-ip")]
  1722. public async Task<IActionResult> GetIp(JsonElement request)
  1723. {
  1724. try
  1725. {
  1726. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient("habook").GetBlobClient($"/records/299813002894381056/IES/Base.json").DownloadContentAsync();
  1727. LessonBase lessonBase = baseblobDownload.Content.ToObjectFromJson<LessonBase>();
  1728. return Ok(lessonBase);
  1729. }
  1730. catch (RequestFailedException ex) when (ex.Status == 404)
  1731. {
  1732. return BadRequest("文件不存在!");
  1733. }
  1734. LessonBase lessonBases = request.ToObject<LessonBase>();
  1735. //List<TmdInfo> tmds= request.ToObject<List<TmdInfo>>();
  1736. //var content = new StringContent(tmds.Select(x=>x.id).ToJsonString(), Encoding.UTF8, "application/json");
  1737. //string json = await _coreAPIHttpService.GetUserInfos(content);
  1738. //string _researchKey = Regex.Replace($"{request.GetProperty("key")}", "[ \\[ \\] \\^ \\-|()【】/' {}_*×――(^)$%~!@#$…&%¥—+=<>《》!!???::•`·、。,;,.;\"‘’“”-]", " ");
  1739. //string[] mm = Regex.Split(_researchKey, "\\s+", RegexOptions.IgnoreCase);
  1740. //var token = await CoreTokenExtensions.CreateAccessToken("c7317f88-7cea-4e48-ac57-a16071f7b884", "kguxh:V.PLmxBdaI@jnrTrDSth]A3346", "China");
  1741. //string ip = await _searcher.SearchIpAsync($"{request.GetProperty("ip")}");
  1742. // return Ok(new { activity, ip, token.AccessToken,token.TokenType,token.IdToken, mm });
  1743. return Ok(lessonBases);
  1744. }
  1745. /// 删除
  1746. /// </summary>
  1747. /// <param name="request"></param>
  1748. /// <returns></returns>
  1749. [ProducesDefaultResponseType]
  1750. [HttpPost("check-online-record")]
  1751. public async Task<IActionResult> CheckOnlinerecord(JsonElement request)
  1752. {
  1753. string sql = $"select c.id,c.name ,b.schoolId as code from c join b in c.schools where b.areaId='9ae614ba-0771-4502-a56e-0537bc5207c3'";
  1754. List<IdNameCode> codes = new List<IdNameCode>();
  1755. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<IdNameCode>(sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1756. {
  1757. codes.Add(item);
  1758. }
  1759. List<dynamic> data = new List<dynamic>(); ;
  1760. foreach (IdNameCode code in codes)
  1761. {
  1762. try
  1763. {
  1764. TeacherTrain train = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherTrain>(code.id, new PartitionKey($"TeacherTrain-{code.code}"));
  1765. data.Add(new { code.id, code.name, code.code, train.totalTime, train.onlineTime, train.classTime, train.offlineTime });
  1766. }
  1767. catch (Exception ex)
  1768. {
  1769. data.Add(new { code.id, code.name, code.code, totalTime = 0, onlineTime = 0, classTime = 0, offlineTime = 0 });
  1770. }
  1771. }
  1772. return Ok(new { data });
  1773. }
  1774. [HttpPost("test-scteacher")]
  1775. public async Task<IActionResult> TestScteacher(JsonElement json)
  1776. {
  1777. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  1778. List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "areaId", "e6fb5d40-bd85-7327-cea8-ea5c642836d2" }, { "SchoolName", "岳池县大佛初级中学校" } });
  1779. //var techs= teachers.Where(t => string.IsNullOrWhiteSpace(t.tmdid));
  1780. return Ok(teachers);
  1781. }
  1782. [HttpPost("get-token")]
  1783. public async Task<IActionResult> GetToken(JsonElement request)
  1784. {
  1785. if (!request.TryGetProperty("id", out JsonElement id)) return BadRequest();
  1786. if (!request.TryGetProperty("host", out JsonElement host)) return BadRequest();
  1787. if (!request.TryGetProperty("name", out JsonElement name)) return BadRequest();
  1788. if (!request.TryGetProperty("picture", out JsonElement picture)) return BadRequest();
  1789. if (!request.TryGetProperty("areaId", out JsonElement areaId)) return BadRequest();
  1790. if (!request.TryGetProperty("school", out JsonElement school)) return BadRequest();
  1791. int timezone = 8;
  1792. if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone, out int tz))
  1793. {
  1794. timezone=tz;
  1795. }
  1796. var auth_token = JwtAuthExtension.CreateAuthToken(host.ToString(), id.ToString(), name.ToString(),
  1797. picture.ToString(), _option.JwtSecretKey,
  1798. scope: "student", Website: "IES",timezone, areaId: areaId.ToString(),schoolID: school.ToString(), roles: new[] { "student" }, expire: 1);
  1799. //var techs= teachers.Where(t => string.IsNullOrWhiteSpace(t.tmdid));
  1800. return Ok(auth_token);
  1801. }
  1802. [HttpPost("test-scteacher-dn")]
  1803. public async Task<IActionResult> TestScteacherDn(JsonElement json)
  1804. {
  1805. var table = _azureStorage.GetCloudTableClient().GetTableReference("ScYxpt");
  1806. string sqls = "select distinct value(c.id )from c where c.code='Base' and IS_DEFINED(c.finalScore)=true ";
  1807. //https://teammodelos.blob.core.chinacloudapi.cn/teammodelos
  1808. //https://teammodelos.blob.core.chinacloudapi.cn/teammodelos/yxpt%2Fjinniu%2Fscbind%2F1647432004.json
  1809. List<ScTeacher> teachers = await table.FindListByDict<ScTeacher>(new Dictionary<string, object>() { { "PartitionKey", "ScTeacher" }, { "areaId", "870a5a6b-1ab3-461a-bdeb-baec19780ddb" } });
  1810. List<string> ids = new List<string>();
  1811. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1812. .GetItemQueryIteratorSql<string>(sqls, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1813. {
  1814. ids.Add(item);
  1815. }
  1816. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1817. List<string> erorr = new List<string>();
  1818. List<ScTeacher> teachersUp = new List<ScTeacher>();
  1819. foreach (var id in ids)
  1820. {
  1821. try
  1822. {
  1823. BlobDownloadResult baseblobDownload = await _azureStorage.GetBlobContainerClient("teammodelos").GetBlobClient($"/yxpt/jinniu/scbind/{id}.json").DownloadContentAsync();
  1824. ScBindData scBindData = baseblobDownload.Content.ToObjectFromJson<ScBindData>();
  1825. var tcd = teachers.Find(x => x.RowKey.Equals(scBindData.pxid));
  1826. if (tcd != null)
  1827. {
  1828. Teacher teacher = new Teacher
  1829. {
  1830. createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
  1831. pk = "Base",
  1832. code = "Base",
  1833. id = id,
  1834. name = scBindData.username,
  1835. size = 2,
  1836. defaultSchool = tcd.schoolCode,
  1837. schools = new List<TeacherSchool> {
  1838. new TeacherSchool
  1839. {
  1840. schoolId = tcd.schoolCode, status = "join", time = now, name = scBindData.sn, areaId = tcd.areaId
  1841. }
  1842. },
  1843. binds = new List<ThirdBind> {
  1844. new ThirdBind
  1845. {
  1846. type= "scsyxpt",userid=scBindData.userid,username= scBindData.username,account=scBindData.account,data=new List<string>{ scBindData.ToJsonString()}
  1847. }
  1848. }
  1849. };
  1850. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(teacher, new PartitionKey("Base"));
  1851. tcd.tmdid = id;
  1852. teachersUp.Add(tcd);
  1853. }
  1854. }
  1855. catch (Exception)
  1856. {
  1857. erorr.Add(id);
  1858. }
  1859. }
  1860. await table.SaveOrUpdateAll(teachersUp);
  1861. return Ok();
  1862. }
  1863. [HttpPost("fix-jinniupujiang-teacher-videotime")]
  1864. public async Task<IActionResult> GetScteacher(JsonElement json)
  1865. {
  1866. if (!json.TryGetProperty("areaId", out JsonElement _areaId)) { return BadRequest(); }
  1867. Area area = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<Area>($"{_areaId}", new PartitionKey("Base-Area"));
  1868. AreaSetting setting = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<AreaSetting>($"{_areaId}", new PartitionKey("AreaSetting"));
  1869. List<string> teachers = new List<string>();
  1870. //获取这个区的教师 //psywgy
  1871. string schoolSql = $"SELECT value c.id FROM c join a in c.schools where a.areaId='{_areaId}' and c.code='Base' ";
  1872. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1873. .GetItemQueryIteratorSql<string>(schoolSql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  1874. {
  1875. teachers.Add(item);
  1876. }
  1877. //获取这些老师的研修记录
  1878. string tr = $"SELECT distinct value(c) FROM c join a in c.currency.teacherAilities where c.id in ({string.Join(",", teachers.Select(x => $"'{x}'"))}) and c.pk='TeacherTrain' and a.videoTime<300 ";
  1879. List<TeacherTrain> teacherTrains = new List<TeacherTrain>();
  1880. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher)
  1881. .GetItemQueryIteratorSql<TeacherTrain>(tr, requestOptions: new QueryRequestOptions { }))
  1882. {
  1883. if (!item.tmdid.Equals("1528783259") || !item.tmdid.Equals("1530606136"))
  1884. {
  1885. teacherTrains.Add(item);
  1886. }
  1887. }
  1888. //获取这个区的能力点树状结构
  1889. string sql = $" select distinct value(b.id ) from c join b in c.children where c.code='AbilityTask-{area.standard}' ";
  1890. List<string> nodeIdsDB = new List<string>();
  1891. await foreach (var y in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).GetItemQueryIteratorSql<string>
  1892. (sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
  1893. {
  1894. nodeIdsDB.Add(y);
  1895. }
  1896. List<AbilitySub> abilitySubs = new List<AbilitySub>();
  1897. List<TeacherVideoTime> teacherVideoTimes = new List<TeacherVideoTime>();
  1898. string ids = teacherTrains.Select(x => x.id).ToJsonString();
  1899. string sqls = $" select value(c) from c where c.code='AbilityTask-{area.standard}'";
  1900. List<AbilityTask> abilityTasks = new List<AbilityTask>();
  1901. Dictionary<string, RecordFileAbility> valuePairs = new Dictionary<string, RecordFileAbility>();
  1902. await foreach (var y in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).GetItemQueryIteratorSql<AbilityTask>
  1903. (sqls, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"AbilityTask-{area.standard}") }))
  1904. {
  1905. abilityTasks.Add(y);
  1906. }
  1907. foreach (var item in teacherTrains)
  1908. {
  1909. List<TeacherAbility> teacherAbility = new List<TeacherAbility>();
  1910. if (item.currency.teacherAilities.Count() > 3)
  1911. {
  1912. //如果选择了大于三个能力点的教师,则优先获取上传了认证材料的的能力点,
  1913. var uploadHas = item.currency.teacherAilities.FindAll(x => x.uploadHas == 1 && x.videoTime < 300);
  1914. if (uploadHas.Any())
  1915. {
  1916. teacherAbility.AddRange(uploadHas);
  1917. }
  1918. if (teacherAbility.Count < 3)
  1919. {
  1920. // 如果仍然未满足数量。则再去获取 没有上传认证材料,但是又有学习时间长的能力点。
  1921. var hasVideoTime = item.currency.teacherAilities.FindAll(x => x.uploadHas != 1 && x.videoTime < 300).OrderByDescending(o => o.videoTime);
  1922. var disCount = 3 - teacherAbility.Count;
  1923. teacherAbility.AddRange(hasVideoTime.Take(disCount));
  1924. }
  1925. }
  1926. else
  1927. {
  1928. teacherAbility.AddRange(item.currency.teacherAilities.Where(ab => ab.videoTime < 300));
  1929. }
  1930. TeacherFile teacherFile = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherFile>(item.id, new PartitionKey($"TeacherFile-{item.code.Replace("TeacherTrain-", "")}"));
  1931. foreach (var ability in teacherAbility)
  1932. {
  1933. TeacherVideoTime teacherVideoTime = new TeacherVideoTime { code = item.code.Replace("TeacherTrain-", ""), id = item.id, abilityId = ability.id, no = ability.no, train_time = ability.videoTime };
  1934. double fileview = 0;
  1935. var filerecord = teacherFile.fileRecords.FindAll(x => x.files.Where(y => y.abilityId.Equals(ability.id)).Count() > 0);
  1936. filerecord.ForEach(x => {
  1937. var file = x.files.FindAll(y => y.abilityId.Equals($"{ability.id}"));
  1938. if (file.IsNotEmpty())
  1939. {
  1940. fileview += x.view;
  1941. }
  1942. });
  1943. double fminut = fileview / 60;
  1944. teacherVideoTime.files_time = fminut;
  1945. var tech = abilityTasks.FindAll(x => x.abilityId.Equals(ability.id));
  1946. // double limit = 0;
  1947. tech.ForEach(task =>
  1948. {
  1949. task.children.ForEach(y =>
  1950. {
  1951. y.rnodes.ForEach(r =>
  1952. {
  1953. if (valuePairs.ContainsKey(r.hash))
  1954. {
  1955. valuePairs.TryGetValue(r.hash, out var value);
  1956. var ablt = value.fileAbilities.Find(z => z.abilityId.Equals(task.abilityId) && z.taskId.Equals(task.id) && z.nodeId.Equals(y.id));
  1957. if (ablt == null)
  1958. {
  1959. value.fileAbilities.Add(new FileAbility { url = r.link, abilityId = task.abilityId, taskId = task.id, nodeId = y.id });
  1960. // limit = limit + r.duration;
  1961. }
  1962. }
  1963. else
  1964. {
  1965. valuePairs.Add(r.hash, new RecordFileAbility
  1966. {
  1967. fileRecord =
  1968. new FileRecord { hash = r.hash, size = r.size.Value, duration = r.duration, view = (int)r.duration, type = r.type, done = true },
  1969. fileAbilities = new List<FileAbility> { new FileAbility { url = r.link, abilityId = task.abilityId, taskId = task.id, nodeId = y.id } }
  1970. });
  1971. // limit = limit + r.duration;
  1972. }
  1973. });
  1974. });
  1975. });
  1976. HashSet<string> childIds = new HashSet<string>();
  1977. foreach (var ps in valuePairs)
  1978. {
  1979. HashSet<string> abilityIds = teacherFile.fileRecords.SelectMany(x => x.files).Select(x => x.abilityId).Where(abid => abid.Equals(ability.id)).ToHashSet();
  1980. double view = 0;
  1981. foreach (var abid in abilityIds)
  1982. {
  1983. var record = teacherFile.fileRecords.FindAll(x => x.files.Where(y => y.abilityId.Equals(abid)).Count() > 0);
  1984. record.ForEach(x => {
  1985. var file = x.files.FindAll(y => y.abilityId.Equals($"{abid}"));
  1986. if (file.IsNotEmpty())
  1987. {
  1988. view += x.view;
  1989. }
  1990. });
  1991. }
  1992. double minut = view / 60;
  1993. teacherVideoTime.after_time = minut;
  1994. if (minut < 300)
  1995. {
  1996. var fils = teacherFile.fileRecords.Find(x => x.hash.Equals(ps.Key));
  1997. if (fils != null)
  1998. {
  1999. ps.Value.fileAbilities.ForEach(x =>
  2000. {
  2001. var a = fils.files.Find(z => z.nodeId.Equals(x.nodeId) && z.abilityId.Equals(x.abilityId));
  2002. if (a == null)
  2003. {
  2004. childIds.Add(x.nodeId);
  2005. fils.files.Add(new FileAbility { url = x.url, abilityId = x.abilityId, taskId = x.taskId, nodeId = x.nodeId });
  2006. }
  2007. });
  2008. }
  2009. else
  2010. {
  2011. ps.Value.fileAbilities.ForEach(x =>
  2012. {
  2013. childIds.Add(x.nodeId);
  2014. });
  2015. teacherFile.fileRecords.Add(new FileRecord
  2016. {
  2017. hash = ps.Value.fileRecord.hash,
  2018. size = ps.Value.fileRecord.size,
  2019. duration = ps.Value.fileRecord.duration,
  2020. view = (int)ps.Value.fileRecord.view,
  2021. type = ps.Value.fileRecord.type,
  2022. done = true,
  2023. files = ps.Value.fileAbilities
  2024. });
  2025. }
  2026. }
  2027. else
  2028. {
  2029. break;
  2030. }
  2031. }
  2032. if (childIds.Any())
  2033. {
  2034. string code = teacherFile.code.Replace("TeacherFile-", "");
  2035. if (!string.IsNullOrWhiteSpace(code))
  2036. {
  2037. try
  2038. {
  2039. AbilitySub abilitySub = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<AbilitySub>(ability.id, new PartitionKey($"AbilitySub-{code}-{teacherFile.id}"));
  2040. var taskIds = abilitySub.taskRcds.Select(x => x.id);
  2041. var notin = childIds.Except(taskIds);
  2042. if (notin.Any())
  2043. {
  2044. abilitySub.taskRcds.AddRange(notin.Select(x => new AbilityTaskRcd { id = x, done = true }));
  2045. abilitySubs.Add(abilitySub);
  2046. }
  2047. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync(abilitySub, abilitySub.id, new PartitionKey($"AbilitySub-{code}-{teacherFile.id}"));
  2048. }
  2049. catch (Exception ex)
  2050. {
  2051. }
  2052. }
  2053. }
  2054. teacherVideoTimes.Add(teacherVideoTime);
  2055. }
  2056. teacherFile = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherFile>(teacherFile, teacherFile.id, new PartitionKey(teacherFile.code));
  2057. item.update.Add(StatisticsService.TeacherAbility);
  2058. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(item, item.id, new PartitionKey(item.code));
  2059. }
  2060. var data = teacherVideoTimes.GroupBy(x => x.code).Select(x => new { x.Key, count = x.ToList().Count, list = x.ToList() }).OrderByDescending(x => x.count);
  2061. return Ok(new { data, abilitySubs });
  2062. }
  2063. public class TeacherVideoTime
  2064. {
  2065. public string code { get; set; }
  2066. public string id { get; set; }
  2067. public string abilityId { get; set; }
  2068. public string no { get; set; }
  2069. public double train_time { get; set; }
  2070. public double files_time { get; set; }
  2071. public double after_time { get; set; }
  2072. }
  2073. [HttpPost("get-teacher-video")]
  2074. public async Task<IActionResult> GetScteacherClassVideo(JsonElement json)
  2075. {
  2076. string sql = " SELECT c.id ,c.school as code FROM c where c.pk='ClassVideo' and c.school<>'SYSTEM_NO_SCHOOL' and ARRAY_LENGTH(c.files)>0 ";
  2077. List<IdNameCode> idNameCodes = new List<IdNameCode>();
  2078. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).GetItemQueryIteratorSql<IdNameCode>(sql, requestOptions: new QueryRequestOptions { }))
  2079. {
  2080. idNameCodes.Add(item);
  2081. }
  2082. foreach (var item in idNameCodes)
  2083. {
  2084. try
  2085. {
  2086. TeacherTrain teacherTrain = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<TeacherTrain>(item.id, new PartitionKey($"TeacherTrain-{item.code}"));
  2087. if (!teacherTrain.teacherClasses.Any())
  2088. {
  2089. teacherTrain.update.Add("TeacherClass");
  2090. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReplaceItemAsync<TeacherTrain>(teacherTrain, teacherTrain.id, new PartitionKey($"TeacherTrain-{item.code}"));
  2091. }
  2092. }
  2093. catch (Exception ex)
  2094. {
  2095. continue;
  2096. }
  2097. }
  2098. return Ok();
  2099. }
  2100. [HttpPost("test-batch")]
  2101. public async Task<IActionResult> TestBatchFUN(JsonElement json)
  2102. {
  2103. List<Task<ItemResponse<TestBatch>>> nameCodes = new List<Task<ItemResponse<TestBatch>>>();
  2104. for (int i = 0; i < 10; i++)
  2105. {
  2106. nameCodes.Add(_azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Student).
  2107. CreateItemAsync(new TestController.TestBatch { id = Guid.NewGuid().ToString(), code = $"TestBatch-{i}", pk = "TestBatch" }, new PartitionKey($"TestBatch-{i}")));
  2108. }
  2109. await Task.WhenAll(nameCodes);
  2110. return Ok();
  2111. }
  2112. public class TestBatch : CosmosEntity
  2113. {
  2114. }
  2115. [HttpPost("export-teacher")]
  2116. public async Task<IActionResult> ExportTeacher(JsonElement json)
  2117. {
  2118. List<string> schools = new()
  2119. {
  2120. "dghznx",
  2121. "cxhhlx",
  2122. "xjaxx",
  2123. "zjqxx",
  2124. "xnygxx",
  2125. "lxxcfx",
  2126. "gxjrxx",
  2127. "cdgxsx",
  2128. "yzxx",
  2129. "kjyxx",
  2130. "wjylxx",
  2131. "dsgjxx",
  2132. "ydzt",
  2133. "xndbxx",
  2134. "sqtszx",
  2135. "cdxczx",
  2136. "ghsyzx",
  2137. "lqsx",
  2138. "cdxxps",
  2139. "xcfx",
  2140. "xyqxx",
  2141. "xncbyy",
  2142. "cdlqjk",
  2143. "lqdmxx",
  2144. "lqyx",
  2145. "pclxxx",
  2146. "cdfzx",
  2147. "xnblxx",
  2148. "ghsx",
  2149. "khdycz",
  2150. "khbmxx",
  2151. "khdecz",
  2152. "khzx",
  2153. "khhbzx",
  2154. "gxxcxx",
  2155. "khhtxx",
  2156. "khdxxx",
  2157. "khsyxx"
  2158. };
  2159. var cosmosClient = _azureCosmos.GetCosmosClient();
  2160. foreach (var item in schools)
  2161. {
  2162. School school = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{item}", new PartitionKey("Base"));
  2163. List<Teacher> teachers = new();
  2164. await foreach (var tch in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIteratorSql<Teacher>(queryText:
  2165. $"SELECT value(c) FROM c join s in c.schools where s.schoolId='{item}' and c.code='Base'",
  2166. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  2167. {
  2168. teachers.Add(tch);
  2169. }
  2170. if (teachers.Count > 0)
  2171. {
  2172. foreach (var teacher in teachers)
  2173. {
  2174. teacher.schools.ForEach(tch => { if (tch.schoolId.Equals(item)) { tch.areaId = school.areaId; } });
  2175. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  2176. }
  2177. }
  2178. }
  2179. return Ok();
  2180. }
  2181. public class RecordFileAbility
  2182. {
  2183. public FileRecord fileRecord { get; set; }
  2184. public List<FileAbility> fileAbilities { get; set; }
  2185. }
  2186. [HttpPost("test-blob-folder")]
  2187. public async Task<IActionResult> TestBlobFolder(JsonElement json)
  2188. {
  2189. string location = _option.Location;
  2190. bool lockKey = await _azureRedis.GetRedisClient(8).KeyExistsAsync($"LessonRecord:Unused:Lock:{location}");
  2191. //key不存在的时候 。
  2192. if (!lockKey)
  2193. {
  2194. var schoolKeys = new List<IdCodeCount>();
  2195. var teacherKeys = new List<IdCodeCount>();
  2196. string sql = "select value c.id from c where c.code='Base'";
  2197. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  2198. GetItemQueryIteratorSql<string>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  2199. {
  2200. teacherKeys.Add(new IdCodeCount { id = item, code = "Teacher" });
  2201. }
  2202. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
  2203. GetItemQueryIteratorSql<string>(queryText: sql, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  2204. {
  2205. schoolKeys.Add(new IdCodeCount { id = item, code = "School" });
  2206. }
  2207. string sqlcount = "select value count(1) from c where c.pk='LessonRecord'";
  2208. foreach (var key in schoolKeys)
  2209. {
  2210. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.School).
  2211. GetItemQueryIteratorSql<int>(queryText: sqlcount, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord-{key.id}") }))
  2212. {
  2213. key.count = item;
  2214. break;
  2215. }
  2216. }
  2217. foreach (var key in teacherKeys)
  2218. {
  2219. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).
  2220. GetItemQueryIteratorSql<int>(queryText: $"select value count(1) from c where c.pk='LessonRecord' and c.tmdid='{key.id}'",
  2221. requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey($"LessonRecord") }))
  2222. {
  2223. key.count = item;
  2224. break;
  2225. }
  2226. }
  2227. schoolKeys.AddRange(teacherKeys);
  2228. //以下代码作用,用于根据当前拥有的课例数判断区分学校和个人使用课例频率越多的,
  2229. //并均分每次需要处理的学校和个人容器个数,避免每次处理批次花费时间相差太大。
  2230. //将每个批次处理数量级控制在500-1000左右。
  2231. List<IEnumerable<IdCodeCount>> counts = new List<IEnumerable<IdCodeCount>>();
  2232. //501-∞
  2233. var count501_ = schoolKeys.Where(x => x.count >= 501); //至少500条
  2234. counts.AddRange(count501_.Page(1));//1个学校
  2235. //201-500
  2236. var count201_500 = schoolKeys.Where(x => x.count >= 201 && x.count <= 500); //至少402条-1000条
  2237. counts.AddRange(count201_500.Page(2));//2个学校
  2238. //100-200
  2239. var count100_200 = schoolKeys.Where(x => x.count >= 100 && x.count <= 200);//至少500条-1000条
  2240. counts.AddRange(count100_200.Page(5));//5个学校
  2241. //51-99
  2242. var count51_99 = schoolKeys.Where(x => x.count >= 51 && x.count <= 99);//至少500条-990条
  2243. counts.AddRange(count51_99.Page(10));//10个学校
  2244. //21-50
  2245. var count21_50 = schoolKeys.Where(x => x.count >= 21 && x.count <= 50);//至少410条-1000条
  2246. counts.AddRange(count21_50.Page(20));//20个学校
  2247. //10-20
  2248. var count10_20 = schoolKeys.Where(x => x.count >= 10 && x.count <= 20);//至少500条-1000条
  2249. counts.AddRange(count10_20.Page(50));//50个学校
  2250. //5-9
  2251. var count0_9 = schoolKeys.Where(x => x.count >= 5 && x.count <= 9);//至少500条-900条
  2252. counts.AddRange(count0_9.Page(100));//100个学校
  2253. //2-4
  2254. var count2_4 = schoolKeys.Where(x => x.count >= 2 && x.count <= 4);//至少500条-1000条
  2255. counts.AddRange(count2_4.Page(250));
  2256. //0-1
  2257. var count0_1 = schoolKeys.Where(x => x.count >= 0 && x.count <= 1);//至少500,就算没有课例也算一次。
  2258. counts.AddRange(count0_1.Page(500));
  2259. int field = 1;
  2260. counts.Count();
  2261. foreach (var item in counts)
  2262. {
  2263. bool stuallstatus = await _azureRedis.GetRedisClient(8).HashSetAsync($"LessonRecord:Unused:Lock:{location}", field, new { status = 0, item }.ToJsonString());
  2264. field += 1;
  2265. }
  2266. await _dingDing.SendBotMsg($"{location},获取到:{schoolKeys.Count} 个学校和个人的容器\n" +
  2267. $"大概要处理:{schoolKeys.Sum(x => x.count) + schoolKeys.Where(x => x.count >= 0).Count()} 条数据\n" +
  2268. $"将数据分为:{field - 1} 次处理,每次处理500-1000条数据。", GroupNames.醍摩豆服務運維群組);
  2269. }
  2270. return Ok(new { });
  2271. }
  2272. public class IdCodeCount
  2273. {
  2274. public string id { get; set; }
  2275. public string code { get; set; }
  2276. public int count { get; set; }
  2277. }
  2278. /// <summary>
  2279. /// 随机获取三个不同类型的题目
  2280. /// </summary>
  2281. /// <param name="request"></param>
  2282. /// <returns></returns>
  2283. [HttpPost("gen-pdf")]
  2284. //[Authorize(Roles = Constant.Role_Root)]
  2285. public IActionResult GenPdf(JsonElement json)
  2286. {
  2287. //https://article.itxueyuan.com/JAxOnG
  2288. //http://t.zoukankan.com/hsiang-p-14608694.html
  2289. //https://github.com/rdvojmoc/DinkToPdf
  2290. //https://blog.csdn.net/u011966339/article/details/114964016?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-114964016-blog-118609642.pc_relevant_antiscanv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3
  2291. var html = @"
  2292. <!DOCTYPE html>
  2293. <html>
  2294. <head>
  2295. <meta charset=""UTF-8"">
  2296. <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
  2297. <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
  2298. <title>校本研修活动完成情况</title>
  2299. <style>
  2300. body {
  2301. font-family: ""fangsong"";
  2302. display: flex;
  2303. flex-direction: column;
  2304. align-items: center;
  2305. }
  2306. .tch-table,
  2307. .details-table {
  2308. width: 100%;
  2309. }
  2310. .tch-table table {
  2311. width: 100%;
  2312. margin: 15px 0;
  2313. border: 0;
  2314. }
  2315. .tch-table th {
  2316. background-color: #c5c5c5;
  2317. color: #222222;
  2318. }
  2319. .tch-table,
  2320. .tch-table th,
  2321. .tch-table td {
  2322. font-size: 0.95em;
  2323. text-align: center;
  2324. padding: 4px;
  2325. border-collapse: collapse;
  2326. font-weight: bolder;
  2327. }
  2328. .tch-table th,
  2329. .tch-table td {
  2330. border-bottom: 1px solid #918b8c;
  2331. border-width: 1px 0 1px 0;
  2332. }
  2333. .tch-table tr {
  2334. border: 1px solid #ffffff;
  2335. height: 3.2em;
  2336. }
  2337. .title {
  2338. font-weight: bold;
  2339. align-self: flex-start;
  2340. margin: 30px 5px;
  2341. }
  2342. .title::before {
  2343. content: """";
  2344. width: 10px;
  2345. height: 10px;
  2346. background: #3a3a3a;
  2347. display: inline-block;
  2348. margin-right: 10px;
  2349. }
  2350. </style>
  2351. </head>
  2352. <body>
  2353. <h1 style=""text-align:center;font-weight: bold;"">校本研修活动完成情况</h1>
  2354. <p class=""title"">教师信息</p>
  2355. <table class=""tch-table"" id=""tchTable"">
  2356. <tr>
  2357. <th style=""width: 33.3%;"">教师姓名</th>
  2358. <th style=""width: 33.3%;"">机构</th>
  2359. <th style=""width: 33.3%;"">教研组</th>
  2360. </tr>
  2361. <tr>
  2362. <td>张三</td>
  2363. <td>四川省成都市盐道街中学</td>
  2364. <td>高中政治教研组</td>
  2365. </tr>
  2366. </table>
  2367. <p class=""title"">活动明细</p>
  2368. <table class=""tch-table"" id=""acTable"">
  2369. <tr>
  2370. <th style=""width: 25%;"">活动主题</th>
  2371. <th style=""width: 15%;"">活动类型</th>
  2372. <th style=""width: 5%;"">任务学时</th>
  2373. <th style=""width: 5%;"">完成学时</th>
  2374. <th style=""width: 20%;"">活动时间</th>
  2375. <th style=""width: 10%;"">活动内容</th>
  2376. <th style=""width: 10%;"">活动任务</th>
  2377. <th style=""width: 10%;"">状态</th>
  2378. </tr>
  2379. <tr>
  2380. <td>语文学科如何在A1技术支持下进行学情分析</td>
  2381. <td>信息化教学案例展示与分享</td>
  2382. <td>1</td>
  2383. <td>1</td>
  2384. <td>2022-04-07 到 2022-04-14</td>
  2385. <td></td>
  2386. <td>扫码签到、作业提交、问卷反馈、评测活动</td>
  2387. <td>已完成</td>
  2388. </tr>
  2389. </table>
  2390. </body>
  2391. </html>
  2392. ";
  2393. try
  2394. {
  2395. GlobalSettings globalSettings = new GlobalSettings();
  2396. globalSettings.ColorMode = ColorMode.Color;
  2397. globalSettings.Orientation = Orientation.Portrait;
  2398. globalSettings.PaperSize = PaperKind.A4;
  2399. globalSettings.Margins = new MarginSettings { Top = 25, Bottom = 25 };
  2400. ObjectSettings objectSettings = new ObjectSettings();
  2401. objectSettings.PagesCount = true;
  2402. objectSettings.HtmlContent = html;
  2403. //WebSettings webSettings = new WebSettings();
  2404. //webSettings.DefaultEncoding = "utf-8";
  2405. HeaderSettings headerSettings = new HeaderSettings();
  2406. headerSettings.FontSize = 15;
  2407. headerSettings.FontName = "fangsong";
  2408. headerSettings.Right = "";
  2409. // headerSettings.Line = true;
  2410. FooterSettings footerSettings = new FooterSettings();
  2411. footerSettings.FontSize = 12;
  2412. footerSettings.FontName = "Ariel";
  2413. footerSettings.Center = "校本研修活动完成情况([page]/[toPage])页";
  2414. // footerSettings.Line = true;
  2415. objectSettings.HeaderSettings = headerSettings;
  2416. objectSettings.FooterSettings = footerSettings;
  2417. //objectSettings.WebSettings = webSettings;
  2418. HtmlToPdfDocument htmlToPdfDocument = new HtmlToPdfDocument()
  2419. {
  2420. GlobalSettings = globalSettings,
  2421. Objects = { objectSettings },
  2422. };
  2423. var a = _converter.Convert(htmlToPdfDocument);
  2424. MemoryStream m = new MemoryStream(a);
  2425. FileStream fs = new FileStream("F:\\1111111111111\\SimplePdf1.pdf", FileMode.Create, FileAccess.Write, FileShare.Read);
  2426. m.WriteTo(fs);
  2427. m.Close();
  2428. fs.Close();
  2429. var doc = new HtmlToPdfDocument()
  2430. {
  2431. GlobalSettings = {
  2432. ColorMode = ColorMode.Color,
  2433. Orientation = Orientation.Portrait,
  2434. PaperSize = PaperKind.A4,
  2435. Margins = new MarginSettings() { Top = 10 },
  2436. Out = @"F:\test.pdf",
  2437. },
  2438. Objects = {
  2439. new ObjectSettings()
  2440. {
  2441. Page = "https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html",
  2442. },
  2443. }
  2444. };
  2445. _converter.Convert(doc);
  2446. return Ok();
  2447. // return Ok(File(a, "application/octet-stream", "SimplePdf.pdf"));
  2448. }
  2449. catch (Exception ex)
  2450. {
  2451. return BadRequest(new { ex = ex.StackTrace, exmsg = ex.Message });
  2452. }
  2453. }
  2454. //寄送Mail測試
  2455. [HttpPost("test-sendmail")]
  2456. public async Task<IActionResult> TestSendMail(JsonElement json)
  2457. {
  2458. string mail = "jeff@habook.com.tw";
  2459. string tid = "d-f1c5abd8247f4be79ceaecdd327e9a68"; //"d-f1c5abd8247f4be79ceaecdd327e9a68":國際站預設模板 //"d-833d40ac6397414b852b91e2fa45850a":活動報名成功通知模板
  2460. string name = "Jeff";
  2461. string location = "Global";
  2462. string sub = "New subject";
  2463. string title = "HiTeach 6";
  2464. string body = "HiTeach 發布了!";
  2465. string image = "https://corestorageservice.blob.core.windows.net/public-marketing/S__43540491.png";
  2466. object data = new { sub = sub, title = title, body = body };
  2467. await _coreAPIHttpService.SendMail(new Dictionary<string, object> { { "to", mail }, { "tid", tid }, { "vars", data } }, location, _configuration);
  2468. return Ok();
  2469. }
  2470. /*
  2471. //自主學習綱領 資料架構測試
  2472. [HttpPost("test-selflearn-structure")]
  2473. public async Task<IActionResult> TestSelfLearnStructure(JsonElement json)
  2474. {
  2475. string tmid = "1595321354";
  2476. ////個人課程
  2477. //主體
  2478. SelfLearn selfLearnT = new SelfLearn();
  2479. selfLearnT.code = $"SelfLearn-{tmid}";
  2480. selfLearnT.id = "a6dc752f-7cae-44a5-9b7b-92cfe71cea14";
  2481. selfLearnT.scope = "private";
  2482. selfLearnT.name = "測試課程課綱";
  2483. selfLearnT.course = new IdName();
  2484. selfLearnT.course.id = "ae64e6a4-54f3-10df-a7f3-79dbe252d295";
  2485. selfLearnT.course.name = "測試課程001";
  2486. selfLearnT.creatorId = $"{tmid}";
  2487. selfLearnT.creatorName = "Miss Lo";
  2488. selfLearnT.release = true;
  2489. selfLearnT.groupLists.Add(new IdName { id = "a986bf87-da87-4bd3-bd90-19ee9fd52836", name = "測試課程名單" });
  2490. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnT);
  2491. //節點:章節
  2492. SelfLearnNode selfLearnNodeTChapter = new SelfLearnNode();
  2493. selfLearnNodeTChapter.code = $"SelfLearn-{tmid}";
  2494. selfLearnNodeTChapter.id = "0990cbb6-3228-41d0-aeb0-62209f37dc0d";
  2495. selfLearnNodeTChapter.name = "第一章節";
  2496. selfLearnNodeTChapter.selfLearnId = selfLearnT.id;
  2497. selfLearnNodeTChapter.nodeType = "chapter";
  2498. selfLearnNodeTChapter.openType = "order";
  2499. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeTChapter);
  2500. //節點:項目
  2501. SelfLearnNode selfLearnNodeTContent = new SelfLearnNode();
  2502. selfLearnNodeTContent.code = $"SelfLearn-{tmid}";
  2503. selfLearnNodeTContent.id = "5627184f-e9b4-4ceb-a1d0-47727db569b1";
  2504. selfLearnNodeTContent.name = "四則運算";
  2505. selfLearnNodeTContent.selfLearnId = selfLearnT.id;
  2506. selfLearnNodeTContent.selfLearnNodeId = selfLearnNodeTChapter.id;
  2507. selfLearnNodeTContent.nodeType = "content";
  2508. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeTContent);
  2509. //內容:作業
  2510. SelfLearnContentHomework selfLearnTContentHomework = new SelfLearnContentHomework();
  2511. selfLearnTContentHomework.code = $"SelfLearn-{tmid}";
  2512. //內容:評量
  2513. SelfLearnContentExam selfLearnTContentExam = new SelfLearnContentExam();
  2514. selfLearnTContentExam.code = $"SelfLearn-{tmid}";
  2515. selfLearnTContentExam.id = "07e6fdd2-6083-4eb6-ac6d-06421edb0b48";
  2516. selfLearnTContentExam.name = "隨堂測驗1";
  2517. selfLearnTContentExam.selfLearnId = selfLearnT.id;
  2518. selfLearnTContentExam.selfLearnNodeId = selfLearnNodeTContent.id;
  2519. selfLearnTContentExam.contentType = "exam";
  2520. //自主課綱的試卷需要從試題庫拷貝到課綱Blob之下 容器:個人課綱:{個人ID} 路徑:selflearn/{selfLearn本體ID}/paper/{試卷名稱}/{試卷各個檔案}
  2521. ////自主課綱Blob需納管入Blob容量計算系統之下
  2522. List<Dictionary<string, string>> sourcePaperDic = new List<Dictionary<string, string>>();
  2523. sourcePaperDic.Add(new Dictionary<string, string>() { { "id", "184914dd-05e0-04f4-e14a-cfce53545018" }, { "blobContainer", "1595321354" }, { "blob", "paper/個人評量測試卷1" }, { "name", "個人評量測試卷1" } });
  2524. foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperDic)
  2525. {
  2526. string targetScope = "private";
  2527. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(sourcePaperInfoDic["blobContainer"]);
  2528. string sourceBlobPath = (!sourcePaperInfoDic["blob"].EndsWith("/")) ? sourcePaperInfoDic["blob"] + "/" : sourcePaperInfoDic["blob"];
  2529. var destBlobContainer = _azureStorage.GetBlobContainerClient(tmid); //拷貝對象容器
  2530. string destBlobPath = $"/selflearn/{selfLearnT.id}/paper/{sourcePaperInfoDic["name"]}/";
  2531. Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  2532. if (sourceBlobs.Count() > 0)
  2533. {
  2534. foreach (var blob in sourceBlobs)
  2535. {
  2536. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  2537. if (sourceFileBlob.Exists())
  2538. {
  2539. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  2540. string fileName = blob.Name.Replace(sourceBlobPath, "");
  2541. string destBlobFilePath = $"{destBlobPath}{fileName}";
  2542. await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  2543. }
  2544. }
  2545. }
  2546. }
  2547. //內容:評量 DB操作
  2548. PaperSimple paper = new PaperSimple()
  2549. {
  2550. id = "184914dd-05e0-04f4-e14a-cfce53545018",
  2551. subjectId = null,
  2552. code = "Paper-1595321354",
  2553. name = "個人評量測試卷1",
  2554. blob = $"/selflearn/{selfLearnT.id}/paper/個人評量測試卷1/",
  2555. scope = "private",
  2556. multipleRule = 1,
  2557. point = new List<double>() { 50, 50 }, //這裡和題庫的格式不同,需要轉換
  2558. answers = new List<List<string>>() { new List<string>() { "B" }, new List<string>() { "A" } }, //這裡和題庫的格式不同,需要轉換
  2559. type = new List<string>() { "single", "single" }, //這裡和題庫的格式不同,需要轉換
  2560. field = new List<int>() { 1, 1 } //認知層次 這裡須由各題的Blob中取得後轉換
  2561. };
  2562. paper.subjectId = selfLearnT.course.id;
  2563. ExamInfo examT = new ExamInfo();
  2564. examT.pk = "Exam";
  2565. examT.scope = "private";
  2566. examT.owner = "teacher";
  2567. examT.code = $"Exam-{tmid}";
  2568. examT.creatorId = $"{tmid}";
  2569. examT.name = "隨堂測驗1";
  2570. examT.papers.Add(paper);
  2571. selfLearnTContentExam.examInfo = examT;
  2572. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnTContentExam);
  2573. ////學校課程
  2574. //主體
  2575. SelfLearn selfLearnS = new SelfLearn();
  2576. selfLearnS.pk = "SelfLearn";
  2577. selfLearnS.code = $"SelfLearn-{tmid}";
  2578. selfLearnS.id = "f05f79f2-c58d-4e27-8214-48385e2ac3cd";
  2579. selfLearnS.scope = "private";
  2580. selfLearnS.school = "hbgl";
  2581. selfLearnS.name = "數學一年級上學期課綱";
  2582. selfLearnS.subject = new IdName();
  2583. selfLearnS.subject.id = "c5f96ea0-e65c-f15c-dc59-410da564c185";
  2584. selfLearnS.subject.name = "數學";
  2585. selfLearnS.period = new IdName();
  2586. selfLearnS.period.id = "127e71a7-0ca8-82b8-476b-5269b78066f7";
  2587. selfLearnS.period.name = "測試國中";
  2588. selfLearnS.course = new IdName();
  2589. selfLearnS.course.id = "0d4fa541-ad4f-bee1-c604-764275f6d10e";
  2590. selfLearnS.course.name = "數學一";
  2591. selfLearnS.creatorId = $"{tmid}";
  2592. selfLearnS.creatorName = "Miss Lo";
  2593. selfLearnS.release = true;
  2594. selfLearnS.classes.Add(new IdName { id = "d3090c56-21de-4cc8-a962-a7e7eaa2e913", name = "2023年A班" });
  2595. selfLearnS.groupLists.Add(new IdName { id = "54a39ec1-be0b-43cd-a978-f3133552f291", name = "七年A班" });
  2596. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnS);
  2597. //節點:章節
  2598. SelfLearnNode selfLearnNodeSChapter = new SelfLearnNode();
  2599. selfLearnNodeSChapter.code = $"SelfLearn-{tmid}";
  2600. selfLearnNodeSChapter.id = "77172663-aa17-44c6-8259-61870c44121f";
  2601. selfLearnNodeSChapter.name = "第一章節";
  2602. selfLearnNodeSChapter.selfLearnId = selfLearnS.id;
  2603. selfLearnNodeSChapter.nodeType = "chapter";
  2604. selfLearnNodeSChapter.openType = "order";
  2605. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeSChapter);
  2606. //節點:項目
  2607. SelfLearnNode selfLearnNodeSContent = new SelfLearnNode();
  2608. selfLearnNodeSContent.code = $"SelfLearn-{tmid}";
  2609. selfLearnNodeSContent.id = "f28c6ecd-38a6-4edb-9160-363a116b8c3b";
  2610. selfLearnNodeSContent.name = "四則運算";
  2611. selfLearnNodeSContent.selfLearnId = selfLearnS.id;
  2612. selfLearnNodeSContent.selfLearnNodeId = selfLearnNodeSChapter.id;
  2613. selfLearnNodeSContent.nodeType = "content";
  2614. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnNodeSContent);
  2615. //內容:作業
  2616. SelfLearnContentHomework selfLearnSContentHomework = new SelfLearnContentHomework();
  2617. selfLearnSContentHomework.code = $"SelfLearn-{tmid}";
  2618. //內容:評量
  2619. SelfLearnContentExam selfLearnSContentExam = new SelfLearnContentExam();
  2620. selfLearnSContentExam.code = $"SelfLearn-{tmid}";
  2621. selfLearnSContentExam.id = "3f088f49-fefa-4af5-a324-c577ffb6d1f8";
  2622. selfLearnSContentExam.name = "隨堂測驗1";
  2623. selfLearnSContentExam.selfLearnId = selfLearnS.id;
  2624. selfLearnSContentExam.selfLearnNodeId = selfLearnNodeSContent.id;
  2625. selfLearnSContentExam.contentType = "exam";
  2626. //自主課綱試卷拷貝到課綱
  2627. foreach (Dictionary<string, string> sourcePaperInfoDic in sourcePaperDic)
  2628. {
  2629. string targetScope = "private";
  2630. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(sourcePaperInfoDic["blobContainer"]);
  2631. string sourceBlobPath = (!sourcePaperInfoDic["blob"].EndsWith("/")) ? sourcePaperInfoDic["blob"] + "/" : sourcePaperInfoDic["blob"];
  2632. var destBlobContainer = _azureStorage.GetBlobContainerClient(tmid); //拷貝對象容器
  2633. string destBlobPath = $"/selflearn/{selfLearnS.id}/paper/{sourcePaperInfoDic["name"]}/";
  2634. Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  2635. if (sourceBlobs.Count() > 0)
  2636. {
  2637. foreach (var blob in sourceBlobs)
  2638. {
  2639. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  2640. if (sourceFileBlob.Exists())
  2641. {
  2642. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  2643. string fileName = blob.Name.Replace(sourceBlobPath, "");
  2644. string destBlobFilePath = $"{destBlobPath}{fileName}";
  2645. await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. paper.blob = $"/selflearn/{selfLearnS.id}/paper/個人評量測試卷1/";
  2651. ExamInfo examS = new ExamInfo();
  2652. examS.pk = "Exam";
  2653. examS.scope = "school";
  2654. examS.owner = "teacher";
  2655. examS.code = $"Exam-{tmid}";
  2656. examS.creatorId = $"{tmid}";
  2657. examS.name = "隨堂測驗1";
  2658. examS.papers.Add(paper);
  2659. selfLearnSContentExam.examInfo = examS;
  2660. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Teacher).UpsertItemAsync(selfLearnSContentExam);
  2661. return Ok();
  2662. }
  2663. //自主學習綱領 生成評量架構測試
  2664. [HttpPost("test-selflearn-create-exam")]
  2665. public async void TestSelfLearnCreateExam(JsonElement json)
  2666. {
  2667. //輸入項:startTime (-1 會以現在時間記入)
  2668. long startTime = (json.TryGetProperty("startTime", out JsonElement startTimeJ)) ? startTimeJ.GetInt64() : -1;
  2669. var client = _azureCosmos.GetCosmosClient();
  2670. string tmid = "1595321354";
  2671. long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  2672. string code = string.Empty;
  2673. string selfLearnContentExamId = string.Empty;
  2674. SelfLearn selfLearn = new SelfLearn();
  2675. SelfLearnContentExam contentExam = new SelfLearnContentExam();
  2676. //[個人評量學校課程]
  2677. code = $"SelfLearn-{tmid}";
  2678. selfLearnContentExamId = "3f088f49-fefa-4af5-a324-c577ffb6d1f8"; //個人評量學校班級
  2679. contentExam = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearnContentExam>(selfLearnContentExamId, new PartitionKey(code));
  2680. if (contentExam != null)
  2681. {
  2682. string selfLearnId = contentExam.selfLearnId;
  2683. selfLearn = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearn>(selfLearnId, new PartitionKey(code));
  2684. }
  2685. if (!string.IsNullOrWhiteSpace(selfLearn.id))
  2686. {
  2687. //評量的架構只能生成 編制班(複數班) OR 選課班(複數班) 擇一,如果同步對象有編制班也有選課班,需生成兩個評量活動
  2688. int examCount = 0;
  2689. if (selfLearn.classes.Count > 0) examCount++;
  2690. if (selfLearn.groupLists.Count > 0) examCount++;
  2691. List<string> actExamInfoId = new List<string>() { "dbdcddc5-a79e-400f-a0b9-42801b176c21", "0c02b5e7-1aea-4126-b872-10baa2b4db56" };
  2692. for (int i = 0; i < examCount; i++)
  2693. {
  2694. string contentExamJsonStr = System.Text.Json.JsonSerializer.Serialize<ExamInfo>(contentExam.examInfo);
  2695. ExamInfo actExamInfo = System.Text.Json.JsonSerializer.Deserialize<ExamInfo>(contentExamJsonStr); //要生成的Exam
  2696. actExamInfo.id = actExamInfoId[i]; //假設每次生成新的評量;實作的時候應該在Exam埋入自主課綱相關的ID,如果可取得此ID的評量則更新
  2697. actExamInfo.source = "0"; //目前先設定為"線上評量",實際上應讓老師選擇
  2698. actExamInfo.creatorId = tmid;
  2699. actExamInfo.year = DateTimeOffset.UtcNow.Year;
  2700. IdName selfLearnSubject = selfLearn.subject;
  2701. IdName selfLearnCourse = selfLearn.course;
  2702. IdName selfLearnPeriod = selfLearn.period;
  2703. if (contentExam.examInfo.scope.Equals("school")) //學校 編制班、選課班 ※編制班、選課班無法共存只能擇一
  2704. {
  2705. actExamInfo.school = selfLearn.school;
  2706. actExamInfo.period.id = selfLearnPeriod.id;
  2707. actExamInfo.period.name = selfLearnPeriod.name;
  2708. actExamInfo.subjects.Add(new ExamSubject() { id = selfLearnSubject.id, name = selfLearnSubject.name });
  2709. if (actExamInfo.id.Equals("dbdcddc5-a79e-400f-a0b9-42801b176c21")) //編制班
  2710. {
  2711. foreach (IdName classRow in selfLearn.classes)
  2712. {
  2713. actExamInfo.classes.Add(classRow.id);
  2714. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "class", classRow.id };
  2715. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2716. }
  2717. }
  2718. else if (actExamInfo.id.Equals("0c02b5e7-1aea-4126-b872-10baa2b4db56")) //選課班
  2719. {
  2720. foreach (IdName groupRow in selfLearn.groupLists)
  2721. {
  2722. actExamInfo.stuLists.Add(groupRow.id);
  2723. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "teach", groupRow.id };
  2724. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2725. }
  2726. }
  2727. }
  2728. else if (contentExam.examInfo.scope.Equals("private"))
  2729. {
  2730. foreach (IdName groupRow in selfLearn.groupLists)
  2731. {
  2732. actExamInfo.subjects.Add(new ExamSubject() { id = selfLearn.course.id, name = selfLearn.course.name });
  2733. actExamInfo.stuLists.Add(groupRow.id);
  2734. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", groupRow.id };
  2735. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2736. }
  2737. }
  2738. //以下是Blob拷貝程序
  2739. //ExamInfo內容取得、調整
  2740. //※規則 owner:"school" => 校園評測 "teacher" => 個人評測
  2741. //※規則 scope:"school" => 校本班級 "private" => 個人班級
  2742. //※規則 BLOB容器: scope:"school" => {學校ID}下 scope:"private" => {個人ID}下
  2743. //試卷情報字典
  2744. string paperSubjectId = actExamInfo.subjects.First().id;
  2745. List<Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
  2746. foreach (PaperSimple paperInfo in contentExam.examInfo.papers)
  2747. {
  2748. string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
  2749. paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
  2750. string paperBlobContainer = tmid;
  2751. sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blobContainer", paperBlobContainer }, { "subjectId", paperSubjectId }, { "blob", paperBlobPath } });
  2752. }
  2753. //取得自主課綱下的試卷資料(blob)、複製到評測紀錄下
  2754. //Blob搬運
  2755. int paperIndex = 0;
  2756. foreach (Dictionary<string, string> recordPaperInfoDic in sourcePaperInfo)
  2757. {
  2758. string targetScope = actExamInfo.scope; //評測對象 school:校本班級 private:私人課程
  2759. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(recordPaperInfoDic["blobContainer"]);
  2760. string sourceBlobPath = recordPaperInfoDic["blob"];
  2761. string destBlobContainerId = (!string.IsNullOrWhiteSpace(actExamInfo.school) && actExamInfo.scope.Equals("school")) ? actExamInfo.school : actExamInfo.creatorId;
  2762. var destBlobContainer = _azureStorage.GetBlobContainerClient(destBlobContainerId); //拷貝對象容器
  2763. string destBlobPath = $"exam/{actExamInfo.id}/paper/{recordPaperInfoDic["subjectId"]}"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/ ※2022-1-6 式樣變更[原]/paper/{試卷ID}/ [新]/paper/{subjectID}/
  2764. Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  2765. if (sourceBlobs.Count() > 0)
  2766. {
  2767. foreach (var blob in sourceBlobs)
  2768. {
  2769. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  2770. if (sourceFileBlob.Exists())
  2771. {
  2772. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  2773. string fileName = blob.Name.Replace(sourceBlobPath, "");
  2774. string destBlobFilePath = $"{destBlobPath}/{fileName}";
  2775. await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  2776. }
  2777. }
  2778. }
  2779. actExamInfo.papers[paperIndex].blob = destBlobPath;
  2780. actExamInfo.papers[paperIndex].subjectId = selfLearnSubject.id;
  2781. paperIndex++;
  2782. }
  2783. //以下是ExamController生成評量邏輯
  2784. actExamInfo.createTime = now;
  2785. actExamInfo.startTime = startTime;
  2786. if (actExamInfo.startTime <= 0) actExamInfo.startTime = now;
  2787. actExamInfo.endTime = actExamInfo.startTime + 172800000; //結束時間設為2天後 ※實際上應由老師設定
  2788. List<string> classes = ExamService.getClasses(actExamInfo.classes, actExamInfo.stuLists);
  2789. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, selfLearn.school);
  2790. actExamInfo.stuCount = tchList.Count;
  2791. actExamInfo.progress = (actExamInfo.startTime > now) ? "pending" : "going";
  2792. var messageBlob = new ServiceBusMessage();
  2793. if (actExamInfo.scope.Equals("school"))
  2794. {
  2795. actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.school).GetBlobsSize($"exam/{actExamInfo.id}");
  2796. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.school }, _serviceBus, _configuration, _azureRedis);
  2797. }
  2798. else
  2799. {
  2800. string schoolId = string.Empty; //看學生是否有屬於學校,如果有則填入學校ID
  2801. foreach (RMember stuInfo in tchList)
  2802. {
  2803. if (!string.IsNullOrWhiteSpace(stuInfo.schoolId) && string.IsNullOrWhiteSpace(schoolId)) schoolId = stuInfo.schoolId;
  2804. }
  2805. actExamInfo.school = (!string.IsNullOrWhiteSpace(schoolId)) ? schoolId : "SYSTEM_NO_SCHOOL";
  2806. actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.creatorId).GetBlobsSize($"exam/{actExamInfo.id}");
  2807. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.creatorId }, _serviceBus, _configuration, _azureRedis);
  2808. }
  2809. int n = 0;
  2810. List<string> sheetIds = new List<string>();
  2811. foreach (PaperSimple simple in actExamInfo.papers)
  2812. {
  2813. simple.blob = $"/exam/{actExamInfo.id}/paper/{actExamInfo.subjects[n].id}";
  2814. n++;
  2815. simple.sheet = null;
  2816. }
  2817. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(actExamInfo, new PartitionKey($"{actExamInfo.code}"));
  2818. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  2819. }
  2820. }
  2821. //[個人評量個人課程]
  2822. //取得自主學習綱領內容、自主學習綱領主體
  2823. code = $"SelfLearn-{tmid}";
  2824. selfLearnContentExamId = "07e6fdd2-6083-4eb6-ac6d-06421edb0b48"; //個人評量個人課程
  2825. contentExam = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearnContentExam>(selfLearnContentExamId, new PartitionKey(code));
  2826. if (contentExam != null)
  2827. {
  2828. string selfLearnId = contentExam.selfLearnId;
  2829. selfLearn = await client.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<SelfLearn>(selfLearnId, new PartitionKey(code));
  2830. }
  2831. if(!string.IsNullOrWhiteSpace(selfLearn.id))
  2832. {
  2833. //補足實體化需要項目
  2834. //targets.row:
  2835. //個人課程: [0]:課程ID(CourseBase.id)[1]stuListId(GroupList.id)
  2836. //學校課程 編制班[0]:課程ID(CourseBase.id)[1]"class"[2]classId
  2837. //學校課程 選課班[0]:課程ID(CourseBase.id)[1]"teach"[2]stuListId(GroupList.id)
  2838. string contentExamJsonStr = System.Text.Json.JsonSerializer.Serialize<ExamInfo>(contentExam.examInfo);
  2839. ExamInfo actExamInfo = System.Text.Json.JsonSerializer.Deserialize<ExamInfo>(contentExamJsonStr); //要生成的Exam
  2840. actExamInfo.id = "78c4232d-b716-40a7-9901-c85b73da79a2"; //假設每次生成新的評量;實作的時候應該在Exam埋入自主課綱相關的ID,如果可取得此ID的評量則更新
  2841. actExamInfo.source = "0"; //目前先設定為"線上評量",實際上應讓老師選擇
  2842. actExamInfo.creatorId = tmid;
  2843. actExamInfo.year = DateTimeOffset.UtcNow.Year;
  2844. IdName selfLearnSubject = selfLearn.subject;
  2845. IdName selfLearnCourse = selfLearn.course;
  2846. IdName selfLearnPeriod = selfLearn.period;
  2847. if (contentExam.examInfo.scope.Equals("school")) //學校 編制班、選課班
  2848. {
  2849. actExamInfo.school = selfLearn.school;
  2850. actExamInfo.period.id = selfLearnPeriod.id;
  2851. actExamInfo.period.name = selfLearnPeriod.name;
  2852. actExamInfo.subjects.Add(new ExamSubject() { id = selfLearnSubject.id, name = selfLearnSubject.name });
  2853. foreach(IdName classRow in selfLearn.classes)
  2854. {
  2855. actExamInfo.classes.Add(classRow.id);
  2856. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "class", classRow.id };
  2857. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2858. }
  2859. foreach (IdName groupRow in selfLearn.groupLists)
  2860. {
  2861. actExamInfo.stuLists.Add(groupRow.id);
  2862. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", "teach", groupRow.id };
  2863. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2864. }
  2865. }
  2866. else if(contentExam.examInfo.scope.Equals("private"))
  2867. {
  2868. foreach (IdName groupRow in selfLearn.groupLists)
  2869. {
  2870. actExamInfo.subjects.Add(new ExamSubject() { id = selfLearn.course.id, name = selfLearn.course.name });
  2871. actExamInfo.stuLists.Add(groupRow.id);
  2872. List<string> targetRow = new List<string>() { $"{selfLearn.course.id}", groupRow.id };
  2873. actExamInfo.targets.Add(System.Text.Json.JsonSerializer.SerializeToElement(targetRow));
  2874. }
  2875. }
  2876. //以下是Blob拷貝程序
  2877. //ExamInfo內容取得、調整
  2878. //※規則 owner:"school" => 校園評測 "teacher" => 個人評測
  2879. //※規則 scope:"school" => 校本班級 "private" => 個人班級
  2880. //※規則 BLOB容器: scope:"school" => {學校ID}下 scope:"private" => {個人ID}下
  2881. //試卷情報字典
  2882. string paperSubjectId = actExamInfo.subjects.First().id;
  2883. List <Dictionary<string, string>> sourcePaperInfo = new List<Dictionary<string, string>>();
  2884. foreach (PaperSimple paperInfo in contentExam.examInfo.papers)
  2885. {
  2886. string paperBlobPath = (!paperInfo.blob.EndsWith("/")) ? paperInfo.blob + "/" : paperInfo.blob;
  2887. paperBlobPath = (paperInfo.blob.StartsWith("/")) ? paperBlobPath.Remove(0, 1) : paperBlobPath;
  2888. string paperBlobContainer = tmid;
  2889. sourcePaperInfo.Add(new Dictionary<string, string>() { { "id", paperInfo.id }, { "blobContainer", paperBlobContainer }, { "subjectId", paperSubjectId }, { "blob", paperBlobPath } });
  2890. }
  2891. //取得自主課綱下的試卷資料(blob)、複製到評測紀錄下
  2892. //Blob搬運
  2893. int paperIndex = 0;
  2894. foreach (Dictionary<string, string> recordPaperInfoDic in sourcePaperInfo)
  2895. {
  2896. string targetScope = actExamInfo.scope; //評測對象 school:校本班級 private:私人課程
  2897. var sourceBlobContainer = _azureStorage.GetBlobContainerClient(recordPaperInfoDic["blobContainer"]);
  2898. string sourceBlobPath = recordPaperInfoDic["blob"];
  2899. string destBlobContainerId = (!string.IsNullOrWhiteSpace(actExamInfo.school) && actExamInfo.scope.Equals("school")) ? actExamInfo.school : actExamInfo.creatorId;
  2900. var destBlobContainer = _azureStorage.GetBlobContainerClient(destBlobContainerId); //拷貝對象容器
  2901. string destBlobPath = $"exam/{actExamInfo.id}/paper/{recordPaperInfoDic["subjectId"]}"; //拷貝對象路徑 path:exam/{評測ID}/paper/{subjectID}/ ※2022-1-6 式樣變更[原]/paper/{試卷ID}/ [新]/paper/{subjectID}/
  2902. Azure.Pageable<BlobItem> sourceBlobs = sourceBlobContainer.GetBlobs(prefix: sourceBlobPath);
  2903. if (sourceBlobs.Count() > 0)
  2904. {
  2905. foreach (var blob in sourceBlobs)
  2906. {
  2907. var sourceFileBlob = sourceBlobContainer.GetBlobClient(blob.Name);
  2908. if (sourceFileBlob.Exists())
  2909. {
  2910. var sourceFileUri = sourceBlobContainer.GetBlobClient(blob.Name).Uri;
  2911. string fileName = blob.Name.Replace(sourceBlobPath, "");
  2912. string destBlobFilePath = $"{destBlobPath}/{fileName}";
  2913. await destBlobContainer.GetBlobClient(destBlobFilePath).StartCopyFromUriAsync(sourceFileUri);
  2914. }
  2915. }
  2916. }
  2917. actExamInfo.papers[paperIndex].blob = destBlobPath;
  2918. actExamInfo.papers[paperIndex].subjectId = selfLearn.course.id;
  2919. paperIndex++;
  2920. }
  2921. //以下是ExamController生成評量邏輯
  2922. actExamInfo.createTime = now;
  2923. actExamInfo.startTime = startTime;
  2924. if (actExamInfo.startTime <= 0) actExamInfo.startTime = now;
  2925. actExamInfo.endTime = actExamInfo.startTime + 172800000; //結束時間設為2天後 ※實際上應由老師設定
  2926. List<string> classes = ExamService.getClasses(actExamInfo.classes, actExamInfo.stuLists);
  2927. (List<RMember> tchList, List<RGroupList> classLists) = await GroupListService.GetMemberByListids(_coreAPIHttpService, client, _dingDing, classes, selfLearn.school);
  2928. actExamInfo.stuCount = tchList.Count;
  2929. actExamInfo.progress = (actExamInfo.startTime > now) ? "pending" : "going";
  2930. var messageBlob = new ServiceBusMessage();
  2931. if (actExamInfo.scope.Equals("school"))
  2932. {
  2933. actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.school).GetBlobsSize($"exam/{actExamInfo.id}");
  2934. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.school }, _serviceBus, _configuration, _azureRedis);
  2935. }
  2936. else
  2937. {
  2938. string schoolId = string.Empty; //看學生是否有屬於學校,如果有則填入學校ID
  2939. foreach (RMember stuInfo in tchList)
  2940. {
  2941. if (!string.IsNullOrWhiteSpace(stuInfo.schoolId) && string.IsNullOrWhiteSpace(schoolId)) schoolId = stuInfo.schoolId;
  2942. }
  2943. actExamInfo.school = (!string.IsNullOrWhiteSpace(schoolId)) ? schoolId: "SYSTEM_NO_SCHOOL";
  2944. actExamInfo.size = await _azureStorage.GetBlobContainerClient(actExamInfo.creatorId).GetBlobsSize($"exam/{actExamInfo.id}");
  2945. await BlobService.RefreshBlobRoot(new BlobRefreshMessage { progress = "insert", root = $"exam", name = actExamInfo.creatorId }, _serviceBus, _configuration, _azureRedis);
  2946. }
  2947. int n = 0;
  2948. List<string> sheetIds = new List<string>();
  2949. foreach (PaperSimple simple in actExamInfo.papers)
  2950. {
  2951. simple.blob = $"/exam/{actExamInfo.id}/paper/{actExamInfo.subjects[n].id}";
  2952. n++;
  2953. simple.sheet = null;
  2954. }
  2955. ExamInfo exam = await client.GetContainer(Constant.TEAMModelOS, "Common").UpsertItemAsync(actExamInfo, new PartitionKey($"{actExamInfo.code}"));
  2956. await BIStats.SetTypeAddStats(client, _dingDing, exam.school, "Exam", 1);//BI统计增/减量
  2957. }
  2958. }
  2959. */
  2960. }
  2961. }