home-learning-modules.integration.spec.ts 193 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860
  1. import { provideHttpClient } from '@angular/common/http';
  2. import { signal } from '@angular/core';
  3. import { TestBed } from '@angular/core/testing';
  4. import { By } from '@angular/platform-browser';
  5. import { provideRouter, Router } from '@angular/router';
  6. import { RouterTestingHarness } from '@angular/router/testing';
  7. import { Observable, of, Subject, throwError } from 'rxjs';
  8. import { CourseCenterPageComponent } from '../features/course-center/course-center-page.component';
  9. import { AppointmentPageComponent } from '../features/appointment/appointment-page.component';
  10. import { LearningPageComponent } from '../features/learning/learning-page.component';
  11. import { StudyRecordsPageComponent } from '../features/study-records/study-records-page.component';
  12. import { HomePageComponent } from '../features/home/home-page.component';
  13. import { routes } from '../app.routes';
  14. import { ApiService } from './api.service';
  15. import { ApiEnvelope, AppUser } from './models';
  16. import { LiveDataRefreshService } from './live-data-refresh.service';
  17. import { PlatformService } from './platform.service';
  18. import { SessionService } from './session.service';
  19. class LearningModulesApiService {
  20. lastScheduleParams: Record<string, unknown> = {};
  21. lastNodeParams: Record<string, unknown> = {};
  22. lastAppointmentCourseParams: Record<string, unknown> = {};
  23. lastWordParams: Record<string, unknown> = {};
  24. lastLearningWordUpdate: Record<string, unknown> = {};
  25. lastMemoryParams: Record<string, unknown> = {};
  26. lastStandaloneLearningRecord: Record<string, unknown> = {};
  27. appointmentStatus = 0;
  28. historyWordAudio = '';
  29. completionRequests: Record<string, unknown>[] = [];
  30. completionResponse = new Subject<ApiEnvelope<unknown>>();
  31. lastAppointmentRecordParams: Record<string, unknown> = {};
  32. studyUpdates: Record<string, unknown>[] = [];
  33. studyBatches: any[] = [];
  34. lastStudyQuery: Record<string, unknown> = {};
  35. reviewPageResponse: Subject<ApiEnvelope<unknown>> | null = null;
  36. courseWords: Record<string, unknown>[] | null = null;
  37. courseIncrements = new Map<string, number>();
  38. courseBookCounts: number[] | null = null;
  39. unitRows: Record<string, unknown>[] = [
  40. { NodeID: 811, NodeName: 'Unit 1', yx_word: 1, total: 20 },
  41. { NodeID: 812, NodeName: 'Unit 2', yx_word: 0, total: 18 },
  42. ];
  43. get<T>(action: string, params: Record<string, unknown> = {}): Observable<ApiEnvelope<T>> {
  44. if (action === 'app_account_overview') return this.post<T>(action, params);
  45. if (action === 'content_list' && params['orders'] === 'NEWID()') {
  46. return this.result<T>(Array.from({length: 8}, (_, i) => ({GeneralID: 9000 + i, Title: `external-${i}`, sy: `外部释义 ${i}`})));
  47. }
  48. if (action === 'content_list' && Number(params['ModelID'] ?? params['modelId']) === 56 && String(params['myfield2']).includes('dsid=')) {
  49. this.lastAppointmentRecordParams = params;
  50. if (!String(params['myfield2']).includes('|pl=300')) return throwError(() => new Error('无权查看该学员的内容记录'));
  51. return this.result<T>([{ GeneralID: 9901 }]);
  52. }
  53. if (action === 'app_lesson_study') {
  54. this.lastStudyQuery = params;
  55. return this.result<T>({record: {learned: this.studyBatches.filter(b => b.status === 'confirmed').reduce((n, b) => n + b.words.length, 0)}, batches: this.studyBatches, pending: this.studyBatches.filter(b => b.status === 'draft').length});
  56. }
  57. if (action === 'e_record_detail') {
  58. return this.result<T>([{ GeneralID: 1001, NodeID: 811, Title: 'apple', sy: '苹果', check: 0 }]);
  59. }
  60. if (action === 'app_lesson_courses') { this.lastAppointmentCourseParams=params; return this.result<T>([{bindingId:'binding-801',kcid:801,Title:'七年级上册',courseName:'七年级上册',syjd:'{}'},{bindingId:'binding-802',kcid:802,Title:'阅读训练',courseName:'阅读训练'}]); }
  61. if (action === 'e_order_detail') {
  62. return this.result<T>([{
  63. GeneralID: 901,
  64. szyh: 100,
  65. HoneyName: '张雅茜',
  66. kcid: 801, bindingId:'binding-801',
  67. yykcmc: '七年级上册',
  68. dszt: this.appointmentStatus,
  69. updatedAt: "2026-10-11T00:00:00Z",
  70. allowedActions: this.appointmentStatus===0?["start"]:this.appointmentStatus===10?["continue","complete"]:this.appointmentStatus===30?[]:["complete"],
  71. reviewStatus: "pending",
  72. dslx: 2,
  73. bxrq: '2026-08-10',
  74. sdsd: '19:00',
  75. jffs: '线上',
  76. }]);
  77. }
  78. if (action === 'content_list' && Number(params['nid']) === 291) {
  79. return this.result<T>([
  80. { GeneralID: 201, CreateTime: '2026-08-01 09:30:00', con: '初中英语@Unit 1', xxqs: JSON.stringify([{ Title: 'apple' }]) },
  81. { GeneralID: 202, CreateTime: '2026-08-04 16:20:00', con: '高中英语@Unit 2' },
  82. ]);
  83. }
  84. if (action === 'content_list' && Number(params['nid']) === 388) {
  85. return this.result<T>([
  86. { GeneralID: 100, Title: '张雅茜@历史任务', kywsj: '2026-05-15 09:00', fxzt: 1, yhid: 100, xxjlid: 900 },
  87. { GeneralID: 101, Title: '张雅茜@任务', kywsj: '2026-08-01 09:00', fxzt: 1, yhid: 100, xxjlid: 900 },
  88. { GeneralID: 102, Title: '张雅茜@任务', kywsj: '2026-08-02 09:00', fxzt: 0, yhid: 100, xxjlid: 900 },
  89. ]);
  90. }
  91. if (action === 'content_list' && Number(params['nid']) === 3) {
  92. return this.result<T>([{ GeneralID: 301, Title: '阅读理解专项' }]);
  93. }
  94. if (action === 'content_list' && Number(params['nid']) === 389) {
  95. return this.result<T>([{ GeneralID: 401, df: 18, totalScore: 48, dontKnow: 20, wrong: 10 }]);
  96. }
  97. if (action === 'content_list' && Number(params['nid']) === 28) {
  98. this.lastAppointmentCourseParams = params;
  99. return this.result<T>([
  100. { GeneralID: 801, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
  101. { GeneralID: 802, kcid: 801, Title2: '【初中英语】阅读训练' },
  102. ]);
  103. }
  104. if (action === 'content_list' && Number(params['ModelID']) === 58) {
  105. return this.result<T>([{ GeneralID: 701, yhid: 100, kcid: 801, syjd: '{}' }]);
  106. }
  107. if (action === 'content_list' && Number(params['nid']) === 29) {
  108. this.lastScheduleParams = params;
  109. return this.result<T>([
  110. { GeneralID: 901, bxrq: '2026-08-10 00:00:00', sdsd: '19:00', Title: '同步伴学', plxm: '张老师', dszt: 10 },
  111. { GeneralID: 902, bxrq: '2026-08-03 00:00:00', sdsd: '18:00', Title: '历史伴学', plxm: '李老师', dszt: 30 },
  112. ]);
  113. }
  114. if (action === 'node_list' && Number(params['pid']) === 8) {
  115. return this.result<T>([{ NodeID: 801, NodeName: '小学人教版词库' }]);
  116. }
  117. if (action === 'node_list' && Number(params['pid']) === 801) {
  118. this.lastNodeParams = params;
  119. return this.result<T>(this.unitRows);
  120. }
  121. if (action === 'e_ck_list') {
  122. this.lastWordParams = params;
  123. const allWords = (this.courseWords ?? (Number(params['nids']) === 813
  124. ? Array.from({ length: 65 }, (_, index) => ({ GeneralID: 2001 + index, NodeID: 813, Title: `word-${index + 1}`, sy: `释义 ${index + 1}` }))
  125. : [
  126. { GeneralID: 1001, NodeID: 811, Title: 'apple', sy: 'n. 苹果', yp: 'apple.mp3', w_learned: 1 },
  127. { GeneralID: 1002, NodeID: 812, Title: 'banana', sy: 'n. 香蕉', yp: 'banana.mp3', w_learned: 0 },
  128. ])).map((word: Record<string, unknown>) => ({...word,w_learned:(Number(word['w_learned'])||0)+(this.courseIncrements.get(String(word['GeneralID']))||0)}));
  129. const pageIndex = Math.max(1, Number(params['cpage'] ?? 1));
  130. const pageSize = Math.max(1, Number(params['psize'] ?? 30));
  131. const passCounts = [0,1,2,3].map(pass => allWords.filter(word => Math.min(3,Number(word['w_learned']) || 0) === pass).length);
  132. const filtered = params['learningPass'] == null ? allWords : allWords.filter(word => Math.min(3,Number(word['w_learned']) || 0) === Number(params['learningPass']));
  133. const result = filtered.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
  134. return of({
  135. retcode: 1,
  136. result: result as T,
  137. page: { itemCount: filtered.length, pageCount: Math.ceil(filtered.length / pageSize), pageIndex, pageSize, passCounts, bookPassCounts: this.courseBookCounts ?? passCounts },
  138. });
  139. }
  140. if (action === 'node_get') return this.result<T>([{ NodeID: 3, NodeName: '专项训练' }]);
  141. if (action === 'app_exam_history') return this.result<T>({items:[{GeneralID:'answer:401',df:18,totalScore:48,dontKnow:20,wrong:10,resultAvailable:true,askid:1,testedAt:'2026-10-01T08:00:00Z'}],hasMore:false});
  142. if (action === 'vote_ask') return this.result<T>([{ ID: 1, Title: '第一组问题' }]);
  143. if (action === 'vote_question') {
  144. return this.result<T>([{ ID: 501, AskID: 1, QType: 1, QTitle: 'apple', QContent: '苹果', QOption: JSON.stringify([{ text: '苹果', value: 1 }]) }]);
  145. }
  146. if (action === 'e_words_list') {
  147. return this.result<T>([{
  148. GeneralID: 601,
  149. Title: 'tend@张雅茜',
  150. detail: [{ GeneralID: 701, Title: 'tend', sy: 'vt.照顾;照料', yp: 'tend.mp3' }],
  151. }]);
  152. }
  153. return this.result<T>([]);
  154. }
  155. post<T>(action: string, params: Record<string, unknown> = {}): Observable<ApiEnvelope<T>> {
  156. if (action === 'stu_record_update_v2') {
  157. this.studyUpdates.push(params);
  158. const batchId=String(params['batchId']), words=JSON.parse(String(params['addon'])).xxqs;
  159. const version=Number(params['expectedVersion']||0)+1;
  160. this.studyBatches=this.studyBatches.filter(b=>b.batchId!==batchId).concat({batchId,words,status:params['saveMode']==='confirm'?'confirmed':'draft',version,bindingId:'binding-801'});
  161. return this.result<T>({ GeneralID: 9901, batchVersion:version, learned:new Set(this.studyBatches.filter(b=>b.status==='confirmed').flatMap(b=>b.words.map((w:any)=>w.GeneralID))).size });
  162. }
  163. if (action === 'app_lesson_complete') {
  164. this.completionRequests.push(params);
  165. return this.completionResponse as Observable<ApiEnvelope<T>>;
  166. }
  167. if (action === 'e_add_words') {
  168. this.lastLearningWordUpdate = params;
  169. if (params['save'] === 1) for (const id of String(params['wordsId']).split(',')) this.courseIncrements.set(id,(this.courseIncrements.get(id)||0)+1);
  170. return this.result<T>({ affected: String(params['wordsId'] ?? '').split(',').filter(Boolean).length });
  171. }
  172. if (action === 'content_add_zt') {
  173. this.lastStandaloneLearningRecord = params;
  174. return this.result<T>({ GeneralID: 9901 });
  175. }
  176. if (action === 'e_order_tongji') {
  177. return this.result<T>({ t30: 4, t60: 6, t_tiyan: 1, t_total: 11, t_shichang: 9, t_yongji: 320 });
  178. }
  179. if (action === 'e_user_list') {
  180. return this.result<T>([{ szyh: 100, honeyname: '张雅茜' }]);
  181. }
  182. if (action === 'app_learning_overview') {
  183. const records = Number(params['studentId']) === 777
  184. ? Array.from({ length: 45 }, (_, index) => ({
  185. GeneralID: 5000 + index,
  186. CreateTime: `2026-08-${String(31 - (index % 20)).padStart(2, '0')} 09:30:00`,
  187. dqrq: '20260801',
  188. con: `分页学习记录 ${index + 1}`,
  189. }))
  190. : [
  191. { GeneralID: 201, CreateTime: '2026-08-01 09:30:00', dqrq: '20260801', con: '初中英语@Unit 1', xxqs: JSON.stringify([{ Title: 'apple' }]), readingArticleId: 'readingarticle201', readingCompletedAt: '2026-08-01T03:00:00.000Z' },
  192. { GeneralID: 202, CreateTime: '2026-08-04 16:20:00', dqrq: '20260804', con: '高中英语@Unit 2', xxqs: JSON.stringify([{ Title: 'banana' }]) },
  193. ];
  194. const selected = String(params['date'] ?? '');
  195. return this.result<T>({
  196. records: (selected ? records.filter((item) => item.CreateTime.startsWith(selected)) : records).slice((Number(params['page']||1)-1)*20,Number(params['page']||1)*20),
  197. page:{itemCount:selected?records.filter(item=>item.CreateTime.startsWith(selected)).length:records.length,pageCount:Math.ceil(records.length/20)},
  198. latestReadingRecord: records[0],
  199. recordDateCounts: { '2026-08-01': 1, '2026-08-04': 1 },
  200. scheduleDateCounts: {},
  201. schedules: [],
  202. courses: [
  203. { GeneralID: 801, id: 701, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
  204. { GeneralID: 802, id: 702, Title2: '【初中英语】阅读训练', syjd: '{"811":"811@Unit 1@1"}' },
  205. ],
  206. refreshedAt: '2026-08-26T00:00:00.000Z',
  207. });
  208. }
  209. if (action === 'app_companion_overview') {
  210. this.lastScheduleParams = params;
  211. const schedules = [
  212. { GeneralID: 901, bxrq: '2026-08-10 00:00:00', sdsd: '19:00', Title: '同步伴学', plxm: '张老师', dszt: 10 },
  213. { GeneralID: 902, bxrq: '2026-08-03 00:00:00', sdsd: '18:00', Title: '历史伴学', plxm: '李老师', dszt: 30 },
  214. { GeneralID: 903, bxrq: '2099-01-01 00:00:00', sdsd: '18:00', Title: '未来计划', plxm: '王老师', dszt: 0 },
  215. ];
  216. const historySchedules = [
  217. { GeneralID: 911, szyh:100, bxrq: '2026-07-14 00:00:00', sdsd: '22:00', Title: '谢晨晨(60分钟练习)', plxm: '张老师', dszt: 30 },
  218. { GeneralID: 912, szyh:101, bxrq: '2026-07-14 00:00:00', sdsd: '17:00', Title: '谢谢(60分钟练习)', plxm: '张老师', dszt: 30 },
  219. { GeneralID: 913, szyh:102, bxrq: '2026-03-09 00:00:00', sdsd: '10:00', Title: '花花(60分钟练习)', plxm: '张老师', dszt: 30 },
  220. { GeneralID: 914, szyh:103, bxrq: '2026-01-18 00:00:00', sdsd: '16:30', Title: '小赵(60分钟练习)', plxm: '张老师', dszt: 30 },
  221. { GeneralID: 915, szyh:104, bxrq: '2026-01-18 00:00:00', sdsd: '16:00', Title: '小黄(60分钟练习)', plxm: '张老师', dszt: 30 },
  222. ];
  223. const rangeStart = String(params['rangeStart'] ?? '');
  224. const rangeEnd = String(params['rangeEnd'] ?? '');
  225. return this.result<T>({
  226. studentOptions: params['history'] ? [{id:'100',name:'谢晨晨',count:1},{id:'101',name:'谢谢',count:1},{id:'102',name:'花花',count:1},{id:'103',name:'小赵',count:1},{id:'104',name:'小黄',count:1}] : [],
  227. courses: [
  228. { GeneralID: 801, id: 701, kcid: 801, Title: '初中英语|七年级上册@同步词汇' },
  229. { GeneralID: 802, id: 702, Title2: '【初中英语】阅读训练', syjd: '{"811":"811@Unit 1@1"}' },
  230. ],
  231. dates:(params['history']?historySchedules:schedules).map(item=>({date:item.bxrq.slice(0,10),finished:item.dszt>=30?1:0,planned:item.dszt>=30?0:1})),
  232. schedules: params['history']
  233. ? historySchedules
  234. : rangeStart && rangeEnd
  235. ? schedules.filter((item) => item.bxrq.slice(0, 10) >= rangeStart && item.bxrq.slice(0, 10) <= rangeEnd)
  236. : schedules,
  237. refreshedAt: '2026-08-26T00:00:00.000Z',
  238. });
  239. }
  240. if (action === 'app_account_overview') {
  241. if (Number(params['uid']) === 300) {
  242. return this.result<T>({
  243. profile: { userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 },
  244. coachPanel: { todaySchedules: 2, completedLessons: 8, reviewIncome: 36, reviewRecords: 3, totalLessons: 11, totalHours: 9, course30: 4, course60: 6, trialLessons: 1 },
  245. refreshedAt: '2026-08-26T00:00:00.000Z',
  246. });
  247. }
  248. return this.result<T>({
  249. profile: { userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 },
  250. companionSummary: { completedSessions: 1, completedMinutes: 60 },
  251. antiForgetSummary: { total: 3, completed: 2, progress: 67, todayTotal: 0, todayCompleted: 0, duePending: 1, scheduled: 0, scheduledDays: 3 },
  252. refreshedAt: '2026-08-26T00:00:00.000Z',
  253. });
  254. }
  255. if (action === 'app_review_page') {
  256. this.lastMemoryParams=params;
  257. if (this.reviewPageResponse) return this.reviewPageResponse as Observable<ApiEnvelope<T>>;
  258. const items=params['scope']==='today' ? [{ GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: String(params['date'])+' 09:00', fxzt: 0, yhid: 100, xxjlid: 900 }] : [
  259. { GeneralID: 100, Title: '张雅茜@历史任务', kc_title: '历史复习', kywsj: '2026-05-15 09:00', learned_at: '2026-05-01T01:15:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
  260. { GeneralID: 101, Title: '张雅茜@任务', kc_title: '初中英语复习', kywsj: '2026-08-01 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
  261. { GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: '2026-08-02 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 0, yhid: 100, xxjlid: 900 },
  262. ...(Number(params['shouru']) === 1
  263. ? [{ GeneralID: 103, Title: '李同学@任务', kc_title: '小学英语复习', kywsj: '2026-08-02 10:00', learned_at: '2026-07-21T02:20:00.000Z', fxzt: 0, yhid: 101, xxjlid: 901 }]
  264. : []),
  265. ];return this.result<T>({items,page:{itemCount:items.length,pageCount:1},summary:{total:items.length,completed:items.filter(i=>i.fxzt===1).length,due:items.filter(i=>i.fxzt!==1).length,today:0,income:0},dates:items.map(i=>({date:i.kywsj.slice(0,10),total:1,completed:i.fxzt===1?1:0}))});
  266. }
  267. if (action === 'e_get_21list') {
  268. this.lastMemoryParams = params;
  269. return this.result<T>([
  270. { GeneralID: 100, Title: '张雅茜@历史任务', kc_title: '历史复习', kywsj: '2026-05-15 09:00', learned_at: '2026-05-01T01:15:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
  271. { GeneralID: 101, Title: '张雅茜@任务', kc_title: '初中英语复习', kywsj: '2026-08-01 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 1, yhid: 100, xxjlid: 900 },
  272. { GeneralID: 102, Title: '张雅茜@任务', kc_title: '高中英语复习', kywsj: '2026-08-02 09:00', learned_at: '2026-07-20T02:20:00.000Z', fxzt: 0, yhid: 100, xxjlid: 900 },
  273. ...(Number(params['shouru']) === 1
  274. ? [{ GeneralID: 103, Title: '李同学@任务', kc_title: '小学英语复习', kywsj: '2026-08-02 10:00', learned_at: '2026-07-21T02:20:00.000Z', fxzt: 0, yhid: 101, xxjlid: 901 }]
  275. : []),
  276. ]);
  277. }
  278. if (action === 'e_record_detail') {
  279. return of({
  280. retcode: 1,
  281. result: [{ GeneralID: 701, Title: 'apple', detail: [{ GeneralID: 701, Title: 'apple', sy: '苹果', yp: this.historyWordAudio }] }],
  282. addon: [{ if_writing: '0', if_writing_tips: '先回忆单词,再查看释义' }],
  283. } as unknown as ApiEnvelope<T>);
  284. }
  285. return this.result<T>([]);
  286. }
  287. assetUrl(path: unknown): string { return String(path ?? ''); }
  288. private result<T>(result: unknown): Observable<ApiEnvelope<T>> {
  289. return of({ retcode: 1, result: result as T });
  290. }
  291. }
  292. describe('home learning modules', () => {
  293. const user = signal<AppUser | null>({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
  294. const selectedStudent = signal<AppUser | null>(null);
  295. const session = {
  296. user,
  297. token: signal('test-token'),
  298. student: selectedStudent,
  299. isLoggedIn: signal(true),
  300. groupId: signal(1),
  301. setStudent: (student: AppUser | null) => selectedStudent.set(student),
  302. patchUser: () => undefined,
  303. logout: () => undefined,
  304. };
  305. beforeEach(() => {
  306. sessionStorage.removeItem('xiaoshu.learning.teacherTodayReview');
  307. localStorage.removeItem('xiaoshu.learning.homeDaily.v1');
  308. spyOn(window, 'confirm').and.returnValue(true);
  309. // Route tests do not depend on remote audio availability or its error-toast timer.
  310. spyOn(HTMLMediaElement.prototype, 'play').and.returnValue(Promise.resolve());
  311. localStorage.removeItem('xiaoshu.learning.300.100.901.unbound.skip_spelling_stage');
  312. user.set({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
  313. session.groupId.set(1);
  314. session.student.set(null);
  315. TestBed.configureTestingModule({
  316. providers: [
  317. provideRouter(routes),
  318. provideHttpClient(),
  319. { provide: ApiService, useClass: LearningModulesApiService },
  320. { provide: SessionService, useValue: session },
  321. ],
  322. });
  323. });
  324. for (const role of [1,3]) {
  325. it(`numbers learning records in reverse across pages and date filters for role ${role}`, async () => {
  326. user.set({userId:role===3?300:100,groupId:role});session.groupId.set(role);
  327. const api=TestBed.inject(ApiService), original=api.post.bind(api);
  328. spyOn(TestBed.inject(LiveDataRefreshService),'watch').and.returnValue(()=>{});
  329. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  330. if(action!=='app_learning_overview')return original(action,params);
  331. const total=params['date']?2:26,offset=(Number(params['page'])-1)*20;
  332. return of({retcode:0,result:{records:Array.from({length:Math.min(20,total-offset)},(_,i)=>({GeneralID:1000+offset+i,CreateTime:params['date']||'2026-11-12 12:00',con:'课程 '+(total-offset-i)})),courses:[],schedules:[],recordDateCounts:{},scheduleDateCounts:{},page:{itemCount:total,pageCount:Math.ceil(total/20)}}});
  333. }) as typeof api.post);
  334. const harness=await RouterTestingHarness.create('/pages/his/his');await harness.fixture.whenStable();harness.fixture.detectChanges();
  335. const component=harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
  336. const numbers=()=>Array.from(harness.routeNativeElement!.querySelectorAll('.learning-item .record-number'),node=>node.textContent!.trim());
  337. expect(numbers()).toEqual(Array.from({length:20},(_,i)=>String(26-i)));
  338. component.goToRecordPage(2);await harness.fixture.whenStable();harness.fixture.detectChanges();
  339. expect(numbers()).toEqual(['6','5','4','3','2','1']);
  340. component.selectDate('2026-11-12');await harness.fixture.whenStable();harness.fixture.detectChanges();
  341. expect(numbers()).toEqual(['2','1']);
  342. });
  343. }
  344. for (const role of [1,3]) {
  345. it(`numbers training records across date groups and pages with newest first for role ${role}`, async () => {
  346. user.set({userId:role===3?300:100,groupId:role});session.groupId.set(role);
  347. const api=TestBed.inject(ApiService), original=api.post.bind(api);
  348. spyOn(TestBed.inject(LiveDataRefreshService),'watch').and.returnValue(()=>{});
  349. const calls:Record<string,unknown>[]=[];
  350. const delayed = new Subject<ApiEnvelope<unknown>>();let retryPage = false;
  351. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  352. if(action!=='app_companion_overview')return original(action,params);
  353. calls.push(params);if(Number(params['page'])===2 && !retryPage)return delayed;
  354. const total=26,offset=(Number(params['page'])-1)*20;
  355. return of({retcode:0,result:{schedules:Array.from({length:Math.min(20,total-offset)},(_,i)=>({GeneralID:1000+offset+i,bxrq:'2026-11-'+String(26-offset-i).padStart(2,'0'),sdsd:'19:00',Title:'训练 '+(26-offset-i),dszt:30})),courses:[],studentOptions:[],dates:[],earningsSummary:{amount:0,pendingCount:0},page:{itemCount:26,pageCount:2}}});
  356. }) as typeof api.post);
  357. const harness=await RouterTestingHarness.create(role===3?'/pages/member/ke_xiao':'/pages/home/cart?csStatus=finished&csRange=all');
  358. await harness.fixture.whenStable();harness.fixture.detectChanges();
  359. const component=harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
  360. const numbers=()=>Array.from(harness.routeNativeElement!.querySelectorAll('.schedule-list .record-number'),node=>node.textContent!.trim());
  361. expect(calls[0]['history']).toBe(role===3);
  362. expect(numbers()).toEqual(Array.from({length:20},(_,i)=>String(26-i)));
  363. expect(harness.routeNativeElement!.querySelector('.schedule-copy strong')?.textContent).toContain('训练 26');
  364. component.turnPage(1);harness.fixture.detectChanges();
  365. expect(numbers()).toEqual(Array.from({length:20},(_,i)=>String(26-i)));
  366. delayed.error(new Error('翻页失败'));await harness.fixture.whenStable();harness.fixture.detectChanges();
  367. expect(numbers()).toEqual(Array.from({length:20},(_,i)=>String(26-i)));
  368. retryPage=true;component.load(true,true);await harness.fixture.whenStable();harness.fixture.detectChanges();
  369. expect(numbers()).toEqual(['6','5','4','3','2','1']);
  370. });
  371. }
  372. it('filters teacher history students before restoring a stale selection and uses server pagination', async () => {
  373. user.set({userId:300, groupId:3}); session.groupId.set(3);
  374. const watch = spyOn(TestBed.inject(LiveDataRefreshService), 'watch').and.returnValue(() => {});
  375. const api = TestBed.inject(ApiService), original = api.post.bind(api);
  376. const students = new Subject<ApiEnvelope<unknown>>();
  377. const post = spyOn(api, 'post').and.callFake(((action: string, params: Record<string, unknown> = {}) => {
  378. if (action === 'e_user_list') return students;
  379. return original(action, params);
  380. }) as typeof api.post);
  381. const harness = await RouterTestingHarness.create('/pages/his/his?uid=999');
  382. expect(post.calls.allArgs().find(([action]) => action === 'e_user_list')?.[1]).toEqual(jasmine.objectContaining({scope:'current-scheduled',selectedStudentId:999}));
  383. expect(post.calls.allArgs().some(([action]) => action === 'app_learning_overview')).toBeFalse();
  384. expect(watch).not.toHaveBeenCalled();
  385. students.next({retcode:0,result:[{szyh:100,honeyname:'在学学员'}],page:{itemCount:1,pageCount:1}});
  386. students.complete();
  387. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  388. const component = harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
  389. expect(component.studentId).toBe(100);
  390. expect(watch).toHaveBeenCalledTimes(1);
  391. expect(session.student()?.userId).toBe(100);
  392. expect(TestBed.inject(Router).url).toContain('uid=100');
  393. expect(component.studentsHaveMore()).toBeFalse();
  394. expect(post.calls.allArgs().filter(([action]) => action === 'app_learning_overview').map(([,params]) => params?.['studentId'])).toEqual([100]);
  395. expect(harness.routeNativeElement?.querySelector('.student-filter select')?.textContent).toContain('在学学员');
  396. });
  397. it('clears teacher history and the old student context when no eligible scheduled students remain', async () => {
  398. user.set({userId:300, groupId:3}); session.groupId.set(3);
  399. session.student.set({userId:999,groupId:1,honeyName:'旧学员'});
  400. spyOn(TestBed.inject(LiveDataRefreshService), 'watch').and.returnValue(() => {});
  401. const api = TestBed.inject(ApiService), original = api.post.bind(api);
  402. const post = spyOn(api, 'post').and.callFake(((action: string, params: Record<string, unknown> = {}) =>
  403. action === 'e_user_list' ? of({retcode:0,result:[],page:{itemCount:0,pageCount:0}}) : original(action,params)) as typeof api.post);
  404. const harness = await RouterTestingHarness.create('/pages/his/his?uid=999');
  405. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  406. expect(session.student()).toBeNull();
  407. expect(TestBed.inject(Router).url).toBe('/pages/his/his');
  408. expect(harness.routeNativeElement?.textContent).toContain('暂无在排课的正常学员');
  409. expect(harness.routeNativeElement?.querySelector('.learning-record-card')).toBeNull();
  410. expect(post.calls.allArgs().some(([action]) => action === 'app_learning_overview')).toBeFalse();
  411. });
  412. it('keeps an eligible restored student and a stable student order while loading more pages', async () => {
  413. user.set({userId:300, groupId:3}); session.groupId.set(3);
  414. spyOn(TestBed.inject(LiveDataRefreshService), 'watch').and.returnValue(() => {});
  415. const api = TestBed.inject(ApiService), original = api.post.bind(api), requests: Record<string,unknown>[] = [];
  416. spyOn(api, 'post').and.callFake(((action: string, params: Record<string, unknown> = {}) => {
  417. if (action !== 'e_user_list') return original(action,params);
  418. requests.push(params);
  419. return of({retcode:0,result:params['cpage']===1?[{szyh:777,honeyname:'原学员'},{szyh:100,honeyname:'另一学员'}]:[{szyh:101,honeyname:'下一页学员'}],page:{itemCount:3,pageCount:2}});
  420. }) as typeof api.post);
  421. const harness = await RouterTestingHarness.create('/pages/his/his?uid=777');
  422. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  423. const component = harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
  424. expect(component.studentId).toBe(777);
  425. expect(component.studentsHaveMore()).toBeTrue();
  426. component.studentId=100; component.onFilterChange();
  427. component.loadStudents(true);
  428. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  429. expect(requests.map(params => params['selectedStudentId'])).toEqual([777,777]);
  430. expect(component.students().map(row => component.studentValue(row))).toEqual([777,100,101]);
  431. expect(component.studentId).toBe(100);
  432. expect(component.studentsHaveMore()).toBeFalse();
  433. });
  434. it('shows a retry state instead of loading a stale student when the filtered student request fails', async () => {
  435. user.set({userId:300, groupId:3}); session.groupId.set(3);
  436. session.student.set({userId:999,groupId:1,honeyName:'旧学员'});
  437. const watch = spyOn(TestBed.inject(LiveDataRefreshService), 'watch').and.returnValue(() => {});
  438. const api = TestBed.inject(ApiService), original = api.post.bind(api);
  439. let fail = true;
  440. const post = spyOn(api, 'post').and.callFake(((action: string, params: Record<string, unknown> = {}) => {
  441. if (action !== 'e_user_list') return original(action,params);
  442. return fail ? throwError(() => new Error('学员列表暂时无法加载')) : of({retcode:0,result:[{szyh:100,honeyname:'在学学员'}],page:{itemCount:1,pageCount:1}});
  443. }) as typeof api.post);
  444. const harness = await RouterTestingHarness.create('/pages/his/his?uid=999');
  445. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  446. expect(session.student()).toBeNull();
  447. expect(harness.routeNativeElement?.textContent).toContain('学员列表加载失败');
  448. expect(post.calls.allArgs().some(([action]) => action === 'app_learning_overview')).toBeFalse();
  449. expect(watch).not.toHaveBeenCalled();
  450. fail = false;
  451. (harness.routeNativeElement?.querySelector('.teacher-student-state button') as HTMLButtonElement).click();
  452. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  453. expect(session.student()?.userId).toBe(100);
  454. expect(harness.routeNativeElement?.querySelector('.teacher-student-state')).toBeNull();
  455. });
  456. it('reconciles monthly review fees from every matching page when an old gateway always returns 29', async () => {
  457. user.set({userId:300, groupId:3, honeyName:'钱老师'}); session.groupId.set(3);
  458. const api = TestBed.inject(ApiService), original = api.post.bind(api), requests: Record<string,unknown>[] = [];
  459. spyOn(api, 'post').and.callFake(((action:string, params:Record<string,unknown> = {}) => {
  460. if (action !== 'app_review_page') return original(action,params);
  461. requests.push(params);
  462. const rows = Array.from({length:params['month']==='2026-09'?6:28}, (_,i) => ({GeneralID:i+1,money:params['month']==='2026-09'?1:i<21?1:0,fxzt:1,kywrq:params['month']+'-15'}));
  463. const size=Number(params['pageSize']), index=Number(params['page']);
  464. return of({result:{items:rows.slice((index-1)*size,index*size),page:{itemCount:rows.length,pageCount:Math.ceil(rows.length/size)},summary:{income:29},dates:[{date:'2026-09-15',total:6,completed:6},{date:'2026-10-15',total:28,completed:28}]}});
  465. }) as typeof api.post);
  466. const harness=await RouterTestingHarness.create('/pages/member/ke_fuxi');
  467. const component=harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
  468. component.setIncomeMonth('2026-10'); await harness.fixture.whenStable(); harness.fixture.detectChanges();
  469. expect(component.totalIncome()).toBe(21); expect(component.items().length).toBe(20);
  470. expect(requests.some(p=>p['month']==='2026-10'&&p['pageSize']===100&&p['includeMetadata']===false)).toBeTrue();
  471. expect(harness.routeNativeElement!.querySelector('.fee-summary-amount')!.textContent).toContain('21.00');
  472. component.setIncomeMonth('2026-09'); await harness.fixture.whenStable(); harness.fixture.detectChanges();
  473. expect(component.totalIncome()).toBe(6); expect(component.serverTotal()).toBe(6);
  474. expect(harness.routeNativeElement!.querySelector('.fee-summary-top')!.textContent).toContain('2026年09月');
  475. });
  476. it('shows lesson fee total with older gateways that omit earningsSummary', async () => {
  477. spyOn(TestBed.inject(LiveDataRefreshService), 'watch').and.returnValue(() => {});
  478. user.set({userId:300, groupId:3, honeyName:'钱老师'}); session.groupId.set(3);
  479. const api=TestBed.inject(ApiService), original=api.post.bind(api);
  480. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={}) => {
  481. if(action!=='app_companion_overview')return original(action,params);
  482. return of({result:{courses:[],schedules:Array.from({length:6},(_,i)=>({GeneralID:i+1,bxrq:'2026-09-15',dszt:30,teacherPay:30,payStatus:'earned'})),page:{itemCount:6,pageCount:1},dates:[{date:'2026-09-15',finished:6,planned:0}],studentOptions:[],refreshedAt:'2026-10-28'}});
  483. }) as typeof api.post);
  484. const harness=await RouterTestingHarness.create();
  485. await harness.navigateByUrl('/pages/member/ke_xiao');
  486. const component=harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
  487. component.setHistoryMonth('2026-09'); await harness.fixture.whenStable(); harness.fixture.detectChanges();
  488. expect(component.earningsSummary()?.amount).toBe(180);
  489. expect(harness.routeNativeElement!.querySelector('.fee-summary-amount')!.textContent).toContain('180.00');
  490. });
  491. it('renders scheduled duration for new lessons without duplicating legacy duration labels', async () => {
  492. user.set({ userId: 300, userName: 'coach', honeyName: '钱老师', groupId: 3 });
  493. session.groupId.set(3);
  494. const harness = await RouterTestingHarness.create('/pages/home/shop');
  495. const center = harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
  496. center.scheduleRange.set('all');
  497. center.schedules.set([
  498. { GeneralID: 1, Title: '可爱同学(单词课)', durationMinutes: 30, bxrq: '2026-10-19', sdsd: '15:00', dszt: 0 },
  499. { GeneralID: 2, Title: '小黄(单词课)', durationMinutes: 60, bxrq: '2026-10-19', sdsd: '19:00', dszt: 0 },
  500. { GeneralID: 3, Title: '熊小俊(60分钟练习)', durationMinutes: 60, bxrq: '2026-10-19', sdsd: '14:00', dszt: 0 },
  501. ]);
  502. harness.fixture.detectChanges();
  503. const titles = Array.from(harness.routeNativeElement!.querySelectorAll('.schedule-copy strong')).map(element => element.textContent?.trim());
  504. expect(titles).toEqual(['熊小俊(60分钟练习)', '可爱同学(单词课) · 30分钟', '小黄(单词课) · 60分钟']);
  505. expect(center.scheduleTitle({ Title: '旧课(60分钟练习)', durationMinutes: 30 })).toBe('旧课(30分钟练习)');
  506. for (const durationMinutes of [undefined, null, 0, -30, 'invalid']) {
  507. expect(center.scheduleTitle({ Title: '旧课(60分钟练习)', durationMinutes })).toBe('旧课(60分钟练习)');
  508. }
  509. });
  510. it('keeps all today tasks cached across navigation and visibility', async () => {
  511. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  512. session.groupId.set(3);
  513. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  514. const originalPost = api.post.bind(api);
  515. const post = spyOn(api, 'post').and.callFake((action, params) => {
  516. if (action !== 'app_review_page') return originalPost(action, params);
  517. return of({ retcode: 1, result: {
  518. items: Array.from({length: 7}, (_, i) => ({ GeneralID: 100+i, yhid: 100, Title: '今日学员', kywsj: params?.['date'], fxzt: i === 6 ? 1 : 0 })),
  519. page: { itemCount: 7, pageCount: 1 }, summary: { total: 7, completed: 1, due: 6, today: 7, income: 0 }, dates: [],
  520. } }) as never;
  521. });
  522. const count = () => post.calls.allArgs().filter(([name]) => name === 'app_review_page').length;
  523. const harness = await RouterTestingHarness.create();
  524. await harness.navigateByUrl('/pages/home/index');
  525. harness.fixture.detectChanges();
  526. expect(harness.routeNativeElement?.querySelectorAll('.coach-memory-list article').length).toBe(7);
  527. expect(harness.routeNativeElement?.querySelectorAll('.coach-memory-footer').length).toBe(1);
  528. expect(harness.routeNativeElement?.textContent).not.toContain('查看今日全部任务');
  529. document.dispatchEvent(new Event('visibilitychange'));
  530. await harness.navigateByUrl('/pages/member/starshop');
  531. await harness.navigateByUrl('/pages/home/index');
  532. harness.fixture.detectChanges();
  533. expect(count()).toBe(1);
  534. expect(harness.routeNativeElement?.querySelector('.coach-memory-state')).toBeNull();
  535. (harness.routeNativeElement?.querySelector('.coach-memory-refresh') as HTMLButtonElement).click();
  536. harness.fixture.detectChanges();
  537. expect(count()).toBe(2);
  538. });
  539. for (const groupId of [1, 3]) {
  540. it(`caches homepage overview for role ${groupId} until an explicit refresh`, async () => {
  541. user.set({ userId: groupId === 3 ? 300 : 100, groupId });
  542. session.groupId.set(groupId);
  543. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  544. const post = spyOn(api, 'post').and.callThrough();
  545. const get = spyOn(api, 'get').and.callThrough();
  546. const count = (action: string) => (action === 'app_account_overview' ? get.calls.allArgs() : post.calls.allArgs()).filter(([name]) => name === action).length;
  547. const harness = await RouterTestingHarness.create();
  548. await harness.navigateByUrl('/pages/home/index');
  549. const first = { stats: count('e_order_tongji'), review: count('app_review_page'), balances: count('app_account_overview') };
  550. if (groupId === 1) expect(get.calls.allArgs().find(([name]) => name === 'app_account_overview')?.[1]).toEqual(jasmine.objectContaining({ profileOnly: true, refresh: true }));
  551. document.dispatchEvent(new Event('visibilitychange'));
  552. await harness.navigateByUrl('/pages/member/starshop');
  553. await harness.navigateByUrl('/pages/home/index');
  554. harness.fixture.detectChanges();
  555. expect(count('e_order_tongji')).toBe(first.stats);
  556. expect(count('app_review_page')).toBe(first.review);
  557. expect(count('app_account_overview')).toBe(first.balances);
  558. expect(harness.routeNativeElement?.textContent).not.toContain('正在同步学习计划');
  559. const button = harness.routeNativeElement?.querySelector(groupId === 3 ? '.coach-hero .coach-refresh' : '.student-home-refresh') as HTMLButtonElement;
  560. button.click();
  561. harness.fixture.detectChanges();
  562. expect(count('e_order_tongji')).toBe(first.stats + 1);
  563. expect(count('app_review_page')).toBe(first.review + (groupId === 1 ? 1 : 0));
  564. expect(count('app_account_overview')).toBe(first.balances + (groupId === 1 ? 1 : 0));
  565. });
  566. }
  567. for (const groupId of [1, 3]) {
  568. it(`caches companion and account tabs for role ${groupId} and refreshes only on request`, async () => {
  569. user.set({ userId: groupId === 3 ? 300 : 100, groupId });
  570. session.groupId.set(groupId);
  571. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  572. const post = spyOn(api, 'post').and.callThrough();
  573. const count = (action: string) => post.calls.allArgs().filter(([name]) => name === action).length;
  574. const harness = await RouterTestingHarness.create();
  575. const route = groupId === 3 ? '/pages/home/shop' : '/pages/home/cart';
  576. await harness.navigateByUrl(route);
  577. await harness.navigateByUrl('/pages/home/ucenter');
  578. const before = { companion: count('app_companion_overview'), account: count('app_account_overview'), versions: count('app_live_versions') };
  579. document.dispatchEvent(new Event('visibilitychange'));
  580. await harness.navigateByUrl(route);
  581. harness.fixture.detectChanges();
  582. expect(count('app_companion_overview')).toBe(before.companion);
  583. expect(harness.routeNativeElement?.querySelector('.center-sync')).toBeNull();
  584. const center = harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
  585. center.showTomorrow();
  586. expect(count('app_companion_overview')).toBe(before.companion + 1);
  587. center.showToday();
  588. expect(count('app_companion_overview')).toBe(before.companion + 1);
  589. center.load(true);
  590. expect(count('app_companion_overview')).toBe(before.companion + 2);
  591. await harness.navigateByUrl('/pages/home/ucenter');
  592. harness.fixture.detectChanges();
  593. expect(count('app_account_overview')).toBe(before.account);
  594. expect(harness.routeNativeElement?.textContent).not.toContain('正在同步...');
  595. expect(harness.routeNativeElement?.querySelector('.account-live-status')).toBeNull();
  596. expect(harness.routeNativeElement?.querySelector('.account-refresh')).toBeNull();
  597. expect(count('app_account_overview')).toBe(before.account);
  598. expect(count('app_live_versions')).toBe(before.versions);
  599. });
  600. }
  601. it('shows only review states to students and keeps pay labels on teacher calendars', async () => {
  602. const harness = await RouterTestingHarness.create('/pages/stu/stu_calendar?scope=overdue');
  603. const calendar = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  604. const today = new Date().toLocaleDateString('sv-SE', {timeZone:'Asia/Shanghai'});
  605. calendar.calendarItems.set([
  606. {GeneralID:1,kywsj:'2000-01-01',kywrq:'2000-01-01',fxzt:0},
  607. {GeneralID:2,kywsj:today,kywrq:today,fxzt:0},
  608. {GeneralID:3,kywsj:'2999-01-01',kywrq:'2999-01-01',fxzt:0},
  609. {GeneralID:4,kywsj:'2000-01-01',kywrq:'2000-01-01',fxzt:1},
  610. ]);
  611. const states = () => Array.from(harness.routeNativeElement!.querySelectorAll('.task-state')).map(node => node.textContent!.trim());
  612. harness.fixture.detectChanges();
  613. expect(states()).toEqual(['逾期补做','待复习','未到期','已完成']);
  614. expect(harness.routeNativeElement!.querySelector('.memory-date-tasks h2')?.textContent).toBe('逾期补做');
  615. expect(harness.routeNativeElement!.textContent).not.toMatch(/计薪|记薪|费用|薪酬|收入/);
  616. user.set({userId:300,groupId:3});session.groupId.set(3);harness.fixture.detectChanges();
  617. expect(states()).toEqual(['逾期补做 · 不计薪','待复习 · 当天完成计薪','未到期','已完成']);
  618. expect(harness.routeNativeElement!.querySelector('.memory-date-tasks h2')?.textContent).toBe('逾期补做 · 不计薪');
  619. user.set({userId:100,groupId:1});session.groupId.set(1);harness.fixture.detectChanges();
  620. expect(harness.routeNativeElement!.textContent).not.toMatch(/计薪|记薪|费用|薪酬|收入/);
  621. });
  622. it('loads the review calendar once per login and refreshes only on an explicit request', async () => {
  623. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  624. const originalPost = api.post.bind(api);
  625. const post = spyOn(api, 'post').and.callFake((action, params) => originalPost(action, params));
  626. const count = (action: string) => post.calls.allArgs().filter(([name]) => name === action).length;
  627. const harness = await RouterTestingHarness.create();
  628. await harness.navigateByUrl('/pages/stu/stu_calendar');
  629. harness.fixture.detectChanges();
  630. expect(count('app_review_page')).toBe(1);
  631. expect(count('app_live_versions')).toBe(0);
  632. await harness.navigateByUrl('/pages/member/starshop');
  633. await harness.navigateByUrl('/pages/stu/stu_calendar');
  634. harness.fixture.detectChanges();
  635. expect(count('app_review_page')).toBe(1);
  636. const calendar = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  637. calendar.retryCalendar();
  638. harness.fixture.detectChanges();
  639. expect(count('app_review_page')).toBe(2);
  640. await harness.navigateByUrl('/pages/member/starshop');
  641. session.token.set('next-login-token');
  642. await harness.navigateByUrl('/pages/stu/stu_calendar');
  643. harness.fixture.detectChanges();
  644. expect(count('app_review_page')).toBe(3);
  645. session.token.set('test-token');
  646. });
  647. it('silently reveals pending and completed words opened from student learning content', async () => {
  648. const play = spyOn(TestBed.inject(PlatformService), 'play');
  649. const harness = await RouterTestingHarness.create();
  650. await harness.navigateByUrl('/pages/his/his');
  651. (harness.routeNativeElement?.querySelector('.current-learning-list button') as HTMLButtonElement).click();
  652. await harness.fixture.whenStable();
  653. harness.fixture.detectChanges();
  654. (harness.routeNativeElement?.querySelector('.node-list button') as HTMLButtonElement).click();
  655. await harness.fixture.whenStable();
  656. harness.fixture.detectChanges();
  657. expect(TestBed.inject(Router).url).toContain('readonly=1');
  658. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  659. for (const [index, meaning] of ['n. 香蕉', 'n. 苹果'].entries()) {
  660. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[index] as HTMLButtonElement).click();
  661. harness.fixture.detectChanges();
  662. expect(harness.routeNativeElement?.querySelector('.audio')).toBeNull();
  663. expect(harness.routeNativeElement?.textContent).not.toContain('读音');
  664. const word = harness.routeNativeElement?.querySelector('.word-reveal') as HTMLButtonElement;
  665. word.click();
  666. harness.fixture.detectChanges();
  667. expect(word.textContent).toContain(meaning);
  668. expect(word.getAttribute('aria-expanded')).toBe('true');
  669. word.click();
  670. harness.fixture.detectChanges();
  671. expect(word.getAttribute('aria-expanded')).toBe('false');
  672. }
  673. learning.words().forEach((word) => learning.play(word));
  674. expect(play).not.toHaveBeenCalled();
  675. });
  676. it('pages through all words in a history record without requesting a course unit', async () => {
  677. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  678. const originalPost = api.post.bind(api);
  679. const post = spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
  680. ? of({ retcode: 1, result: Array.from({ length: 31 }, (_, index) => ({
  681. GeneralID: 700 + index,
  682. Title: `history-${index + 1}`,
  683. detail: [{ GeneralID: 700 + index, Title: `history-${index + 1}`, sy: `释义 ${index + 1}` }],
  684. })), addon: [] } as ApiEnvelope<any>)
  685. : originalPost(action, params));
  686. const get = spyOn(api, 'get').and.callThrough();
  687. const harness = await RouterTestingHarness.create();
  688. await harness.navigateByUrl('/pages/his/his_words?id=201');
  689. harness.fixture.detectChanges();
  690. const list = () => harness.routeNativeElement?.querySelectorAll('.readonly-word-list article') ?? [];
  691. expect(list().length).toBe(30);
  692. expect(harness.routeNativeElement?.textContent).toContain('共 31 个单词');
  693. (harness.routeNativeElement?.querySelector('.word-preview-pagination .page-direction:last-of-type') as HTMLButtonElement).click();
  694. await harness.fixture.whenStable();
  695. harness.fixture.detectChanges();
  696. expect(list().length).toBe(1);
  697. expect(list()[0].textContent).toContain('history-31');
  698. expect(harness.routeNativeElement?.textContent).toContain('2 / 2 页');
  699. expect(get.calls.allArgs().some(([action]) => action === 'e_ck_list')).toBeFalse();
  700. expect(post.calls.allArgs().filter(([action]) => action === 'e_record_detail').length).toBe(1);
  701. (harness.routeNativeElement?.querySelector('.word-preview-pagination .page-direction:first-child') as HTMLButtonElement).click();
  702. await harness.fixture.whenStable();
  703. harness.fixture.detectChanges();
  704. expect(list().length).toBe(30);
  705. expect(list()[0].textContent).toContain('history-1');
  706. });
  707. it('plays student history words on click without changing learning records or enabling unit preview audio', async () => {
  708. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  709. api.historyWordAudio = 'apple.mp3';
  710. const post = spyOn(api, 'post').and.callThrough();
  711. const platform = TestBed.inject(PlatformService);
  712. const play = spyOn(platform, 'play').and.resolveTo('played');
  713. const stopAudio = spyOn(platform, 'stopAudio');
  714. const harness = await RouterTestingHarness.create();
  715. await harness.navigateByUrl('/pages/his/his');
  716. (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
  717. await harness.fixture.whenStable();
  718. harness.fixture.detectChanges();
  719. expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
  720. expect(play).not.toHaveBeenCalled();
  721. post.calls.reset();
  722. const button = harness.routeNativeElement?.querySelector('.history-word-audio') as HTMLButtonElement;
  723. expect(button.disabled).toBeFalse();
  724. expect(button.getAttribute('aria-label')).toBe('播放单词读音:apple');
  725. expect(harness.routeNativeElement?.querySelector('.readonly-word-list')?.textContent).not.toContain('苹果');
  726. button.querySelector('strong')!.click();
  727. await harness.fixture.whenStable();
  728. harness.fixture.detectChanges();
  729. expect(harness.routeNativeElement?.querySelector('.readonly-word-list')?.textContent).not.toContain('苹果');
  730. play.calls.mostRecent().args[2]!.onEnded();
  731. harness.fixture.detectChanges();
  732. expect(harness.routeNativeElement?.querySelector('.readonly-word-list')?.textContent).toContain('苹果');
  733. (button.querySelector('lucide-icon') as HTMLElement).click();
  734. expect(play).toHaveBeenCalledTimes(2);
  735. expect(play.calls.mostRecent().args[0]).toContain('apple.mp3');
  736. expect(post).not.toHaveBeenCalled();
  737. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  738. learning.words.update((words) => words.map((word) => ({ ...word, audio: '' })));
  739. harness.fixture.detectChanges();
  740. expect(button.disabled).toBeFalse();
  741. expect(harness.routeNativeElement?.textContent).toContain('点击生成读音');
  742. button.click();
  743. expect(play).toHaveBeenCalledTimes(2);
  744. stopAudio.calls.reset();
  745. await harness.navigateByUrl('/pages/home/index');
  746. expect(stopAudio).toHaveBeenCalled();
  747. await harness.navigateByUrl('/pages/stu/stu_con?nid=811&readonly=1');
  748. expect(harness.routeNativeElement?.querySelector('.history-word-audio')).toBeNull();
  749. const preview = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  750. preview.words().forEach((word) => preview.play(word));
  751. expect(play).toHaveBeenCalledTimes(2);
  752. });
  753. it('prepares listening choices during matching and reuses them when advancing', async () => {
  754. const prefix = 'xiaoshu.learning.100.100.practice.';
  755. const words = [{GeneralID:1001,Title:'apple',sy:'苹果'},{GeneralID:1002,Title:'banana',sy:'香蕉'}];
  756. localStorage.setItem(prefix+'learn_mode','newword');
  757. localStorage.setItem(prefix+'choose_newword_learn',JSON.stringify(words));
  758. localStorage.setItem(prefix+'_page_word_orilist',JSON.stringify([words]));
  759. localStorage.setItem(prefix+'_page_current_learn','1');
  760. const response = new Subject<ApiEnvelope<any>>();
  761. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  762. const get = api.get.bind(api);
  763. let count = 0;
  764. spyOn(api,'get').and.callFake((action,params) => {
  765. if (action==='content_list' && params?.['orders']==='NEWID()') {count++;return response;}
  766. return get(action,params);
  767. });
  768. spyOn(TestBed.inject(PlatformService),'play');
  769. const harness = await RouterTestingHarness.create();
  770. await harness.navigateByUrl('/pages/stu/stu3');
  771. expect(harness.routeNativeElement?.querySelector('.match-grid')).not.toBeNull();
  772. expect(count).toBe(1);
  773. response.next({retcode:1,result:[{GeneralID:301,Title:'cat',sy:'猫'},{GeneralID:302,Title:'dog',sy:'狗'},{GeneralID:303,Title:'bird',sy:'鸟'}]});
  774. response.complete();
  775. await harness.navigateByUrl('/pages/stu/stu4');
  776. expect(count).toBe(1);
  777. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  778. expect(learning.choicesLoading()).toBeFalse();
  779. expect(harness.routeNativeElement?.querySelectorAll('.option-list button').length).toBe(4);
  780. });
  781. it('keeps the spoken word among listening choices and discards answers from an earlier question', async () => {
  782. const prefix = 'xiaoshu.learning.100.100.practice.';
  783. const selectedWords = [
  784. { GeneralID: 1001, Title: 'apple', sy: '苹果', yp: 'apple.mp3' },
  785. { GeneralID: 1002, Title: 'banana', sy: '香蕉', yp: 'banana.mp3' },
  786. ];
  787. localStorage.setItem(prefix + 'learn_mode', 'newword');
  788. localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify(selectedWords));
  789. localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([selectedWords]));
  790. localStorage.setItem(prefix + '_page_current_learn', '1');
  791. const responses = [new Subject<ApiEnvelope<any>>(), new Subject<ApiEnvelope<any>>()];
  792. let requestCount = 0;
  793. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  794. const get = api.get.bind(api);
  795. spyOn(api, 'get').and.callFake((action, params) => action === 'content_list' && params?.['orders'] === 'NEWID()'
  796. ? responses[requestCount++] ?? of({ retcode: 1, result: [] } as ApiEnvelope<any>)
  797. : get(action, params));
  798. spyOn(TestBed.inject(PlatformService), 'play');
  799. const harness = await RouterTestingHarness.create();
  800. await harness.navigateByUrl('/pages/stu/stu4');
  801. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  802. const firstWord = learning.current()!;
  803. const firstResponse = responses[0];
  804. expect(requestCount).toBe(1);
  805. expect(learning.choicesLoading()).toBeTrue();
  806. learning.chooseMeaning(firstWord);
  807. expect(learning.current()).toBe(firstWord); // Cannot answer while options are loading.
  808. firstResponse?.next({ retcode: 1, result: Array.from({ length: 8 }, (_, index) => ({
  809. GeneralID: 301 + index, Title: `extra-${index}`, sy: `干扰项 ${index}`,
  810. })) });
  811. expect(learning.choiceOptions().length).toBe(4);
  812. expect(learning.choiceOptions().filter(option => Number(option.id) >= 301).length).toBeGreaterThanOrEqual(2);
  813. learning.chooseMeaning(firstWord);
  814. const secondWord = learning.current()!;
  815. expect(secondWord.id).not.toBe(firstWord.id);
  816. expect(requestCount).toBe(1); // Reuse the pool instead of requesting each question.
  817. firstResponse?.next({ retcode: 1, result: [{ GeneralID: 999, Title: 'stale', sy: '迟到结果' }] });
  818. expect(learning.choiceOptions().length).toBe(4);
  819. expect(learning.choiceOptions().some(option => option.id === '999')).toBeFalse();
  820. expect(learning.choiceOptions().some(option => option.id === secondWord.id)).toBeTrue();
  821. localStorage.removeItem(prefix + 'learn_mode');
  822. localStorage.removeItem(prefix + 'choose_newword_learn');
  823. localStorage.removeItem(prefix + '_page_word_orilist');
  824. localStorage.removeItem(prefix + '_page_current_learn');
  825. });
  826. it('lets a student study selected words from their wordbook while keeping course stages teacher-led', async () => {
  827. localStorage.removeItem('xiaoshu.learning.100.100.practice.learn_mode');
  828. localStorage.removeItem('xiaoshu.learning.100.100.practice.choose_newword_learn');
  829. const harness = await RouterTestingHarness.create();
  830. const router = TestBed.inject(Router);
  831. await harness.navigateByUrl('/pages/member/starshop');
  832. (harness.routeNativeElement?.querySelector('.word-select-list > button') as HTMLButtonElement).click();
  833. (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  834. await harness.fixture.whenStable();
  835. harness.fixture.detectChanges();
  836. const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  837. expect(router.url).toContain('/pages/stu/stu_con');
  838. expect(learning().words().map((word) => word.word)).toEqual(['tend']);
  839. learning().skipStudyList();
  840. await harness.fixture.whenStable();
  841. harness.fixture.detectChanges();
  842. expect(router.url).toContain('/pages/stu/stu3');
  843. expect(learning().words().map((word) => word.word)).toEqual(['tend']);
  844. learning().chooseMatch('left', learning().words()[0]);
  845. learning().chooseMatch('right', learning().words()[0]);
  846. learning().continueAfterStage();
  847. await harness.fixture.whenStable();
  848. harness.fixture.detectChanges();
  849. expect(router.url).toContain('/pages/stu/stu4');
  850. expect(learning().words().map((word) => word.word)).toEqual(['tend']);
  851. learning().chooseMeaning(learning().words()[0]);
  852. learning().continueAfterStage();
  853. await harness.fixture.whenStable();
  854. harness.fixture.detectChanges();
  855. expect(router.url).toContain('/pages/stu/stu5');
  856. for (const letter of learning().current()!.word) {
  857. const index = learning().letters().findIndex((choice) => !choice.used && choice.value === letter);
  858. expect(index).toBeGreaterThanOrEqual(0);
  859. learning().spellLetter(index);
  860. }
  861. learning().nextSpellingWord();
  862. learning().continueAfterStage();
  863. await harness.fixture.whenStable();
  864. expect(router.url).toBe('/pages/member/starshop');
  865. expect(localStorage.getItem('xiaoshu.learning.100.100.practice.learn_mode')).toBeNull();
  866. await harness.navigateByUrl('/pages/stu/stu_con?nids=811&pnid=801');
  867. await harness.fixture.whenStable();
  868. expect(router.url).toBe('/pages/home/cart');
  869. });
  870. it('lets a teacher open a student wordbook, switch learners and save practice for the selected learner', async () => {
  871. user.set({userId:300, userName:'coach', honeyName:'老师', groupId:3});
  872. session.groupId.set(3);
  873. selectedStudent.set({userId:888, honeyName:'正在排课的学员', groupId:1});
  874. spyOn(TestBed.inject(PlatformService), 'play').and.resolveTo('played');
  875. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  876. const get = api.get.bind(api);
  877. const pendingFirstLearner = new Subject<ApiEnvelope<any>>();
  878. const words = (uid: number, completed = false) => ({
  879. retcode:1, result:[{GeneralID:uid, xxcs:completed ? 2 : 1,
  880. detail:[{GeneralID:uid+700, Title:uid===100 ? 'apple' : 'banana', sy:uid===100 ? '苹果' : '香蕉', yp:'/UploadFiles/test.mp3'}]}],
  881. page:{itemCount:1, pendingCount:completed ? 0 : 1, completedCount:completed ? 1 : 0},
  882. });
  883. const read = spyOn(api, 'get').and.callFake((action, params): Observable<ApiEnvelope<any>> => {
  884. if (action === 'e_user_list') return of({retcode:1, result:[{userId:100, honeyName:'学员甲'}, {userId:101, honeyName:'学员乙'}]});
  885. if (action !== 'e_words_list') return get(action, params);
  886. const uid = Number(params?.['uid']);
  887. const completed = params?.['learningStatus'] === 'completed';
  888. if (uid === 100 && completed) return pendingFirstLearner;
  889. const saved = uid === 101 && api.lastLearningWordUpdate['save'] === 1;
  890. if (saved !== completed) return of({retcode:1, result:[], page:{itemCount:0, pendingCount:saved ? 0 : 1, completedCount:saved ? 1 : 0}});
  891. return of(words(uid, saved));
  892. });
  893. const harness = await RouterTestingHarness.create();
  894. const router = TestBed.inject(Router);
  895. const page = () => harness.routeNativeElement!;
  896. const stage = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  897. const settled = async () => { await harness.fixture.whenStable(); harness.fixture.detectChanges(); };
  898. await harness.navigateByUrl('/pages/home/index');
  899. (page().querySelector('.coach-wordbook-entry') as HTMLAnchorElement).click();
  900. await settled();
  901. expect(router.url).toBe('/pages/member/starshop');
  902. expect(read).toHaveBeenCalledWith('e_user_list', jasmine.objectContaining({scope:'wordbook'}));
  903. expect(page().querySelector('.word-select-list')?.textContent).toContain('apple');
  904. expect(page().querySelector('.danger-button')).toBeNull();
  905. (page().querySelector('.word-select-list button') as HTMLButtonElement).click();
  906. (page().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  907. const picker = page().querySelector<HTMLSelectElement>('#wordbook-student')!;
  908. picker.value = '101';
  909. picker.dispatchEvent(new Event('change'));
  910. pendingFirstLearner.next(words(100, true));
  911. await settled();
  912. expect(page().querySelector('.word-select-list')?.textContent).toContain('banana');
  913. expect(page().querySelector('.word-select-list')?.textContent).not.toContain('apple');
  914. expect(stage().selected().size).toBe(0);
  915. expect(selectedStudent()?.userId).toBe(888);
  916. (page().querySelector('.word-select-list button') as HTMLButtonElement).click();
  917. await settled();
  918. (page().querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  919. await settled();
  920. expect(router.url).toBe('/pages/stu/stu_con?wordbookStudentId=101');
  921. expect(stage().words().map(word=>word.word)).toEqual(['banana']);
  922. stage().skipStudyList();
  923. await settled();
  924. expect(router.url).toBe('/pages/stu/stu3?wordbookStudentId=101');
  925. stage().chooseMatch('left', stage().words()[0]);
  926. stage().chooseMatch('right', stage().words()[0]);
  927. stage().continueAfterStage();
  928. await settled();
  929. stage().chooseMeaning(stage().words()[0]);
  930. stage().continueAfterStage();
  931. await settled();
  932. expect(router.url).toBe('/pages/stu/pl_stu5?wordbookStudentId=101');
  933. stage().skipSpellingStage();
  934. await settled();
  935. expect(api.lastLearningWordUpdate).toEqual(jasmine.objectContaining({uid:101, scope:'wordbook', wordsId:'801', save:1}));
  936. expect(router.url).toBe('/pages/member/starshop?wordbookStudentId=101');
  937. expect(page().querySelector<HTMLSelectElement>('#wordbook-student')?.value).toBe('101');
  938. expect(selectedStudent()?.userId).toBe(888);
  939. (page().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  940. await settled();
  941. expect(page().querySelector('.completed-column')?.textContent).toContain('banana');
  942. }, 15000);
  943. it('separates unlearned and learned wordbook words while keeping selections across tabs', async () => {
  944. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  945. const get = api.get.bind(api);
  946. spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
  947. ? of({ retcode: 1, result: params?.['learningStatus'] === 'completed'
  948. ? [{ GeneralID: 602, Title: 'prepare@张雅茜', xxcs: 2, detail: [{ GeneralID: 702, Title: 'prepare', sy: '准备' }] }]
  949. : [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 1, detail: [{ GeneralID: 701, Title: 'tend', sy: '照顾' }] }],
  950. page: { itemCount: 1, pendingCount: 1, completedCount: 1, pageCount: 1, pageIndex: 1, pageSize: 30 } } as ApiEnvelope<any>)
  951. : get(action, params));
  952. const harness = await RouterTestingHarness.create();
  953. await harness.navigateByUrl('/pages/member/starshop');
  954. harness.fixture.detectChanges();
  955. const tabs = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.word-selection-tabs button') ?? [];
  956. expect(tabs[0].textContent).toContain('未学习');
  957. expect(tabs[0].textContent).toContain('1');
  958. expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('tend');
  959. (harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button') as HTMLButtonElement).click();
  960. tabs[1].click();
  961. harness.fixture.detectChanges();
  962. expect(tabs[1].textContent).toContain('已学习');
  963. expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('prepare');
  964. (harness.routeNativeElement?.querySelector('.completed-column .word-select-list > button') as HTMLButtonElement).click();
  965. harness.fixture.detectChanges();
  966. expect(harness.routeNativeElement?.querySelector('.selection-header strong')?.textContent).toContain('已选 2 个单词');
  967. tabs[0].click();
  968. harness.fixture.detectChanges();
  969. expect(harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button.selected')).not.toBeNull();
  970. });
  971. for (const legacy of [false, true]) {
  972. it(`selects wordbook words independently when practice IDs repeat (${legacy ? 'legacy' : 'paged'} response)`, async () => {
  973. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  974. const get = api.get.bind(api);
  975. const pending = Array.from({ length: 35 }, (_, index) => ({
  976. GeneralID: 601,
  977. scid: 701 + index,
  978. xxcs: 1,
  979. detail: [{ GeneralID: 701 + index, Title: `word-${index + 1}`, yp: 'word.mp3' }],
  980. }));
  981. const completed = [{ GeneralID: 601, scid: 801, xxcs: 2, detail: [{ GeneralID: 801, Title: 'done' }] }];
  982. spyOn(api, 'get').and.callFake((action, params) => {
  983. if (action !== 'e_words_list') return get(action, params);
  984. const rows = legacy ? [...pending, ...completed] : params?.['learningStatus'] === 'completed' ? completed : pending;
  985. const page = Number(params?.['cpage']);
  986. const size = Number(params?.['psize']);
  987. return of({ retcode: 1, result: rows.slice((page - 1) * size, page * size), page: {
  988. itemCount: rows.length, pageCount: Math.ceil(rows.length / size), pageIndex: page, pageSize: size,
  989. ...(!legacy ? { pendingCount: pending.length, completedCount: completed.length } : {}),
  990. } } as ApiEnvelope<any>);
  991. });
  992. const harness = await RouterTestingHarness.create();
  993. await harness.navigateByUrl('/pages/member/starshop');
  994. const view = () => harness.routeNativeElement!;
  995. const rows = () => view().querySelectorAll<HTMLButtonElement>('.word-select-list > button');
  996. const selected = () => Array.from(view().querySelectorAll('.word-select-list > button.selected strong'), node => node.textContent);
  997. const click = (element: HTMLElement) => { element.click(); harness.fixture.detectChanges(); };
  998. const expectCount = (count: number) => expect(view().querySelector('.selection-header strong')?.textContent).toContain(`已选 ${count} 个单词`);
  999. click(rows()[3]);
  1000. expect(selected()).toEqual(['word-4']);
  1001. expectCount(1);
  1002. click(rows()[1]);
  1003. expect(selected()).toEqual(['word-2', 'word-4']);
  1004. click(rows()[3]);
  1005. expect(selected()).toEqual(['word-2']);
  1006. click(rows()[1].querySelector('.audio') as HTMLElement);
  1007. expect(selected()).toEqual(['word-2']);
  1008. click(view().querySelectorAll<HTMLButtonElement>('.mobile-pagination button')[1]);
  1009. click(rows()[0]);
  1010. expect(selected()).toEqual(['word-31']);
  1011. expectCount(2);
  1012. click(view().querySelectorAll<HTMLButtonElement>('.word-selection-tabs button')[1]);
  1013. expect(selected()).toEqual([]);
  1014. click(rows()[0]);
  1015. expectCount(3);
  1016. click(view().querySelectorAll<HTMLButtonElement>('.word-selection-tabs button')[0]);
  1017. expect(selected()).toEqual(['word-2']);
  1018. click(view().querySelector('.selection-header .primary-button') as HTMLButtonElement);
  1019. await harness.fixture.whenStable();
  1020. harness.fixture.detectChanges();
  1021. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1022. expect(learning.words().map(word => word.word)).toEqual(['word-2', 'word-31', 'done']);
  1023. expect(new Set(learning.words().map(word => word.id)).size).toBe(3);
  1024. learning.leave();
  1025. await harness.fixture.whenStable();
  1026. });
  1027. }
  1028. it('deletes only the selected vocabulary ID when a wordbook detail uses scid as its identity', async () => {
  1029. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1030. const get = api.get.bind(api);
  1031. spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
  1032. ? of({ retcode: 1, result: [
  1033. { GeneralID: 601, scid: 701, xxcs: 1, detail: [{ GeneralID: 701, Title: 'first' }] },
  1034. { GeneralID: 601, scid: 702, xxcs: 1, detail: { Title: 'second' } },
  1035. ], page: { itemCount: 2, pendingCount: 2, completedCount: 0, pageCount: 1, pageIndex: 1, pageSize: 30 } } as ApiEnvelope<any>)
  1036. : get(action, params));
  1037. const post = spyOn(api, 'post').and.callThrough();
  1038. const harness = await RouterTestingHarness.create();
  1039. await harness.navigateByUrl('/pages/member/starshop');
  1040. const view = harness.routeNativeElement!;
  1041. view.querySelectorAll<HTMLButtonElement>('.word-select-list > button')[1].click();
  1042. harness.fixture.detectChanges();
  1043. expect(view.querySelectorAll('.word-select-list > button.selected').length).toBe(1);
  1044. (view.querySelector('.danger-button') as HTMLButtonElement).click();
  1045. expect(post).toHaveBeenCalledWith('e_add_words', jasmine.objectContaining({ uid: 100, wordsId: '702', ifnew: 0 }));
  1046. });
  1047. for (const role of [1,3]) {
  1048. it(`reveals a wordbook meaning only after completed pronunciation for role ${role}`,async()=>{
  1049. user.set({userId:role===3?300:100,groupId:role});session.groupId.set(role);
  1050. const api=TestBed.inject(ApiService),original=api.get.bind(api);
  1051. spyOn(api,'get').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  1052. if(action==='e_user_list')return of({retcode:0,result:[{userId:100,honeyName:'学员甲'},{userId:101,honeyName:'学员乙'}]});
  1053. if(action==='e_words_list')return of({retcode:0,result:[{GeneralID:601,xxcs:params['learningStatus']==='completed'?2:1,detail:[{GeneralID:701,Title:'apple',sy:'苹果',yp:'apple.mp3'}]},{GeneralID:602,xxcs:params['learningStatus']==='completed'?2:1,detail:[{GeneralID:702,Title:'banana',sy:'香蕉',yp:'banana.mp3'}]}],...(role===3?{page:{itemCount:2,pendingCount:2,completedCount:2}}:{})});
  1054. return original(action,params);
  1055. }) as typeof api.get);
  1056. const platform=TestBed.inject(PlatformService),play=spyOn(platform,'play').and.resolveTo('played');spyOn(platform,'toast');
  1057. const harness=await RouterTestingHarness.create('/pages/member/starshop');await harness.fixture.whenStable();harness.fixture.detectChanges();
  1058. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1059. const rows=()=>harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('.word-select-list > button');
  1060. const meanings=()=>Array.from(harness.routeNativeElement!.querySelectorAll('.word-select-list small'),node=>node.textContent);
  1061. expect(meanings()).toEqual([]);
  1062. rows()[0].click();await harness.fixture.whenStable();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
  1063. const old=play.calls.mostRecent().args[2]!;expect(old).toBeDefined();if(!old)return;
  1064. rows()[1].click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  1065. old.onEnded();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
  1066. play.calls.mostRecent().args[2]!.onError?.();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
  1067. rows()[0].querySelector<HTMLElement>('.audio')!.click();await harness.fixture.whenStable();
  1068. play.calls.mostRecent().args[2]!.onEnded();harness.fixture.detectChanges();expect(meanings()).toEqual(['苹果']);
  1069. expect(component.selected().size).toBe(2);
  1070. component.load();await harness.fixture.whenStable();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
  1071. rows()[0].click();await harness.fixture.whenStable();const late=play.calls.mostRecent().args[2]!;
  1072. if(role===3)component.selectWordbookStudent(101);else {component.selectNewWordBucket('completed');component.selectNewWordBucket('pending');}
  1073. await harness.fixture.whenStable();late.onEnded();harness.fixture.detectChanges();expect(meanings()).toEqual([]);
  1074. });
  1075. }
  1076. it('pronounces a wordbook word on row click and only once on speaker click', async () => {
  1077. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1078. const get = api.get.bind(api);
  1079. spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
  1080. ? of({ retcode: 1, result: [{ GeneralID: 601, xxcs: 1, detail: [{ GeneralID: 701, Title: 'tend', yp: 'UploadFiles/tend.mp3' }] }],
  1081. page: { itemCount: 1, pageCount: 1, pageIndex: 1, pageSize: Number(params?.['psize']) } } as ApiEnvelope<any>)
  1082. : get(action, params));
  1083. const play = spyOn(TestBed.inject(PlatformService), 'play');
  1084. const harness = await RouterTestingHarness.create();
  1085. await harness.navigateByUrl('/pages/member/starshop');
  1086. harness.fixture.detectChanges();
  1087. const row = harness.routeNativeElement?.querySelector('.pending-column .word-select-list > button') as HTMLButtonElement;
  1088. row.querySelector('strong')!.click();
  1089. harness.fixture.detectChanges();
  1090. expect(row.classList.contains('selected')).toBeTrue();
  1091. expect(play).toHaveBeenCalledTimes(1);
  1092. expect(play.calls.mostRecent().args[0]).toBe('UploadFiles/tend.mp3');
  1093. expect(play.calls.mostRecent().args[0]).not.toContain('UploadFiles/UploadFiles');
  1094. (row.querySelector('.audio') as HTMLElement).click();
  1095. harness.fixture.detectChanges();
  1096. expect(play).toHaveBeenCalledTimes(2);
  1097. expect(row.classList.contains('selected')).toBeTrue();
  1098. });
  1099. it('shows 30 wordbook words per page while counting every learning status', async () => {
  1100. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1101. const get = api.get.bind(api);
  1102. const pending = Array.from({ length: 65 }, (_, index) => ({ GeneralID: 601 + index, xxcs: 1, detail: [{ GeneralID: 701 + index, Title: `pending-${index + 1}` }] }));
  1103. const completed = Array.from({ length: 7 }, (_, index) => ({ GeneralID: 801 + index, xxcs: 2, detail: [{ GeneralID: 901 + index, Title: `completed-${index + 1}` }] }));
  1104. const requests: Record<string, unknown>[] = [];
  1105. spyOn(api, 'get').and.callFake((action, params) => {
  1106. if (action !== 'e_words_list') return get(action, params);
  1107. requests.push(params ?? {});
  1108. const rows = params?.['learningStatus'] === 'completed' ? completed : pending;
  1109. const page = Number(params?.['cpage']);
  1110. const size = Number(params?.['psize']);
  1111. return of({ retcode: 1, result: rows.slice((page - 1) * size, page * size),
  1112. page: { itemCount: rows.length, pendingCount: pending.length, completedCount: completed.length,
  1113. pageCount: Math.ceil(rows.length / size), pageIndex: page, pageSize: size } } as ApiEnvelope<any>);
  1114. });
  1115. const harness = await RouterTestingHarness.create();
  1116. await harness.navigateByUrl('/pages/member/starshop');
  1117. harness.fixture.detectChanges();
  1118. const view = () => harness.routeNativeElement!;
  1119. const rows = () => view().querySelectorAll('.pending-column .word-select-list > button');
  1120. expect(requests[0]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', cpage: 1, psize: 30 }));
  1121. expect(rows().length).toBe(30);
  1122. expect(view().querySelectorAll('.word-selection-tabs b')[0].textContent).toContain('65');
  1123. expect(view().querySelectorAll('.word-selection-tabs b')[1].textContent).toContain('7');
  1124. (rows()[0] as HTMLButtonElement).click();
  1125. (view().querySelectorAll('.mobile-pagination button')[1] as HTMLButtonElement).click();
  1126. harness.fixture.detectChanges();
  1127. expect(requests[1]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', cpage: 2, psize: 30 }));
  1128. expect(rows().length).toBe(30);
  1129. expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 2 / 3 页');
  1130. (view().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  1131. harness.fixture.detectChanges();
  1132. expect(requests[2]).toEqual(jasmine.objectContaining({ learningStatus: 'completed', cpage: 1, psize: 30 }));
  1133. expect(view().querySelectorAll('.completed-column .word-select-list > button').length).toBe(7);
  1134. expect(view().querySelector('.selection-header strong')?.textContent).toContain('已选 1 个单词');
  1135. });
  1136. it('keeps wordbook counts and rows correct when the server only returns the old mixed list', async () => {
  1137. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1138. const get = api.get.bind(api);
  1139. const all = Array.from({ length: 139 }, (_, index) => ({
  1140. GeneralID: 601 + index,
  1141. xxcs: 1,
  1142. detail: [{ GeneralID: 701 + index, Title: `word-${index + 1}` }],
  1143. }));
  1144. const requests: Record<string, unknown>[] = [];
  1145. spyOn(api, 'get').and.callFake((action, params) => {
  1146. if (action !== 'e_words_list') return get(action, params);
  1147. requests.push(params ?? {});
  1148. const page = Number(params?.['cpage']);
  1149. const size = Number(params?.['psize']);
  1150. return of({ retcode: 1, result: all.slice((page - 1) * size, page * size),
  1151. page: { itemCount: all.length, pageCount: Math.ceil(all.length / size), pageIndex: page, pageSize: size } } as ApiEnvelope<any>);
  1152. });
  1153. const harness = await RouterTestingHarness.create();
  1154. await harness.navigateByUrl('/pages/member/starshop');
  1155. harness.fixture.detectChanges();
  1156. const view = () => harness.routeNativeElement!;
  1157. expect(requests.length).toBe(2);
  1158. expect(requests[0]).toEqual(jasmine.objectContaining({ learningStatus: 'pending', psize: 30 }));
  1159. expect(requests[1]).toEqual(jasmine.objectContaining({ cpage: 1, psize: 500 }));
  1160. expect(view().querySelectorAll('.word-selection-tabs b')[0].textContent).toContain('139');
  1161. expect(view().querySelectorAll('.word-selection-tabs b')[1].textContent).toContain('0');
  1162. expect(view().querySelectorAll('.pending-column .word-select-list > button').length).toBe(30);
  1163. expect(view().querySelector('.pending-column .word-select-list > button')?.textContent).toContain('word-1');
  1164. expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 1 / 5 页 · 共 139 个单词');
  1165. (view().querySelectorAll('.mobile-pagination button')[1] as HTMLButtonElement).click();
  1166. harness.fixture.detectChanges();
  1167. expect(view().querySelector('.mobile-pagination')?.textContent).toContain('第 2 / 5 页');
  1168. (view().querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  1169. harness.fixture.detectChanges();
  1170. expect(view().querySelectorAll('.completed-column .word-select-list > button').length).toBe(0);
  1171. expect(requests.length).toBe(2);
  1172. });
  1173. it('saves completed wordbook study before showing the word in the learned tab', async () => {
  1174. const prefix = 'xiaoshu.learning.100.100.practice.';
  1175. const word = { GeneralID: 701, Title: 'tend', sy: '照顾' };
  1176. localStorage.setItem(prefix + 'learn_mode', JSON.stringify('newword'));
  1177. localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify([word]));
  1178. localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([[word]]));
  1179. localStorage.setItem(prefix + '_page_current_learn', JSON.stringify(1));
  1180. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1181. const get = api.get.bind(api);
  1182. spyOn(api, 'get').and.callFake((action, params) => action === 'e_words_list'
  1183. ? of({ retcode: 1, result: api.lastLearningWordUpdate['save'] === 1 && params?.['learningStatus'] === 'completed'
  1184. ? [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 2, detail: [word] }]
  1185. : api.lastLearningWordUpdate['save'] === 1 ? [] : [{ GeneralID: 601, Title: 'tend@张雅茜', xxcs: 1, detail: [word] }],
  1186. page: { itemCount: params?.['learningStatus'] === 'completed' ? 1 : api.lastLearningWordUpdate['save'] === 1 ? 0 : 1,
  1187. pendingCount: api.lastLearningWordUpdate['save'] === 1 ? 0 : 1, completedCount: api.lastLearningWordUpdate['save'] === 1 ? 1 : 0,
  1188. pageCount: 1, pageIndex: 1, pageSize: 30 } } as ApiEnvelope<any>)
  1189. : get(action, params));
  1190. const harness = await RouterTestingHarness.create();
  1191. const router = TestBed.inject(Router);
  1192. await harness.navigateByUrl('/pages/stu/stu5');
  1193. const learning = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1194. learning.skipSpellingStage();
  1195. await harness.fixture.whenStable();
  1196. harness.fixture.detectChanges();
  1197. expect(api.lastLearningWordUpdate).toEqual(jasmine.objectContaining({ uid: 100, wordsId: '701', save: 1 }));
  1198. expect(router.url).toBe('/pages/member/starshop');
  1199. const tabs = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.word-selection-tabs button') ?? [];
  1200. expect(tabs[0].textContent).toContain('0');
  1201. tabs[1].click();
  1202. harness.fixture.detectChanges();
  1203. expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('tend');
  1204. }, 15000);
  1205. it('skips the entire spelling stage for student wordbook self-study in one click', async () => {
  1206. const prefix = 'xiaoshu.learning.100.100.practice.';
  1207. const words = [
  1208. { GeneralID: 701, Title: 'tend', sy: '照顾' },
  1209. { GeneralID: 702, Title: 'work on', sy: '从事' },
  1210. { GeneralID: 703, Title: 'prepare', sy: '准备' },
  1211. ];
  1212. localStorage.setItem(prefix + 'learn_mode', JSON.stringify('newword'));
  1213. localStorage.setItem(prefix + 'choose_newword_learn', JSON.stringify(words.slice(0, 2)));
  1214. localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify([words.slice(0, 2), words.slice(2)]));
  1215. localStorage.setItem(prefix + '_page_current_learn', JSON.stringify(1));
  1216. const harness = await RouterTestingHarness.create();
  1217. const router = TestBed.inject(Router);
  1218. await harness.navigateByUrl('/pages/stu/stu5');
  1219. harness.fixture.detectChanges();
  1220. const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1221. expect(learning().words().length).toBe(2);
  1222. expect(learning().currentIndex()).toBe(0);
  1223. const skip = Array.from(harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.skippable-spelling-actions button') ?? [])
  1224. .find((button) => button.textContent?.includes('跳过这一关'))!;
  1225. skip.click();
  1226. await harness.fixture.whenStable();
  1227. harness.fixture.detectChanges();
  1228. expect(router.url).toContain('/pages/stu/stu_con');
  1229. expect(learning().words().map((word) => word.word)).toEqual(['prepare']);
  1230. learning().skipStudyList();
  1231. await harness.fixture.whenStable();
  1232. harness.fixture.detectChanges();
  1233. learning().chooseMatch('left', learning().words()[0]);
  1234. learning().chooseMatch('right', learning().words()[0]);
  1235. learning().continueAfterStage();
  1236. await harness.fixture.whenStable();
  1237. harness.fixture.detectChanges();
  1238. expect(router.url).toContain('/pages/stu/stu4');
  1239. learning().chooseMeaning(learning().words()[0]);
  1240. learning().continueAfterStage();
  1241. await harness.fixture.whenStable();
  1242. expect(router.url).toBe('/pages/member/starshop');
  1243. expect(localStorage.getItem(prefix + 'learn_mode')).toBeNull();
  1244. }, 15000);
  1245. it('still pronounces pending and completed words when a coach reveals them', async () => {
  1246. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1247. session.groupId.set(3);
  1248. session.student.set({ userId: 100, userName: 'student', groupId: 1 });
  1249. const play = spyOn(TestBed.inject(PlatformService), 'play');
  1250. const harness = await RouterTestingHarness.create();
  1251. await harness.navigateByUrl('/pages/stu/stu_abc?nids=811,812&pnid=801');
  1252. for (const index of [0, 1]) {
  1253. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[index] as HTMLButtonElement).click();
  1254. harness.fixture.detectChanges();
  1255. expect(harness.routeNativeElement?.querySelector('.audio')).not.toBeNull();
  1256. (harness.routeNativeElement?.querySelector('.word-reveal') as HTMLButtonElement).click();
  1257. }
  1258. expect(play).toHaveBeenCalledTimes(2);
  1259. expect(play.calls.argsFor(0)[0]).toContain('banana.mp3');
  1260. expect(play.calls.argsFor(1)[0]).toContain('apple.mp3');
  1261. });
  1262. it('allows second and third passes per word before the whole book is finished and stops selection after three passes', async () => {
  1263. user.set({userId:300,groupId:3});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  1264. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1265. api.courseWords=[{GeneralID:1001,NodeID:811,Title:'apple',w_learned:1},{GeneralID:1002,NodeID:811,Title:'banana',w_learned:2},{GeneralID:1003,NodeID:811,Title:'pear',w_learned:3}];
  1266. api.courseBookCounts=[1,1,1,1]; // An unselected unit still has a first-pass word.
  1267. const harness=await RouterTestingHarness.create('/pages/stu/stu_abc?nids=811&pnid=801&bindingId=701');
  1268. const learning=()=>harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1269. const tab=(n:number)=>(harness.routeNativeElement!.querySelectorAll('.course-pass-tabs button')[n] as HTMLButtonElement);
  1270. harness.fixture.detectChanges();
  1271. expect(harness.routeNativeElement!.querySelectorAll('.course-pass-tabs button').length).toBe(4);
  1272. tab(1).click();harness.fixture.detectChanges();
  1273. expect(harness.routeNativeElement!.querySelector('.word-select-check')).not.toBeNull();
  1274. expect(harness.routeNativeElement!.textContent).toContain('选择单词开始第二遍学习');
  1275. expect(learning().firstPassProgress()).toBe(75);
  1276. const select=harness.routeNativeElement!.querySelector('.word-select-check') as HTMLButtonElement;
  1277. select.click();harness.fixture.detectChanges();
  1278. expect(learning().selected().size).toBe(1);
  1279. tab(2).click();harness.fixture.detectChanges();
  1280. const secondPass=harness.routeNativeElement!.querySelector('.word-select-check') as HTMLButtonElement;
  1281. expect(secondPass).not.toBeNull();
  1282. secondPass.click();harness.fixture.detectChanges();
  1283. expect(learning().selected().size).toBe(2);
  1284. secondPass.click();harness.fixture.detectChanges();
  1285. expect(learning().selected().size).toBe(1);
  1286. tab(3).click();harness.fixture.detectChanges();
  1287. expect(harness.routeNativeElement!.textContent).toContain('已完成三遍学习');
  1288. expect(harness.routeNativeElement!.querySelector('.word-select-check')).toBeNull();
  1289. expect(learning().firstPassProgress()).toBe(75);
  1290. // Selecting a learned word must actually enter the regular learning flow.
  1291. tab(1).click();harness.fixture.detectChanges();
  1292. (harness.routeNativeElement!.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  1293. await harness.fixture.whenStable();harness.fixture.detectChanges();
  1294. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  1295. expect(learning().words().map(word=>word.word)).toEqual(['apple']);
  1296. const finishPass=async()=>{
  1297. for(let stage=0;stage<4;stage++){
  1298. const skip=Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('.sticky-actions button')).find(button=>button.textContent?.includes('跳过这一关'))!;
  1299. skip.click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  1300. }
  1301. expect(TestBed.inject(Router).url).toBe('/pages/his/his');
  1302. };
  1303. await finishPass();
  1304. expect(api.courseIncrements.get('1001')).toBe(1);
  1305. await harness.navigateByUrl('/pages/stu/stu_abc?nids=811&pnid=801&bindingId=701');harness.fixture.detectChanges();
  1306. tab(2).click();harness.fixture.detectChanges();
  1307. expect(learning().words().find(word=>word.word==='apple')?.['w_learned']).toBe(2);
  1308. (harness.routeNativeElement!.querySelector('[aria-label="加入学习:apple"]') as HTMLButtonElement).click();
  1309. (harness.routeNativeElement!.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  1310. await harness.fixture.whenStable();harness.fixture.detectChanges();
  1311. await finishPass();
  1312. expect(api.courseIncrements.get('1001')).toBe(2);
  1313. await harness.navigateByUrl('/pages/stu/stu_abc?nids=811&pnid=801&bindingId=701');harness.fixture.detectChanges();
  1314. tab(3).click();harness.fixture.detectChanges();
  1315. expect(learning().words().find(word=>word.word==='apple')?.['w_learned']).toBe(3);
  1316. expect(harness.routeNativeElement!.querySelector('.word-select-check')).toBeNull();
  1317. expect(learning().firstPassProgress()).toBe(75);
  1318. api.courseBookCounts=[0,0,1,3];tab(0).click();tab(3).click();harness.fixture.detectChanges();
  1319. expect(learning().firstPassProgress()).toBe(100);
  1320. },30000);
  1321. it('shows named schedule students below the trigger and closes after selection or Escape', async () => {
  1322. user.set({userId:300,userName:'coach',honeyName:'张老师',groupId:3});
  1323. const harness=await RouterTestingHarness.create();
  1324. await harness.navigateByUrl('/pages/home/shop');
  1325. const component=harness.fixture.debugElement.query(By.directive(CourseCenterPageComponent)).componentInstance as CourseCenterPageComponent;
  1326. component.serverStudents.set([{id:'100',name:'张雅茜',count:15},{id:'101',name:'花花',count:9},{id:'102',name:' ',count:1}]);
  1327. spyOn(component,'load').and.stub();
  1328. harness.fixture.detectChanges();
  1329. await new Promise(resolve => setTimeout(resolve, 0));
  1330. const trigger=harness.routeNativeElement!.querySelector<HTMLButtonElement>('.student-filter .xs-dropdown-trigger')!;
  1331. expect(trigger.textContent).toContain('全部学员(25)');
  1332. trigger.click();harness.fixture.detectChanges();
  1333. const menu=document.querySelector<HTMLElement>('.xs-dropdown-menu')!;
  1334. expect(menu.textContent).toContain('张雅茜(15)');
  1335. expect(menu.textContent).toContain('学员 102(1)');
  1336. expect(menu.getBoundingClientRect().top).toBeGreaterThan(trigger.getBoundingClientRect().bottom);
  1337. menu.querySelectorAll('button')[2].click();harness.fixture.detectChanges();
  1338. await new Promise(resolve => setTimeout(resolve, 0));
  1339. expect(component.selectedStudent()).toBe('101');
  1340. expect(trigger.textContent).toContain('花花(9)');
  1341. expect(document.querySelector('.xs-dropdown-menu')).toBeNull();
  1342. trigger.click();harness.fixture.detectChanges();
  1343. document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape'}));harness.fixture.detectChanges();
  1344. expect(document.querySelector('.xs-dropdown-menu')).toBeNull();
  1345. });
  1346. it('shows the planned review day and original learning time for migrated August tasks', async () => {
  1347. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1348. session.groupId.set(3);
  1349. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1350. const post = api.post.bind(api);
  1351. spyOn(api, 'post').and.callFake((action, params) => action === 'app_review_page'
  1352. ? of({ retcode: 1, result: {
  1353. items: [{ GeneralID: 102, yhid: 100, xxjlid: 900, kcid: 801, Title: '张雅茜@任务',
  1354. kywrq: params?.['date'], kywsj: '2026-09-01 09:00', CreateTime: '2026-09-01T02:25:17Z',
  1355. learned_at: '2026-07-31T01:20:00Z', learned_date: '20260731', fxzt: 0 }],
  1356. page: { itemCount: 1, pageCount: 1 }, summary: { total: 1, completed: 0, due: 1, today: 0, income: 0 },
  1357. dates: [{ date: '2026-08-01', total: 1, completed: 0 }, { date: '2026-08-15', total: 1, completed: 0 }],
  1358. } } as ApiEnvelope<any>) : post(action, params));
  1359. const harness = await RouterTestingHarness.create();
  1360. await harness.navigateByUrl('/pages/stu/stu_calendar?date=2026-08-01');
  1361. await harness.fixture.whenStable();harness.fixture.detectChanges();
  1362. expect(harness.routeNativeElement?.querySelector('.task-context')?.textContent).toContain('复习日期 2026-08-01');
  1363. expect(harness.routeNativeElement?.querySelector('.first-learned-at')?.textContent).toContain('2026-07-31 09:20');
  1364. (harness.routeNativeElement?.querySelector('[aria-label^="2026-08-15"]') as HTMLButtonElement).click();
  1365. await harness.fixture.whenStable();harness.fixture.detectChanges();
  1366. expect(harness.routeNativeElement?.querySelector('.task-context')?.textContent).toContain('复习日期 2026-08-15');
  1367. const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1368. const task = component.calendarItems()[0];
  1369. expect(component.calendarFirstLearnedAt({ learned_date: '20260731' })).toContain('2026-07-31(时间未记录)');
  1370. component.openCalendar(task);
  1371. await harness.fixture.whenStable();
  1372. expect(TestBed.inject(Router).url).toContain('plannedDate=2026-08-15');
  1373. });
  1374. it('keeps the anti-forget page visible while a selected date loads locally', async () => {
  1375. const harness = await RouterTestingHarness.create();
  1376. await harness.navigateByUrl('/pages/stu/stu_calendar');
  1377. await harness.fixture.whenStable();
  1378. harness.fixture.detectChanges();
  1379. const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1380. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1381. component.memoryMonth.set(new Date(2026, 8, 1, 12));
  1382. component.memorySelectedDate.set('2026-09-11');
  1383. harness.fixture.detectChanges();
  1384. const response = new Subject<ApiEnvelope<unknown>>();
  1385. api.reviewPageResponse = response;
  1386. (harness.routeNativeElement?.querySelector('[aria-label^="2026-09-12"]') as HTMLButtonElement).click();
  1387. harness.fixture.detectChanges();
  1388. expect(api.lastMemoryParams['date']).toBe('2026-09-12');
  1389. expect(harness.routeNativeElement?.querySelector('.memory-overview')).not.toBeNull();
  1390. expect(harness.routeNativeElement?.querySelector('.memory-calendar')).not.toBeNull();
  1391. expect(harness.routeNativeElement?.querySelector('.memory-list-loading')?.textContent).toContain('正在加载当日复习');
  1392. response.next({
  1393. retcode: 1,
  1394. result: {
  1395. items: [{ GeneralID: 120, Title: '张雅茜@任务', kc_title: '9月12日复习', kywsj: '2026-09-12 09:00', fxzt: 0, yhid: 100, xxjlid: 920 }],
  1396. page: { itemCount: 1, pageCount: 1 },
  1397. summary: { total: 1, completed: 0, due: 0, today: 0, income: 0 },
  1398. dates: [{ date: '2026-09-12', total: 1, completed: 0 }],
  1399. },
  1400. });
  1401. response.complete();
  1402. api.reviewPageResponse = null;
  1403. await harness.fixture.whenStable();
  1404. harness.fixture.detectChanges();
  1405. expect(harness.routeNativeElement?.querySelector('.memory-list-loading')).toBeNull();
  1406. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('9月12日复习');
  1407. });
  1408. it('shows a retryable error instead of an empty review when the detail has no words', async () => {
  1409. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1410. const post = api.post.bind(api);
  1411. spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
  1412. ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : post(action, params));
  1413. const harness = await RouterTestingHarness.create();
  1414. await harness.navigateByUrl('/pages/stu/record?id=900&gid=102&kcid=801');
  1415. harness.fixture.detectChanges();
  1416. expect(harness.routeNativeElement?.querySelector('.empty-state.error')?.textContent).toContain('没有读取到单词');
  1417. expect(harness.routeNativeElement?.querySelector('.empty-state.error button')?.textContent).toContain('重新加载');
  1418. expect(harness.routeNativeElement?.querySelector('.record-list')).toBeNull();
  1419. });
  1420. it('syncs a missing learning record and reopens its review words', async () => {
  1421. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1422. const post = api.post.bind(api);
  1423. let detailReads = 0;
  1424. spyOn(api, 'post').and.callFake((action, params) => {
  1425. if (action === 'e_record_detail') {
  1426. detailReads += 1;
  1427. return of({ retcode: 1, result: detailReads === 1 ? [] : [{ GeneralID: 701, Title: 'apple', sy: '苹果' }], addon: [] } as ApiEnvelope<any>);
  1428. }
  1429. if (action === 'app_learning_overview') return of({ retcode: 1, result: {} } as ApiEnvelope<any>);
  1430. return post(action, params);
  1431. });
  1432. const harness = await RouterTestingHarness.create();
  1433. await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
  1434. harness.fixture.detectChanges();
  1435. expect(detailReads).toBe(2);
  1436. expect(harness.routeNativeElement?.querySelector('.record-word')?.textContent).toContain('apple');
  1437. expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
  1438. });
  1439. it('reads the original word list when the detail stays empty after syncing', async () => {
  1440. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1441. const post = api.post.bind(api);
  1442. const get = api.get.bind(api);
  1443. spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
  1444. ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : action === 'app_learning_overview'
  1445. ? of({ retcode: 1, result: {} } as ApiEnvelope<any>) : post(action, params));
  1446. spyOn(api, 'get').and.callFake((action, params) => action === 'content_get'
  1447. ? of({ retcode: 1, result: [{ GeneralID: 864038, xxqs: JSON.stringify([{ GeneralID: 701, Title: 'apple' }]) }] } as ApiEnvelope<any>)
  1448. : get(action, params));
  1449. const harness = await RouterTestingHarness.create();
  1450. await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
  1451. harness.fixture.detectChanges();
  1452. expect(harness.routeNativeElement?.querySelector('.record-word')?.textContent).toContain('apple');
  1453. expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
  1454. });
  1455. it('allows a confirmed notes review to finish once without loading missing vocabulary', async () => {
  1456. user.set({userId:300,groupId:3}); session.groupId.set(3); session.student.set({userId:100,groupId:1});
  1457. const api = TestBed.inject(ApiService), post = api.post.bind(api), reply = new Subject<ApiEnvelope<any>>();
  1458. const submit = spyOn(api, 'post').and.callFake((action,params) => action === 'e_record_detail'
  1459. ? of({retcode:1,result:[],addon:[{reviewContentMode:'notes',courseCategoryKey:'high_writing'}]} as ApiEnvelope<any>)
  1460. : action === 'app_review_complete' ? reply : post(action,params));
  1461. const get = spyOn(api,'get').and.callThrough();
  1462. const harness = await RouterTestingHarness.create();
  1463. await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047'); harness.fixture.detectChanges();
  1464. expect(harness.routeNativeElement?.textContent).toContain('语法写作复习');
  1465. expect(harness.routeNativeElement?.textContent).toContain('请带领学生复习课堂语法笔记');
  1466. expect(harness.routeNativeElement?.querySelector('.record-list')).toBeNull();
  1467. expect(get.calls.allArgs().some(a=>a[0]==='content_get')).toBeFalse();
  1468. expect(submit.calls.allArgs().some(a=>a[0]==='app_learning_overview')).toBeFalse();
  1469. const end = harness.routeNativeElement?.querySelector('.sticky-actions button') as HTMLButtonElement;
  1470. expect(end.textContent).toContain('结束复习'); end.click(); harness.fixture.detectChanges();
  1471. expect(end.disabled).toBeTrue();end.click();
  1472. const requests=submit.calls.allArgs().filter(a=>a[0]==='app_review_complete');
  1473. expect(requests.length).toBe(1);expect(requests[0][1]).toEqual({id:'864047'});
  1474. expect(harness.routeNativeElement?.querySelector('.review-complete')).toBeNull();
  1475. reply.next({retcode:1,result:{amount:1,rewardStatus:'earned'}});reply.complete();harness.fixture.detectChanges();
  1476. expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).toContain('复习已完成');
  1477. });
  1478. it('identifies a legacy writing review with no original words and keeps it incomplete', async () => {
  1479. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1480. const post = api.post.bind(api);
  1481. const get = api.get.bind(api);
  1482. spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
  1483. ? of({ retcode: 1, result: [], addon: [] } as ApiEnvelope<any>) : action === 'app_learning_overview'
  1484. ? of({ retcode: 1, result: {} } as ApiEnvelope<any>) : post(action, params));
  1485. spyOn(api, 'get').and.callFake((action, params) => action === 'content_get'
  1486. ? of({ retcode: 1, result: [{ GeneralID: 864038, xxqs: '', learned: 0, con: '完成了写作学习' }] } as ApiEnvelope<any>)
  1487. : get(action, params));
  1488. const harness = await RouterTestingHarness.create();
  1489. await harness.navigateByUrl('/pages/stu/record?id=864038&gid=864047&kcid=398');
  1490. harness.fixture.detectChanges();
  1491. expect(harness.routeNativeElement?.textContent).toContain('写作学习记录,原本没有单词');
  1492. expect(harness.routeNativeElement?.querySelector('.record-list')).toBeNull();
  1493. expect(harness.routeNativeElement?.querySelector('a[href="/pages/stu/stu_calendar"]')).not.toBeNull();
  1494. expect(harness.routeNativeElement?.textContent).not.toContain('结束本次复习');
  1495. });
  1496. it('renders source-shaped data for all four home entries', async () => {
  1497. const harness = await RouterTestingHarness.create();
  1498. await harness.navigateByUrl('/pages/home/index');
  1499. expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
  1500. expect(harness.routeNativeElement?.querySelector('.home-header [aria-label="搜索"]')).toBeNull();
  1501. expect(harness.routeNativeElement?.querySelector('.home-header [aria-label="用户中心"]')).toBeNull();
  1502. expect(harness.routeNativeElement?.querySelector('.memory-hero')).not.toBeNull();
  1503. expect(harness.routeNativeElement?.querySelectorAll('.memory-dot').length).toBe(21);
  1504. expect(harness.routeNativeElement?.querySelector('.today-panel')?.textContent).toContain('学习新词');
  1505. expect(harness.routeNativeElement?.querySelectorAll('.student-stats > div').length).toBe(5);
  1506. expect(harness.routeNativeElement?.querySelectorAll('.quick-grid > a').length).toBe(4);
  1507. expect(harness.routeNativeElement?.querySelector('.continue-button')?.getAttribute('href')).toBe('/pages/stu/stu_calendar');
  1508. expect(harness.routeNativeElement?.querySelector('.task-link')?.getAttribute('href')).toBe('/pages/home/cart');
  1509. await harness.navigateByUrl('/pages/stu/index');
  1510. await harness.fixture.whenStable();
  1511. harness.fixture.detectChanges();
  1512. expect(TestBed.inject(Router).url).toBe('/pages/home/cart');
  1513. expect(harness.routeNativeElement?.textContent).not.toContain('选择词库教材');
  1514. await harness.navigateByUrl('/pages/stu/stu_list?nid=801&bindingId=701');
  1515. await harness.fixture.whenStable();
  1516. harness.fixture.detectChanges();
  1517. expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
  1518. expect(harness.routeNativeElement?.querySelector('.node-list button')?.textContent).toContain('已学 1/20 · 进度 5%');
  1519. expect(harness.routeNativeElement?.querySelectorAll('.unit-progress-ring').length).toBe(2);
  1520. expect(harness.routeNativeElement?.querySelector('.unit-progress-ring')?.textContent).toContain('5%');
  1521. expect(harness.routeNativeElement?.querySelector('.unit-selection-summary')).toBeNull();
  1522. expect(harness.routeNativeElement?.querySelector('.unit-actions')).toBeNull();
  1523. const firstUnit = harness.routeNativeElement?.querySelector('.node-list button') as HTMLButtonElement;
  1524. firstUnit.click();
  1525. await harness.fixture.whenStable();
  1526. harness.fixture.detectChanges();
  1527. const readonlyRouter = TestBed.inject(Router);
  1528. expect(readonlyRouter.url).toBe('/pages/stu/stu_abc?nids=811&pnid=801&readonly=1');
  1529. expect(harness.routeNativeElement?.querySelector('.selection-header')?.textContent).toContain('词库学习进度');
  1530. expect(harness.routeNativeElement?.querySelector('.selection-header .primary-button')).toBeNull();
  1531. expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('banana');
  1532. expect(harness.routeNativeElement?.querySelector('.word-select-check')).toBeNull();
  1533. expect(harness.routeNativeElement?.querySelector('.word-assessment')).toBeNull();
  1534. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  1535. harness.fixture.detectChanges();
  1536. expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('apple');
  1537. expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
  1538. await harness.navigateByUrl('/pages/home/index');
  1539. await harness.navigateByUrl('/pages/stu/stu_con?nid=813&pnid=801&readonly=1');
  1540. await harness.fixture.whenStable();
  1541. harness.fixture.detectChanges();
  1542. const wordApi = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1543. expect(wordApi.lastWordParams['psize']).toBe(30);
  1544. expect(harness.routeNativeElement?.querySelectorAll('.readonly-word-list article').length).toBe(30);
  1545. expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('第 1–30 条 · 共 65 个单词');
  1546. expect(harness.routeNativeElement?.querySelector('.word-preview-pagination')?.textContent).toContain('1 / 3 页');
  1547. (harness.routeNativeElement?.querySelector('[aria-label="第 2 页"]') as HTMLButtonElement).click();
  1548. await harness.fixture.whenStable();
  1549. harness.fixture.detectChanges();
  1550. expect(wordApi.lastWordParams['cpage']).toBe(2);
  1551. expect(harness.routeNativeElement?.querySelectorAll('.readonly-word-list article').length).toBe(30);
  1552. expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('第 31–60 条 · 共 65 个单词');
  1553. expect(harness.routeNativeElement?.querySelector('.readonly-word-list')?.textContent).toContain('word-31');
  1554. expect(harness.routeNativeElement?.querySelector('.word-preview-pagination')?.textContent).toContain('2 / 3 页');
  1555. await harness.navigateByUrl('/pages/stu/stu_list?nid=999&bindingId=799');
  1556. await harness.fixture.whenStable();
  1557. harness.fixture.detectChanges();
  1558. expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_abc?nids=999&readonly=1');
  1559. expect(harness.routeNativeElement?.querySelector('.selection-header')?.textContent).toContain('词库学习进度');
  1560. await harness.navigateByUrl('/pages/stu/stu_calendar');
  1561. const calendarComponent=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1562. calendarComponent.memoryMonth.set(new Date(2026,7,1));
  1563. calendarComponent.memorySelectedDate.set('2026-08-02');
  1564. (calendarComponent as any).loadCalendar();
  1565. harness.fixture.detectChanges();
  1566. expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
  1567. expect(harness.routeNativeElement?.querySelector('.memory-student-filter')).toBeNull();
  1568. expect(harness.routeNativeElement?.querySelectorAll('.memory-date').length).toBe(42);
  1569. expect(harness.routeNativeElement?.querySelectorAll('.memory-date.completed, .memory-date.due').length).toBe(2);
  1570. expect(harness.routeNativeElement?.querySelector('.memory-overview')?.textContent).toContain('2 / 3');
  1571. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('高中英语复习');
  1572. expect(harness.routeNativeElement?.querySelector('.review-sequence')?.textContent).toContain('第 3 次复习');
  1573. expect(harness.routeNativeElement?.querySelector('.first-learned-at')?.textContent).toContain('首次学习:2026-07-20 10:20');
  1574. for (let index = 0; index < 3; index += 1) {
  1575. (harness.routeNativeElement?.querySelector('[aria-label="上个月"]') as HTMLButtonElement).click();
  1576. harness.fixture.detectChanges();
  1577. }
  1578. expect(harness.routeNativeElement?.querySelector('[aria-label^="2026-05-15"]')?.classList).toContain('completed');
  1579. expect(harness.routeNativeElement?.textContent).toContain('张雅茜');
  1580. expect(harness.routeNativeElement?.querySelector('.memory-overview header b')?.textContent).toContain('67%');
  1581. expect(harness.routeNativeElement?.querySelector('.memory-stats')?.textContent).toContain('2 / 3');
  1582. await harness.navigateByUrl('/pages/home/ucenter');
  1583. expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
  1584. expect(harness.routeNativeElement?.querySelector('.new-word-entry')?.getAttribute('href')).toBe('/pages/home/cart');
  1585. expect(harness.routeNativeElement?.querySelector('.course-memory')?.textContent).toContain('21 天抗遗忘计划');
  1586. expect(harness.routeNativeElement?.querySelector('.memory-overview em')?.textContent).toContain('67%');
  1587. expect(harness.routeNativeElement?.querySelector('.memory-overview')?.textContent).toContain('覆盖 3 个复习日');
  1588. expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('3总任务');
  1589. expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('2已完成');
  1590. expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('1到期待复习');
  1591. expect(harness.routeNativeElement?.querySelector('.memory-counts')?.textContent).toContain('0未来待复习');
  1592. await harness.navigateByUrl('/pages/stu/record?id=827482&gid=828268&kcid=203');
  1593. const recordWord = harness.routeNativeElement?.querySelector('.record-word') as HTMLButtonElement;
  1594. expect(recordWord.querySelector('.record-copy strong')?.textContent).toBe('apple');
  1595. expect(harness.routeNativeElement?.textContent).not.toContain('苹果');
  1596. recordWord.click();
  1597. await harness.fixture.whenStable();
  1598. harness.fixture.detectChanges();
  1599. expect(recordWord.querySelector('.record-copy strong')?.textContent).toBe('苹果');
  1600. expect(harness.routeNativeElement?.querySelector('.record-overview')?.textContent).toContain('1 / 1');
  1601. await harness.navigateByUrl('/pages/member/starshop');
  1602. expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
  1603. expect(harness.routeNativeElement?.querySelector('.word-select-list strong')?.textContent).toBe('tend');
  1604. expect(harness.routeNativeElement?.querySelector('.word-select-list')?.textContent).not.toContain('@张雅茜');
  1605. (harness.routeNativeElement?.querySelector('.word-select-list > button') as HTMLButtonElement).click();
  1606. (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  1607. await harness.fixture.whenStable();
  1608. const selectedNewWords = JSON.parse(sessionStorage.getItem('xiaoshu.learning.100.100.practice.selectedWords') ?? '[]') as Array<{ word?: string }>;
  1609. expect(selectedNewWords[0]?.word).toBe('tend');
  1610. expect(sessionStorage.getItem('xiaoshu.learning.100.100.practice.selectedWords')).not.toContain('@张雅茜');
  1611. await harness.navigateByUrl('/pages/his/well?nid=3');
  1612. expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
  1613. expect(harness.routeNativeElement?.textContent).toContain('阅读理解专项');
  1614. await harness.navigateByUrl('/pages/home/cart');
  1615. expect(harness.fixture.nativeElement.querySelector('.tabbar')).not.toBeNull();
  1616. expect(harness.fixture.nativeElement.querySelector('.app-header .icon-button')).toBeNull();
  1617. expect(harness.fixture.nativeElement.querySelector('.app-header h1')?.textContent).toContain('伴学中心');
  1618. expect(harness.routeNativeElement?.querySelector('.library-entry')).toBeNull();
  1619. expect(harness.routeNativeElement?.textContent).toContain('我的学习内容');
  1620. expect(harness.routeNativeElement?.querySelectorAll('.course-list li').length).toBe(2);
  1621. expect(harness.routeNativeElement?.querySelectorAll('.course-list button').length).toBe(2);
  1622. expect((harness.routeNativeElement?.querySelector('.course-list button') as HTMLButtonElement).disabled).toBeFalse();
  1623. expect((harness.routeNativeElement?.querySelectorAll('.course-list button')[1] as HTMLButtonElement).disabled).toBeFalse();
  1624. expect(harness.routeNativeElement?.textContent).toContain('【七年级上册】同步词汇');
  1625. expect(harness.routeNativeElement?.textContent).toContain('点击查看老师分配的单词列表');
  1626. (harness.routeNativeElement?.querySelector('.course-list button') as HTMLButtonElement).click();
  1627. await harness.fixture.whenStable();
  1628. harness.fixture.detectChanges();
  1629. expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_list?nid=801&bindingId=701');
  1630. expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
  1631. expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastNodeParams['bindingId']).toBe('701');
  1632. await harness.navigateByUrl('/pages/home/cart');
  1633. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(0);
  1634. expect(harness.routeNativeElement?.querySelectorAll('.calendar-day').length).toBe(42);
  1635. const allDates = Array.from(harness.routeNativeElement?.querySelectorAll('.range-tabs button') ?? [])
  1636. .find((button) => button.textContent?.trim() === '全部') as HTMLButtonElement;
  1637. allDates.click();
  1638. harness.fixture.detectChanges();
  1639. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(3);
  1640. expect(harness.routeNativeElement?.textContent).toContain('同步伴学');
  1641. expect(harness.routeNativeElement?.textContent).toContain('历史伴学');
  1642. const plannedIncompleteFilter = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-filters button') ?? [])
  1643. .find((button) => button.textContent?.includes('计划未完成')) as HTMLButtonElement;
  1644. expect(plannedIncompleteFilter.textContent).toContain('1');
  1645. plannedIncompleteFilter.click();
  1646. harness.fixture.detectChanges();
  1647. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
  1648. expect(harness.routeNativeElement?.textContent).toContain('计划未完成');
  1649. expect(harness.routeNativeElement?.textContent).not.toContain('未来计划');
  1650. (harness.routeNativeElement?.querySelector('.schedule-filters button') as HTMLButtonElement).click();
  1651. harness.fixture.detectChanges();
  1652. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1653. expect(api.lastScheduleParams['mode']).toBe('student');
  1654. expect(api.lastScheduleParams['pageSize']).toBe(20);
  1655. const finishedFilter = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-filters button') ?? [])
  1656. .find((button) => button.textContent?.includes('已结束')) as HTMLButtonElement;
  1657. finishedFilter.click();
  1658. harness.fixture.detectChanges();
  1659. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
  1660. expect(harness.routeNativeElement?.textContent).toContain('历史伴学');
  1661. const allFilter = harness.routeNativeElement?.querySelector('.schedule-filters button') as HTMLButtonElement;
  1662. allFilter.click();
  1663. harness.fixture.detectChanges();
  1664. const upcomingSchedule = Array.from(harness.routeNativeElement?.querySelectorAll('.schedule-list article') ?? [])
  1665. .find((article) => article.textContent?.includes('同步伴学')) as HTMLElement;
  1666. upcomingSchedule.click();
  1667. await harness.fixture.whenStable();
  1668. expect(TestBed.inject(Router).url).toBe('/pages/shop/stu_get_order?id=901');
  1669. await harness.navigateByUrl('/pages/his/his');
  1670. expect(harness.fixture.nativeElement.querySelector('.tabbar')).toBeNull();
  1671. const aiReadingFeature = harness.routeNativeElement?.querySelector('.ai-reading-feature') as HTMLElement;
  1672. expect(aiReadingFeature.textContent).toContain('AI 阅读巩固');
  1673. expect(aiReadingFeature.textContent).toContain('生成阅读');
  1674. expect(aiReadingFeature.textContent).toContain('AI 批改');
  1675. expect(aiReadingFeature.querySelector('img')?.getAttribute('src')).toBe('/static/images/ai-reading-journey.png');
  1676. const aiReadingCta = aiReadingFeature.querySelector('.ai-reading-cta') as HTMLButtonElement;
  1677. expect(aiReadingCta.disabled).toBeFalse();
  1678. expect(aiReadingFeature.textContent).toContain('最近学过的 1 个单词');
  1679. expect(aiReadingCta.textContent).toContain('立即生成阅读');
  1680. aiReadingCta.click();
  1681. await harness.fixture.whenStable();
  1682. const aiReadingRouter = TestBed.inject(Router);
  1683. expect(aiReadingRouter.url).toContain('/words/go-reading');
  1684. expect(aiReadingRouter.parseUrl(aiReadingRouter.url).queryParams['returnUrl']).toBe('/pages/his/his');
  1685. expect(aiReadingRouter.parseUrl(aiReadingRouter.url).queryParams['GeneralID']).toBe('201');
  1686. await harness.navigateByUrl('/pages/his/his');
  1687. const currentLearningCard = harness.routeNativeElement?.querySelector('.current-learning-card') as HTMLElement;
  1688. const learningRecordCard = harness.routeNativeElement?.querySelector('.learning-record-card') as HTMLElement;
  1689. expect(currentLearningCard.textContent).toContain('我的学习内容');
  1690. const records = harness.fixture.debugElement.query(By.directive(StudyRecordsPageComponent)).componentInstance as StudyRecordsPageComponent;
  1691. expect(records.courseTitle({ Title: '单词课|高中@人教版2022年录', Title2: '人教版2022年录' })).toBe('【高中】人教版2022年录');
  1692. expect(records.courseTitle({ Title: '单词课|初中@人教版2024年9月录', Title2: '人教版2024年9月录' })).toBe('【初中】人教版2024年9月录');
  1693. expect(currentLearningCard.querySelectorAll('.current-learning-list button').length).toBe(2);
  1694. expect((currentLearningCard.querySelectorAll('.current-learning-list button')[1] as HTMLButtonElement).disabled).toBeFalse();
  1695. expect(currentLearningCard.compareDocumentPosition(learningRecordCard) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  1696. (currentLearningCard.querySelector('.current-learning-list button') as HTMLButtonElement).click();
  1697. await harness.fixture.whenStable();
  1698. harness.fixture.detectChanges();
  1699. expect(TestBed.inject(Router).url).toBe('/pages/stu/stu_list?nid=801&bindingId=701');
  1700. expect(harness.routeNativeElement?.querySelectorAll('.node-list button').length).toBe(2);
  1701. await harness.navigateByUrl('/pages/his/his');
  1702. expect(harness.routeNativeElement?.textContent).toContain('初中英语 / Unit 1');
  1703. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
  1704. (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
  1705. await harness.fixture.whenStable();
  1706. harness.fixture.detectChanges();
  1707. expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
  1708. expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('学生只读');
  1709. expect(harness.routeNativeElement?.querySelector('.readonly-word-card')).not.toBeNull();
  1710. expect(harness.routeNativeElement?.querySelector('.selection-header')).toBeNull();
  1711. await harness.navigateByUrl('/pages/his/his');
  1712. (harness.routeNativeElement?.querySelector('.date-trigger') as HTMLButtonElement).click();
  1713. harness.fixture.detectChanges();
  1714. const currentMonth = new Date();
  1715. const monthDifference = (2026 - currentMonth.getFullYear()) * 12 + (7 - currentMonth.getMonth());
  1716. const shiftLabel = monthDifference < 0 ? '上个月' : '下个月';
  1717. for (let index = 0; index < Math.abs(monthDifference); index += 1) {
  1718. (harness.routeNativeElement?.querySelector(`[aria-label="${shiftLabel}"]`) as HTMLButtonElement).click();
  1719. harness.fixture.detectChanges();
  1720. }
  1721. expect(harness.routeNativeElement?.querySelector('.date-picker-popover header strong')?.textContent).toContain('2026年8月');
  1722. expect(harness.routeNativeElement?.querySelectorAll('.date-picker-day').length).toBe(42);
  1723. expect(harness.routeNativeElement?.querySelectorAll('.date-picker-day.has-record').length).toBe(2);
  1724. expect(harness.routeNativeElement?.querySelector('.date-picker-day.has-record')?.getAttribute('aria-label')).toContain('2026-08-01');
  1725. (harness.routeNativeElement?.querySelector('[aria-label^="2026-08-01"]') as HTMLButtonElement).click();
  1726. harness.fixture.detectChanges();
  1727. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(1);
  1728. expect(harness.routeNativeElement?.querySelector('.learning-record-card')?.textContent).not.toContain('高中英语 / Unit 2');
  1729. (harness.routeNativeElement?.querySelector('.record-actions button') as HTMLButtonElement).click();
  1730. harness.fixture.detectChanges();
  1731. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
  1732. const completedReading = harness.routeNativeElement?.querySelector('.reading-button.completed') as HTMLButtonElement;
  1733. expect(completedReading.textContent).toContain('已完成阅读');
  1734. expect(completedReading.getAttribute('aria-label')).toBe('查看已完成的历史阅读理解');
  1735. completedReading.click();
  1736. await harness.fixture.whenStable();
  1737. const router = TestBed.inject(Router);
  1738. expect(router.url).toContain('/words/reading');
  1739. expect(router.parseUrl(router.url).queryParams['sid']).toBe('readingarticle201');
  1740. expect(router.parseUrl(router.url).queryParams['returnUrl']).toBe('/pages/his/his');
  1741. await harness.navigateByUrl('/pages/his/his');
  1742. const newReading = harness.routeNativeElement?.querySelector('.reading-button:not(.completed)') as HTMLButtonElement;
  1743. expect(newReading.textContent).toContain('阅读');
  1744. newReading.click();
  1745. await harness.fixture.whenStable();
  1746. expect(router.url).toContain('/words/go-reading');
  1747. expect(router.parseUrl(router.url).queryParams['returnUrl']).toBe('/pages/his/his');
  1748. expect(harness.routeNativeElement?.querySelector('.back-button')).not.toBeNull();
  1749. (harness.routeNativeElement?.querySelector('.back-button') as HTMLButtonElement).click();
  1750. await harness.fixture.whenStable();
  1751. expect(router.url).toBe('/pages/his/his');
  1752. (harness.fixture.nativeElement.querySelector('.app-header .icon-button') as HTMLButtonElement).click();
  1753. await harness.fixture.whenStable();
  1754. expect(router.url).toBe('/pages/home/index');
  1755. await harness.navigateByUrl('/pages/his/exam');
  1756. expect(harness.routeNativeElement?.textContent).toContain('第一组问题');
  1757. expect(harness.routeNativeElement?.textContent).toContain('相当于初二水平');
  1758. expect(harness.routeNativeElement?.textContent).toContain('共 1 题');
  1759. const startButton = harness.routeNativeElement?.querySelector('.exam-intro > button') as HTMLButtonElement;
  1760. startButton.click();
  1761. harness.fixture.detectChanges();
  1762. expect(harness.routeNativeElement?.querySelector('.question-word')?.textContent).toContain('apple');
  1763. expect(harness.routeNativeElement?.querySelector('.question-card > h2')).toBeNull();
  1764. expect(harness.routeNativeElement?.querySelectorAll('.exam-options button').length).toBe(1);
  1765. (harness.routeNativeElement?.querySelector('.exam-options button') as HTMLButtonElement).click();
  1766. harness.fixture.detectChanges();
  1767. });
  1768. it('matches coach review tasks to student names by ID when task name fields are blank', async () => {
  1769. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1770. session.groupId.set(3);
  1771. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1772. const response = new Subject<ApiEnvelope<unknown>>();
  1773. api.reviewPageResponse = response;
  1774. const harness = await RouterTestingHarness.create();
  1775. await harness.navigateByUrl('/pages/home/index');
  1776. response.next({ retcode: 1, result: {
  1777. items: [
  1778. { GeneralID: 102, yhid: 100, honeyName: '', Title: '旧姓名@复习', kywsj: String(api.lastMemoryParams['date']), fxzt: 0, xxjlid: 900 },
  1779. { GeneralID: 103, yhid: '101', honeyName: ' ', HoneyName: '', kywsj: String(api.lastMemoryParams['date']), fxzt: 0, xxjlid: 901 },
  1780. ],
  1781. students: [{ id: '101', name: '李同学', taskCount: 1 }, { id: '100', name: '张雅茜', taskCount: 1 }],
  1782. page: { itemCount: 2, pageCount: 1 },
  1783. summary: { total: 2, completed: 0, due: 2, today: 0, income: 0 }, dates: [],
  1784. } });
  1785. response.complete();
  1786. api.reviewPageResponse = null;
  1787. harness.fixture.detectChanges();
  1788. const names = Array.from(harness.routeNativeElement?.querySelectorAll('.coach-memory-copy strong') ?? []).map((node) => node.textContent);
  1789. expect(names).toEqual(['张雅茜', '李同学']);
  1790. const home = harness.fixture.debugElement.query(By.directive(HomePageComponent)).componentInstance as HomePageComponent;
  1791. expect(home.coachReviewStudent({ yhid: 102, honeyName: '', HoneyName: ' ', Title: '王同学@复习' })).toBe('王同学');
  1792. expect(home.coachReviewStudent({ yhid: 103, honeyName: '', Title: ' ' })).toBe('学员 103');
  1793. expect(home.coachReviewStudent({ honeyName: '' })).toBe('未关联学员');
  1794. (harness.routeNativeElement?.querySelectorAll('.coach-memory-list article > button')[1] as HTMLButtonElement).click();
  1795. await harness.fixture.whenStable();
  1796. expect(session.student()).toEqual(jasmine.objectContaining({ userId: 101, honeyName: '李同学' }));
  1797. expect(TestBed.inject(Router).url).toContain('/pages/stu/record?id=901&gid=103');
  1798. });
  1799. it('keeps the complete point-reading flow available to coaches', async () => {
  1800. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1801. session.groupId.set(3);
  1802. const harness = await RouterTestingHarness.create();
  1803. await harness.navigateByUrl('/pages/home/index');
  1804. await harness.fixture.whenStable();
  1805. harness.fixture.detectChanges();
  1806. const coachLinks = Array.from(harness.routeNativeElement?.querySelectorAll('.coach-quick-grid > a') ?? []).map((link) => link.getAttribute('href'));
  1807. expect(coachLinks).toEqual(['/pages/home/shop', '/pages/member/ke_xiao', '/pages/his/his', '/pages/member/ke_fuxi', '/pages/member/starshop']);
  1808. expect(harness.routeNativeElement?.querySelector('.home-header .header-action')).toBeNull();
  1809. const coachAccountTab = (Array.from(harness.fixture.nativeElement.querySelectorAll('.tabbar a')) as HTMLAnchorElement[])
  1810. .find((link) => link.getAttribute('href') === '/pages/home/ucenter');
  1811. expect(coachAccountTab?.textContent).toContain('我的');
  1812. expect(harness.routeNativeElement?.querySelector('.content-section')).toBeNull();
  1813. const memoryApi = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1814. expect(memoryApi.lastMemoryParams).toEqual(jasmine.objectContaining({ uid: 300, pageSize:100, scope:'today', includeMetadata:false, includeIncome:false }));
  1815. expect(harness.routeNativeElement?.querySelector('.coach-memory-board')?.textContent).toContain('抗遗忘带练');
  1816. expect(harness.routeNativeElement?.querySelector('.coach-memory-board')?.textContent).toContain('张雅茜');
  1817. expect(harness.routeNativeElement?.querySelector('.coach-memory-list article.ready > button')?.textContent).toContain('查看计划');
  1818. expect(harness.routeNativeElement?.querySelector('.coach-memory-footer')?.getAttribute('href')).toBe('/pages/stu/stu_calendar');
  1819. (harness.routeNativeElement?.querySelector('.coach-memory-list article.ready > button') as HTMLButtonElement).click();
  1820. await harness.fixture.whenStable();
  1821. expect(TestBed.inject(Router).url).toContain('/pages/stu/record?id=900&gid=102');
  1822. expect(session.student()?.userId).toBe(100);
  1823. await harness.navigateByUrl('/pages/stu/stu_calendar');
  1824. const calendarComponent=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  1825. calendarComponent.memoryMonth.set(new Date(2026,7,1));
  1826. calendarComponent.memorySelectedDate.set('2026-08-02');
  1827. (calendarComponent as any).loadCalendar();
  1828. harness.fixture.detectChanges();
  1829. await harness.fixture.whenStable();
  1830. harness.fixture.detectChanges();
  1831. expect(memoryApi.lastMemoryParams).toEqual(jasmine.objectContaining({ uid: 300, pageSize:20 }));
  1832. expect(harness.routeNativeElement?.querySelector('.memory-copy')?.textContent).toContain('关联学员抗遗忘任务');
  1833. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('张雅茜');
  1834. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks button')?.textContent).toContain('带学生复习');
  1835. const memoryStudentFilter = harness.routeNativeElement?.querySelector('[aria-label="筛选抗遗忘学员"] select') as HTMLSelectElement;
  1836. expect(memoryStudentFilter.options.length).toBe(2);
  1837. memoryStudentFilter.value = '100';
  1838. memoryStudentFilter.dispatchEvent(new Event('change'));
  1839. harness.fixture.detectChanges();
  1840. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).toContain('张雅茜');
  1841. expect(harness.routeNativeElement?.querySelector('.memory-date-tasks')?.textContent).not.toContain('李同学');
  1842. expect(harness.routeNativeElement?.querySelector('.memory-stats')?.textContent).toContain('2 / 3');
  1843. await harness.navigateByUrl('/pages/member/ke_xiao');
  1844. await harness.fixture.whenStable();
  1845. harness.fixture.detectChanges();
  1846. const monthFilter = harness.routeNativeElement?.querySelector('[aria-label="按月份筛选陪练记录"]') as HTMLSelectElement;
  1847. const monthPicker = harness.routeNativeElement?.querySelector('.month-control .xs-dropdown-trigger') as HTMLButtonElement;
  1848. expect(monthFilter.value).toBe('all');
  1849. expect(monthFilter.options.length).toBe(4);
  1850. expect(monthPicker).not.toBeNull();
  1851. expect(Number.parseFloat(getComputedStyle(monthPicker).paddingLeft)).toBeGreaterThanOrEqual(40);
  1852. expect(monthPicker.getBoundingClientRect().height).toBe(46);
  1853. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(5);
  1854. monthFilter.value = '2026-03';
  1855. monthFilter.dispatchEvent(new Event('change'));
  1856. const studentSelect = harness.routeNativeElement?.querySelector('select[aria-label="按学员筛选陪练记录"]') as HTMLSelectElement;
  1857. expect(harness.routeNativeElement?.querySelector('input[type="search"]')).toBeNull();
  1858. studentSelect.value = '102';
  1859. studentSelect.dispatchEvent(new Event('change'));
  1860. expect(memoryApi.lastScheduleParams['studentId']).toBe('102');
  1861. expect(memoryApi.lastScheduleParams['search']).toBeUndefined();
  1862. harness.fixture.detectChanges();
  1863. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(1);
  1864. expect(harness.routeNativeElement?.querySelector('.schedule-list')?.textContent).toContain('花花');
  1865. expect(harness.routeNativeElement?.querySelector('.schedule-band > header')?.textContent).toContain('5 节');
  1866. (harness.routeNativeElement?.querySelector('.history-filter-panel footer button:last-child') as HTMLButtonElement).click();
  1867. harness.fixture.detectChanges();
  1868. expect(harness.routeNativeElement?.querySelectorAll('.schedule-list article').length).toBe(5);
  1869. await harness.navigateByUrl('/pages/his/his');
  1870. await harness.fixture.whenStable();
  1871. harness.fixture.detectChanges();
  1872. expect((harness.routeNativeElement?.querySelector('.student-filter select') as HTMLSelectElement).selectedOptions[0]?.textContent).toContain('张雅茜');
  1873. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(2);
  1874. expect(session.student()?.userId).toBe(100);
  1875. (harness.routeNativeElement?.querySelector('.learning-record-card .learning-item') as HTMLElement).click();
  1876. await harness.fixture.whenStable();
  1877. harness.fixture.detectChanges();
  1878. expect(TestBed.inject(Router).url).toBe('/pages/his/his_words?id=201');
  1879. expect(harness.routeNativeElement?.querySelector('.readonly-word-header')?.textContent).toContain('历史记录');
  1880. expect(harness.routeNativeElement?.querySelector('.readonly-word-card')?.textContent).toContain('apple');
  1881. expect(harness.routeNativeElement?.querySelector('.readonly-word-card')?.textContent).toContain('共 1 个单词');
  1882. expect(harness.routeNativeElement?.querySelector('.selection-header')).toBeNull();
  1883. await harness.navigateByUrl('/pages/his/his');
  1884. await harness.fixture.whenStable();
  1885. harness.fixture.detectChanges();
  1886. const teacherCourse = harness.routeNativeElement?.querySelector('.current-learning-list button') as HTMLButtonElement;
  1887. expect(teacherCourse.disabled).toBeFalse();
  1888. expect(teacherCourse.classList.contains('readonly')).toBeFalse();
  1889. expect(teacherCourse.textContent).toContain('选择本次学习单元');
  1890. teacherCourse.click();
  1891. await harness.fixture.whenStable();
  1892. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_list');
  1893. await harness.navigateByUrl('/pages/home/ucenter');
  1894. await harness.fixture.whenStable();
  1895. harness.fixture.detectChanges();
  1896. const teacherServices = Array.from(harness.routeNativeElement?.querySelectorAll('.service-grid > a') ?? []).map((link) => link.getAttribute('href'));
  1897. expect(teacherServices).toEqual(['/pages/home/shop', '/pages/member/ke_xiao', '/pages/his/his', '/pages/member/feedback']);
  1898. expect(harness.routeNativeElement?.querySelector('.coach-wallet-strip')?.textContent).toContain('累计抗遗忘费用');
  1899. await harness.navigateByUrl('/pages/stu/stu_list?nid=801&bindingId=701');
  1900. await harness.fixture.whenStable();
  1901. harness.fixture.detectChanges();
  1902. expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastNodeParams['userId']).toBe(100);
  1903. const units = harness.routeNativeElement?.querySelectorAll('.node-list button') as NodeListOf<HTMLButtonElement>;
  1904. units[0].click();
  1905. units[1].click();
  1906. harness.fixture.detectChanges();
  1907. expect(harness.routeNativeElement?.querySelector('.unit-selection-summary')?.textContent).toContain('已选 2 个单元');
  1908. (harness.routeNativeElement?.querySelector('.unit-actions .primary-button') as HTMLButtonElement).click();
  1909. await harness.fixture.whenStable();
  1910. harness.fixture.detectChanges();
  1911. const router = TestBed.inject(Router);
  1912. expect(router.url).toContain('/pages/stu/stu_abc');
  1913. expect(harness.routeNativeElement?.querySelector('.pending-column')?.textContent).toContain('banana');
  1914. expect(harness.routeNativeElement?.querySelector('.completed-column')).toBeNull();
  1915. expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(1);
  1916. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  1917. harness.fixture.detectChanges();
  1918. expect(harness.routeNativeElement?.querySelector('.completed-column')?.textContent).toContain('apple');
  1919. expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
  1920. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[0] as HTMLButtonElement).click();
  1921. harness.fixture.detectChanges();
  1922. const firstWord = harness.routeNativeElement?.querySelector('.pending-column .word-refine-item') as HTMLElement;
  1923. (firstWord.querySelector('.word-reveal') as HTMLButtonElement).click();
  1924. harness.fixture.detectChanges();
  1925. (firstWord.querySelector('.known-button') as HTMLButtonElement).click();
  1926. harness.fixture.detectChanges();
  1927. expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(0);
  1928. expect(harness.routeNativeElement?.querySelector('.selection-header .primary-button')?.textContent).toContain('保存识词结果');
  1929. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  1930. harness.fixture.detectChanges();
  1931. expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(2);
  1932. (harness.routeNativeElement?.querySelector('.completed-column .word-assessment:has(.known-button.active) .unknown-button') as HTMLButtonElement).click();
  1933. harness.fixture.detectChanges();
  1934. expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(1);
  1935. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[0] as HTMLButtonElement).click();
  1936. harness.fixture.detectChanges();
  1937. expect(harness.routeNativeElement?.querySelectorAll('.pending-column .word-refine-item').length).toBe(1);
  1938. (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  1939. await harness.fixture.whenStable();
  1940. harness.fixture.detectChanges();
  1941. expect(router.url).toContain('/pages/stu/stu_con');
  1942. expect(harness.routeNativeElement?.querySelectorAll('.repeat-list > button').length).toBe(1);
  1943. expect(harness.routeNativeElement?.querySelector('.readonly-word-header')).toBeNull();
  1944. await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&bindingId=701');
  1945. await harness.fixture.whenStable();
  1946. harness.fixture.detectChanges();
  1947. const spellingActions = harness.routeNativeElement?.querySelector('.teacher-spelling-actions') as HTMLElement;
  1948. expect(spellingActions.querySelectorAll('button').length).toBe(3);
  1949. expect(spellingActions.textContent).toContain('跳过这一关');
  1950. expect((harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent).words().length).toBe(1);
  1951. expect(localStorage.getItem('xiaoshu.learning.300.100.701._page_word_orilist')).not.toBeNull();
  1952. (spellingActions.querySelectorAll('button')[1] as HTMLButtonElement).click();
  1953. await harness.fixture.whenStable();
  1954. harness.fixture.detectChanges();
  1955. expect(router.url).toBe('/pages/his/his');
  1956. const standaloneRecord = (TestBed.inject(ApiService) as unknown as LearningModulesApiService).lastStandaloneLearningRecord;
  1957. expect(JSON.parse(String(standaloneRecord['content']))).toEqual(jasmine.objectContaining({ ModelID: 56, Hits: 1, title: '张雅茜' }));
  1958. expect(JSON.parse(String(standaloneRecord['addon']))).toEqual(jasmine.objectContaining({ UserID: 100, pl: 300, learned: 1, createReviewPlan: false }));
  1959. }, 20000);
  1960. it('loads appointment courses and units for the appointment student when no student is selected in the session', async () => {
  1961. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1962. session.groupId.set(3);
  1963. session.student.set(null);
  1964. const harness = await RouterTestingHarness.create();
  1965. await harness.navigateByUrl('/pages/shop/get_order?id=901');
  1966. await harness.fixture.whenStable();
  1967. harness.fixture.detectChanges();
  1968. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1969. expect(session.student()?.userId).toBe(100);
  1970. expect(api.lastAppointmentCourseParams['orderId']).toBe('901');
  1971. expect(api.lastNodeParams['userId']).toBe(100);
  1972. const courseSelect = harness.routeNativeElement?.querySelector('.course-section select') as HTMLSelectElement;
  1973. expect(courseSelect).not.toBeNull();
  1974. expect(courseSelect.options.length).toBeGreaterThanOrEqual(2);
  1975. expect(courseSelect.closest('.course-section')?.textContent).toContain('七年级上册');
  1976. expect(harness.routeNativeElement?.querySelectorAll('.unit-grid article').length).toBe(2);
  1977. const unitButtons = harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.unit-select');
  1978. expect(unitButtons?.[0].textContent).toContain('已学 5%');
  1979. expect(unitButtons?.[0].textContent).toContain('1/20 词');
  1980. expect(unitButtons?.[1].textContent).toContain('已学 0%');
  1981. expect(unitButtons?.[1].textContent).toContain('0/18 词');
  1982. expect((unitButtons?.[0].querySelector('.unit-progress-track > span') as HTMLElement).style.width).toBe('5%');
  1983. unitButtons?.[0].click();
  1984. unitButtons?.[1].click();
  1985. harness.fixture.detectChanges();
  1986. expect(harness.routeNativeElement?.querySelectorAll('.unit-select[aria-pressed="true"]').length).toBe(2);
  1987. expect(unitButtons?.[0].textContent).toContain('已学 5%');
  1988. });
  1989. it('distinguishes completed, empty and unavailable appointment vocabulary progress', async () => {
  1990. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  1991. session.groupId.set(3);
  1992. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  1993. api.unitRows = [
  1994. { NodeID: 811, NodeName: '已学全册', yx_word: '20', total: '20' },
  1995. { NodeID: 812, NodeName: '空册', yx_word: 0, total: 0 },
  1996. { NodeID: 813, NodeName: '缺少统计' },
  1997. { NodeID: 814, NodeName: '异常统计', yx_word: 'invalid', total: 20 },
  1998. ];
  1999. const harness = await RouterTestingHarness.create();
  2000. await harness.navigateByUrl('/pages/shop/get_order?id=901');
  2001. await harness.fixture.whenStable();
  2002. harness.fixture.detectChanges();
  2003. const units = harness.routeNativeElement?.querySelectorAll('.unit-select');
  2004. expect(units?.[0].textContent).toContain('已学 100%');
  2005. expect(units?.[0].textContent).toContain('20/20 词');
  2006. expect(units?.[1].textContent).toContain('已学 0%');
  2007. expect(units?.[1].textContent).toContain('暂无单词');
  2008. for (const index of [2, 3]) {
  2009. expect(units?.[index].textContent).toContain('暂无进度数据');
  2010. expect(units?.[index].querySelector('.unit-progress-track')).toBeNull();
  2011. }
  2012. });
  2013. it('ends without requiring feedback and keeps lesson pay out of the completion notice', async () => {
  2014. user.set({userId:300,userName:'coach',honeyName:'张老师',groupId:3});session.groupId.set(3);
  2015. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
  2016. spyOn(TestBed.inject(PlatformService),'confirm').and.resolveTo(true);
  2017. const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/shop/get_order?id=901');await harness.fixture.whenStable();harness.fixture.detectChanges();
  2018. const component=harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
  2019. await component.endLesson();expect(api.completionRequests.length).toBe(1);expect(api.completionRequests[0]['feedback']).toBeUndefined();
  2020. api.appointmentStatus=30;api.completionResponse.next({retcode:0,result:{status:30,teacherPay:45,payStatus:'earned',feedbackStatus:'pending'}});api.completionResponse.complete();
  2021. harness.fixture.detectChanges();expect(harness.routeNativeElement?.textContent).toContain('已结课');expect(harness.routeNativeElement?.textContent).not.toMatch(/费用|¥45/);expect(harness.routeNativeElement?.textContent).toContain('反馈待补');
  2022. });
  2023. it('retains the optional feedback-and-complete dialog and submits once after validation', async () => {
  2024. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2025. session.groupId.set(3);
  2026. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2027. api.appointmentStatus = 10;
  2028. const harness = await RouterTestingHarness.create();
  2029. await harness.navigateByUrl('/pages/shop/get_order?id=901');
  2030. const component = harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
  2031. await harness.fixture.whenStable();
  2032. harness.fixture.detectChanges();
  2033. const dialog = harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement;
  2034. const endButton = harness.routeNativeElement?.querySelector('.appointment-actions .primary-button') as HTMLButtonElement;
  2035. expect(dialog.open).toBeFalse();
  2036. component.openCompletionFeedback();
  2037. harness.fixture.detectChanges();
  2038. expect(dialog.open).toBeTrue();
  2039. expect(api.completionRequests.length).toBe(0);
  2040. const submit = dialog.querySelector('.feedback-actions .primary-button') as HTMLButtonElement;
  2041. submit.click();
  2042. harness.fixture.detectChanges();
  2043. expect(dialog.querySelector('[role="alert"]')?.textContent).toContain('请填写本次学习内容');
  2044. expect(api.completionRequests.length).toBe(0);
  2045. const summary = dialog.querySelector('textarea') as HTMLTextAreaElement;
  2046. summary.value = 'Unit 3 词汇';
  2047. summary.dispatchEvent(new Event('input'));
  2048. await harness.fixture.whenStable();
  2049. (dialog.querySelector('.feedback-actions .secondary-button') as HTMLButtonElement).click();
  2050. expect(dialog.open).toBeFalse();
  2051. expect(api.appointmentStatus).toBe(10);
  2052. component.openCompletionFeedback();
  2053. harness.fixture.detectChanges();
  2054. expect((dialog.querySelector('textarea') as HTMLTextAreaElement).value).toBe('Unit 3 词汇');
  2055. component.reviewStatus = '完成';
  2056. component.trainingStatus = '需要巩固';
  2057. component.trainingSummary = '下次复习 Unit 3';
  2058. component.noHomework = true;
  2059. submit.click();
  2060. submit.click();
  2061. harness.fixture.detectChanges();
  2062. expect(api.completionRequests.length).toBe(1);
  2063. expect(JSON.parse(String(api.completionRequests[0]['feedback']))).toEqual(jasmine.objectContaining({ contentSummary: 'Unit 3 词汇', noHomework: true, homework: '无作业' }));
  2064. expect(submit.disabled).toBeTrue();
  2065. dialog.dispatchEvent(new Event('cancel', { cancelable: true }));
  2066. expect(dialog.open).toBeTrue();
  2067. api.appointmentStatus = 30;
  2068. api.completionResponse.next({ retcode: 1, result: {} });
  2069. api.completionResponse.complete();
  2070. await harness.fixture.whenStable();
  2071. harness.fixture.detectChanges();
  2072. expect(harness.routeNativeElement?.querySelector('dialog')).toBeNull();
  2073. expect(harness.routeNativeElement?.textContent).toContain('已结课');
  2074. });
  2075. it('keeps feedback editable after a failed submission and allows closing with Escape', async () => {
  2076. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2077. session.groupId.set(3);
  2078. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2079. api.appointmentStatus = 10;
  2080. const harness = await RouterTestingHarness.create();
  2081. await harness.navigateByUrl('/pages/shop/get_order?id=901');
  2082. const component = harness.fixture.debugElement.query(By.directive(AppointmentPageComponent)).componentInstance as AppointmentPageComponent;
  2083. await harness.fixture.whenStable();
  2084. component.openCompletionFeedback();
  2085. component.contentSummary = 'Unit 3';
  2086. component.reviewStatus = '完成';
  2087. component.trainingStatus = '正常进行';
  2088. component.trainingSummary = '继续 Unit 4';
  2089. component.noHomework = true;
  2090. component.finishCoachLesson();
  2091. api.completionResponse.error(new Error('提交失败,请重试'));
  2092. harness.fixture.detectChanges();
  2093. const dialog = harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement;
  2094. expect(dialog.open).toBeTrue();
  2095. expect(dialog.querySelector('[role="alert"]')?.textContent).toContain('提交失败,请重试');
  2096. expect((dialog.querySelector('fieldset') as HTMLFieldSetElement).disabled).toBeFalse();
  2097. expect(component.contentSummary).toBe('Unit 3');
  2098. expect(api.appointmentStatus).toBe(10);
  2099. dialog.dispatchEvent(new Event('cancel', { cancelable: true }));
  2100. expect(dialog.open).toBeFalse();
  2101. });
  2102. it('counts words marked as known as completed and persists them for the student', async () => {
  2103. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2104. session.groupId.set(3);
  2105. session.student.set({ userId: 100, userName: 'student', honeyName: '张雅茜', groupId: 1 });
  2106. const harness = await RouterTestingHarness.create();
  2107. await harness.navigateByUrl('/pages/stu/stu_abc?nids=811,812&pnid=801');
  2108. await harness.fixture.whenStable();
  2109. harness.fixture.detectChanges();
  2110. const pendingWord = harness.routeNativeElement?.querySelector('.pending-column .word-refine-item') as HTMLElement;
  2111. (pendingWord.querySelector('.word-reveal') as HTMLButtonElement).click();
  2112. harness.fixture.detectChanges();
  2113. (pendingWord.querySelector('.known-button') as HTMLButtonElement).click();
  2114. harness.fixture.detectChanges();
  2115. (harness.routeNativeElement?.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  2116. await harness.fixture.whenStable();
  2117. harness.fixture.detectChanges();
  2118. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2119. expect(api.lastLearningWordUpdate).toEqual(jasmine.objectContaining({ uid: 100, wordsId: '1002', kcid: '801', save: 1 }));
  2120. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');
  2121. expect(harness.routeNativeElement?.querySelector('.completed-column')).toBeNull();
  2122. (harness.routeNativeElement?.querySelectorAll('.word-selection-tabs button')[1] as HTMLButtonElement).click();
  2123. harness.fixture.detectChanges();
  2124. expect(harness.routeNativeElement?.querySelectorAll('.completed-column .word-refine-item').length).toBe(2);
  2125. expect(harness.routeNativeElement?.querySelector('.pending-column')).toBeNull();
  2126. });
  2127. it('confirms three rounds into 17 words and can continue selecting before ending the lesson', async () => {
  2128. user.set({userId:300,groupId:3}); session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2129. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
  2130. api.studyBatches=[9,5,3].map((count,index)=>({batchId:'round-'+index,version:1,status:'draft',bindingId:'binding-801',words:Array.from({length:count},(_,i)=>({GeneralID:index*100+i+1,Title:'word'+index+'-'+i,check:0}))}));
  2131. const harness=await RouterTestingHarness.create();
  2132. for(let index=0;index<3;index++){
  2133. await harness.navigateByUrl('/pages/stu/pl_end?orderId=901&bindingId=binding-801&batchId=round-'+index);await harness.fixture.whenStable();harness.fixture.detectChanges();
  2134. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2135. expect(component.words().length).toBe([9,5,3][index]);component.markAllKnown();component.submitReview(index<2);await harness.fixture.whenStable();harness.fixture.detectChanges();
  2136. expect(TestBed.inject(Router).url).toBe('/pages/shop/get_order?id=901'+(index===2?'&feedback=1':''));
  2137. expect(harness.routeNativeElement?.textContent).toContain('本节学习成果 · '+[9,14,17][index]+' 个词');
  2138. }
  2139. expect(api.completionRequests.length).toBe(0);
  2140. });
  2141. it('reveals and speaks each assessment word without changing mastery', async () => {
  2142. user.set({userId:300,groupId:3});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2143. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
  2144. api.studyBatches=[{batchId:'meaning-round',version:1,status:'draft',bindingId:'binding-801',words:[{GeneralID:1001,Title:'crop',sy:'庄稼',check:1},{GeneralID:1002,Title:'gather',sy:'聚集',check:2}]}];
  2145. const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/stu/pl_end?orderId=901&bindingId=binding-801&batchId=meaning-round');await harness.fixture.whenStable();harness.fixture.detectChanges();
  2146. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2147. const play=spyOn(component,'play').and.resolveTo();const cards=harness.routeNativeElement!.querySelectorAll('.review-list article');
  2148. expect(cards[0].textContent).not.toContain('庄稼');(cards[0].querySelector('.word-audio') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2149. expect(play).toHaveBeenCalledWith(component.words()[0]);expect(cards[0].textContent).toContain('庄稼');expect(cards[1].textContent).not.toContain('聚集');
  2150. expect(component.reviewValue(component.words()[0])).toBe(1);expect(component.reviewValue(component.words()[1])).toBe(2);
  2151. (cards[0].querySelector('.word-audio') as HTMLButtonElement).click();harness.fixture.detectChanges();expect(cards[0].textContent).not.toContain('庄稼');expect(play).toHaveBeenCalledTimes(2);
  2152. });
  2153. it('keeps round choices on save failure and retries with the same command key', async () => {
  2154. user.set({userId:300,groupId:3});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2155. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;api.appointmentStatus=10;
  2156. api.studyBatches=[{batchId:'retry-round',version:1,status:'draft',bindingId:'binding-801',courseId:'802',words:[{GeneralID:1001,Title:'apple',check:0}]}];
  2157. const post=api.post.bind(api);let fail=true;const spy=spyOn(api,'post').and.callFake((action,params)=>action==='stu_record_update_v2'&&fail?(fail=false,throwError(()=>new Error('断网'))):post(action,params));
  2158. const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/stu/pl_end?orderId=901&bindingId=binding-801&batchId=retry-round');await harness.fixture.whenStable();harness.fixture.detectChanges();
  2159. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;component.markAllKnown();component.submitReview(true);await harness.fixture.whenStable();
  2160. expect(component.words().length).toBe(1);expect(component.reviewCount(1)).toBe(1);expect(TestBed.inject(Router).url).toContain('/pl_end');
  2161. component.submitReview(true);await harness.fixture.whenStable();const requests=spy.calls.allArgs().filter(([action])=>action==='stu_record_update_v2');expect(requests.length).toBe(2);expect(requests[0][1]?.['requestKey']).toBe(requests[1][1]?.['requestKey']);
  2162. expect(api.lastLearningWordUpdate['kcid']).toBe('802'); // Resume uses the batch book, not the scheduled book.
  2163. });
  2164. it('finishes the last vocabulary group, loads the coach record and opens completion feedback', async () => {
  2165. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2166. session.groupId.set(3);
  2167. session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
  2168. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2169. api.appointmentStatus = 10;
  2170. const word = { GeneralID: 1001, NodeID: 811, Title: 'apple', sy: '苹果' };
  2171. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_word_orilist', JSON.stringify([[word]]));
  2172. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_current_learn', '1');
  2173. // Stale page-count metadata must not create a nonexistent next group.
  2174. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_total_page', '2');
  2175. localStorage.removeItem('xiaoshu.learning.300.100.901.unbound.learn_mode');
  2176. const harness = await RouterTestingHarness.create();
  2177. const router = TestBed.inject(Router);
  2178. const navigate = spyOn(router, 'navigate').and.callThrough();
  2179. await harness.navigateByUrl('/pages/stu/stu_con?nids=811&pnid=801&orderId=901');
  2180. await harness.fixture.whenStable();
  2181. harness.fixture.detectChanges();
  2182. const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2183. const skipStage = () => {
  2184. const button = Array.from(harness.routeNativeElement?.querySelectorAll<HTMLButtonElement>('.sticky-actions button') ?? [])
  2185. .find(item => item.textContent?.includes('跳过这一关'));
  2186. expect(button).toBeDefined();
  2187. button!.click();
  2188. };
  2189. skipStage();
  2190. await harness.fixture.whenStable();
  2191. harness.fixture.detectChanges();
  2192. expect(router.url).toContain('/pages/stu/stu3');
  2193. expect(learning().matchLeft().length).toBe(1);
  2194. skipStage();
  2195. await harness.fixture.whenStable();
  2196. harness.fixture.detectChanges();
  2197. expect(router.url).toContain('/pages/stu/stu4');
  2198. expect(learning().correct()).toBe(0);
  2199. skipStage();
  2200. await harness.fixture.whenStable();
  2201. harness.fixture.detectChanges();
  2202. expect(router.url).toContain('/pages/stu/pl_stu5');
  2203. expect(router.url).toContain('orderId=901');
  2204. expect(learning().correct()).toBe(0);
  2205. skipStage();
  2206. expect(learning().hasNextWordBatch).toBeFalse();
  2207. await harness.fixture.whenStable();
  2208. harness.fixture.detectChanges();
  2209. harness.fixture.detectChanges();
  2210. expect(router.url).toContain('/pages/stu/pl_end');
  2211. expect(api.lastStudyQuery['orderId']).toBe('901');
  2212. expect(harness.routeNativeElement?.querySelector('.empty-state.error')).toBeNull();
  2213. expect(learning().words()[0].word).toBe('apple');
  2214. learning().markAllKnown();
  2215. learning().submitReview();
  2216. await harness.fixture.whenStable();
  2217. harness.fixture.detectChanges();
  2218. harness.fixture.detectChanges();
  2219. expect(router.url).toBe('/pages/shop/get_order?id=901&feedback=1');
  2220. expect((harness.routeNativeElement?.querySelector('dialog') as HTMLDialogElement).open).toBeTrue();
  2221. expect(api.appointmentStatus).toBe(10);
  2222. expect(api.completionRequests.length).toBe(0);
  2223. expect(api.studyUpdates.length).toBe(2);
  2224. expect(JSON.parse(String(api.studyUpdates[1]['addon'])).xxqs[0].check).toBe(1);
  2225. expect(navigate.calls.all().every(call => call.args[1]?.replaceUrl === true)).toBeTrue();
  2226. }, 20000);
  2227. it('advances only to a real next group and returns from the last stage to its course in one click', async () => {
  2228. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2229. session.groupId.set(3);
  2230. session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
  2231. const pages = [[{ GeneralID: 1001, Title: 'apple', sy: '苹果' }, { GeneralID: 1002, Title: 'banana', sy: '香蕉' }], [{ GeneralID: 1003, Title: 'cherry', sy: '樱桃' }]];
  2232. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_word_orilist', JSON.stringify(pages));
  2233. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_total_page', '0');
  2234. localStorage.setItem('xiaoshu.learning.300.100.901.unbound._page_current_learn', '1');
  2235. const harness = await RouterTestingHarness.create();
  2236. const router = TestBed.inject(Router);
  2237. await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&orderId=901');
  2238. await harness.fixture.whenStable();
  2239. harness.fixture.detectChanges();
  2240. const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2241. expect(component.words().length).toBe(2);
  2242. component.skipSpellingStage();
  2243. await harness.fixture.whenStable();
  2244. harness.fixture.detectChanges();
  2245. expect(router.url).toContain('/pages/stu/stu_con');
  2246. const next = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2247. expect(next.words()[0].word).toBe('cherry');
  2248. expect((TestBed.inject(ApiService) as unknown as LearningModulesApiService).studyUpdates.length).toBe(0);
  2249. (harness.routeNativeElement?.querySelector('.app-header button[aria-label="返回"]') as HTMLButtonElement).click();
  2250. await harness.fixture.whenStable();
  2251. harness.fixture.detectChanges();
  2252. expect(router.url).toBe('/pages/shop/get_order?id=901');
  2253. for (const key of ['_page_word_orilist', '_page_total_page', '_page_current_learn', 'skip_spelling_stage']) localStorage.removeItem(`xiaoshu.learning.300.100.901.unbound.${key}`);
  2254. });
  2255. it('keeps teacher-led spelling skipped through the remaining word groups', async () => {
  2256. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2257. session.groupId.set(3);
  2258. session.student.set({ userId: 100, honeyName: '张雅茜', groupId: 1 });
  2259. const prefix = 'xiaoshu.learning.300.100.901.unbound.';
  2260. const pages = [[{ GeneralID: 1001, Title: 'apple', sy: '苹果' }], [{ GeneralID: 1002, Title: 'banana', sy: '香蕉' }]];
  2261. localStorage.setItem(prefix + '_page_word_orilist', JSON.stringify(pages));
  2262. localStorage.setItem(prefix + '_page_current_learn', '1');
  2263. const harness = await RouterTestingHarness.create();
  2264. const router = TestBed.inject(Router);
  2265. await harness.navigateByUrl('/pages/stu/pl_stu5?nids=811&pnid=801&orderId=901');
  2266. const learning = () => harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2267. learning().skipSpellingStage();
  2268. await harness.fixture.whenStable();
  2269. harness.fixture.detectChanges();
  2270. expect(router.url).toContain('/pages/stu/stu_con');
  2271. expect(localStorage.getItem(prefix + 'skip_spelling_stage')).toBe('true');
  2272. learning().skipStudyList();
  2273. await harness.fixture.whenStable();
  2274. harness.fixture.detectChanges();
  2275. learning().chooseMatch('left', learning().words()[0]);
  2276. learning().chooseMatch('right', learning().words()[0]);
  2277. learning().continueAfterStage();
  2278. await harness.fixture.whenStable();
  2279. harness.fixture.detectChanges();
  2280. expect(router.url).toContain('/pages/stu/stu4');
  2281. learning().chooseMeaning(learning().words()[0]);
  2282. expect(learning().stageActionLabel).toBe('查看学习结果');
  2283. learning().continueAfterStage();
  2284. await harness.fixture.whenStable();
  2285. expect(router.url).toContain('/pages/stu/pl_end');
  2286. expect(localStorage.getItem(prefix + 'skip_spelling_stage')).toBe('true');
  2287. localStorage.removeItem(prefix + 'skip_spelling_stage');
  2288. }, 15000);
  2289. it('resolves the appointment student before reading end results and offers an exit on failure', async () => {
  2290. user.set({ userId: 300, userName: 'coach', honeyName: '张老师', groupId: 3 });
  2291. session.groupId.set(3);
  2292. session.student.set({ userId: 999, honeyName: '之前的学员', groupId: 1 });
  2293. const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2294. const get = api.get.bind(api);
  2295. spyOn(api, 'get').and.callFake((action, params) => action === 'app_lesson_study'
  2296. ? throwError(() => new Error('学习记录暂时无法加载')) : get(action, params));
  2297. const harness = await RouterTestingHarness.create();
  2298. await harness.navigateByUrl('/pages/stu/pl_end?id=901');
  2299. await harness.fixture.whenStable();
  2300. harness.fixture.detectChanges();
  2301. harness.fixture.detectChanges();
  2302. expect(session.student()?.userId).toBe(100);
  2303. expect(api.get).toHaveBeenCalledWith('app_lesson_study', {orderId:'901'});
  2304. expect(harness.routeNativeElement?.querySelector('.empty-state.error')?.textContent).toContain('学习记录暂时无法加载');
  2305. (harness.routeNativeElement?.querySelector('.empty-state.error .primary-button') as HTMLButtonElement).click();
  2306. await harness.fixture.whenStable();
  2307. harness.fixture.detectChanges();
  2308. expect(TestBed.inject(Router).url).toBe('/pages/shop/get_order?id=901');
  2309. });
  2310. it('shows learning history in pages of twenty records', async () => {
  2311. user.set({ userId: 777, userName: 'paged-student', honeyName: '分页学员', groupId: 1 });
  2312. session.groupId.set(1);
  2313. const harness = await RouterTestingHarness.create();
  2314. await harness.navigateByUrl('/pages/his/his');
  2315. await harness.fixture.whenStable();
  2316. harness.fixture.detectChanges();
  2317. expect(harness.routeNativeElement?.querySelector('.record-actions')?.textContent).toContain('45 条');
  2318. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(20);
  2319. expect(harness.routeNativeElement?.querySelector('.record-pagination')?.textContent).toContain('第 1 / 3 页');
  2320. const pageButtons = harness.routeNativeElement?.querySelectorAll('.record-pagination button') as NodeListOf<HTMLButtonElement>;
  2321. expect(pageButtons[0].disabled).toBeTrue();
  2322. pageButtons[1].click();
  2323. harness.fixture.detectChanges();
  2324. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(20);
  2325. expect(harness.routeNativeElement?.querySelector('.record-pagination')?.textContent).toContain('第 2 / 3 页');
  2326. (harness.routeNativeElement?.querySelectorAll('.record-pagination button')[1] as HTMLButtonElement).click();
  2327. harness.fixture.detectChanges();
  2328. expect(harness.routeNativeElement?.querySelectorAll('.learning-record-card .learning-item').length).toBe(5);
  2329. expect((harness.routeNativeElement?.querySelectorAll('.record-pagination button')[1] as HTMLButtonElement).disabled).toBeTrue();
  2330. });
  2331. it('keeps review completion free of pay details for every reward outcome', async()=>{
  2332. user.set({userId:300,groupId:3,honeyName:'老师'});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2333. const harness=await RouterTestingHarness.create('/pages/stu/record?id=900&gid=103');await harness.fixture.whenStable();
  2334. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2335. for (const result of [
  2336. {amount:0.5,rewardStatus:'earned'},
  2337. {amount:1,rewardStatus:'earned',unchanged:true},
  2338. {amount:0,rewardStatus:'ineligible',ineligibleReason:'self_study',unchanged:true},
  2339. {amount:0,rewardStatus:'ineligible',ineligibleReason:'duplicate_review',unchanged:true},
  2340. {amount:0,rewardStatus:'ineligible'},
  2341. {amount:0,rewardStatus:'pending'},
  2342. ]) {
  2343. component.reviewCompletion.set(result);harness.fixture.detectChanges();
  2344. const completion=harness.routeNativeElement?.querySelector('.review-complete');
  2345. expect(completion?.textContent).toContain('复习已完成');
  2346. expect(completion?.textContent).not.toMatch(/收入|费用|计薪|记账|¥/);
  2347. expect(completion?.textContent).toContain('继续今日任务');
  2348. expect(completion?.textContent).toContain('返回原任务列表');
  2349. }
  2350. user.set({userId:100,groupId:1,honeyName:'学生'});session.groupId.set(1);harness.fixture.detectChanges();
  2351. expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).toContain('复习已完成');
  2352. expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).not.toMatch(/收入|费用|计薪|记账|¥/);
  2353. });
  2354. it('waits for server completion and blocks duplicate clicks for overdue work', async()=>{
  2355. user.set({userId:300,groupId:3,honeyName:'老师'});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2356. const api=TestBed.inject(ApiService),post=api.post.bind(api),reply=new Subject<ApiEnvelope<any>>();
  2357. const submit=spyOn(api,'post').and.callFake((action,params)=>action==='app_review_complete'?reply:post(action,params));
  2358. const harness=await RouterTestingHarness.create();await harness.navigateByUrl('/pages/stu/record?id=900&gid=103&plannedDate=2000-01-01');await harness.fixture.whenStable();
  2359. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2360. component.endRecord();component.endRecord();harness.fixture.detectChanges();expect(component.reviewCompletion()).toBeNull();expect(component.canDeactivate()).toBeFalse();
  2361. expect(submit.calls.allArgs().filter(a=>a[0]==='app_review_complete').length).toBe(1);
  2362. reply.next({retcode:1,result:{amount:0,rewardStatus:'ineligible',completed:true}});reply.complete();harness.fixture.detectChanges();
  2363. expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).toContain('复习已完成');expect(harness.routeNativeElement?.querySelector('.review-complete')?.textContent).not.toMatch(/收入|费用|计薪|¥/);expect(component.canDeactivate()).toBeTrue();
  2364. });
  2365. async function teacherSelection(count: number, pass = 0, orderId = '') {
  2366. user.set({userId:300,groupId:3}); session.groupId.set(3); session.student.set({userId:100,groupId:1});
  2367. const api=TestBed.inject(ApiService) as unknown as LearningModulesApiService;
  2368. api.courseWords=Array.from({length:count},(_,i)=>({GeneralID:1001+i,NodeID:811,Title:'word-'+(i+1),sy:'释义 '+(i+1),w_learned:pass}));
  2369. const harness=await RouterTestingHarness.create();
  2370. await harness.navigateByUrl('/pages/stu/stu_abc?nids=811&pnid=801' + (orderId ? '&orderId=' + orderId : ''));
  2371. await harness.fixture.whenStable(); harness.fixture.detectChanges();
  2372. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2373. if(pass>0){component.selectCoursePass(pass);await harness.fixture.whenStable();harness.fixture.detectChanges();}
  2374. return {api,harness,component};
  2375. }
  2376. it('keeps compact known and unknown decisions visible before revealing a word', async () => {
  2377. const {harness,component}=await teacherSelection(2);
  2378. const row=harness.routeNativeElement!.querySelector('.word-refine-item')!;
  2379. expect(component.selectionRevealed().size).toBe(0);
  2380. expect(row.querySelector('.word-refine-main .known-button')?.textContent?.trim()).toBe('认识');
  2381. expect(row.querySelector('.word-refine-main .unknown-button')?.textContent?.trim()).toBe('不认识');
  2382. (row.querySelector('.known-button') as HTMLButtonElement).click(); harness.fixture.detectChanges();
  2383. expect(component.coursePassCount(1)).toBe(1);
  2384. });
  2385. it('saves 205 accumulated known words in bounded requests without losing words', async () => {
  2386. const {api,harness,component}=await teacherSelection(205);
  2387. for(let page=0;page<2;page++){component.loadMoreSelection();await harness.fixture.whenStable();harness.fixture.detectChanges();}
  2388. const original=api.post.bind(api),sizes:number[]=[];
  2389. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2390. if(action==='e_add_words'){const size=String(params['wordsId']).split(',').length;sizes.push(size);if(size>100)return throwError(()=>new Error('单次最多操作 100 个单词'));}
  2391. return original(action,params);
  2392. }) as typeof api.post);
  2393. for(const word of component.words())component.markWordKnown(word);
  2394. component.startSelected();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2395. expect(sizes).toEqual([100,100,5]);
  2396. expect(api.courseIncrements.size).toBe(205);
  2397. expect([...api.courseIncrements.values()].every(n=>n===1)).toBeTrue();
  2398. expect(component.newlyKnownWords().length).toBe(0);
  2399. expect(component.coursePassCount(1)).toBe(205);
  2400. });
  2401. it('retains successful known-word batches when a later request fails and retries only remaining words', async () => {
  2402. const {api,harness,component}=await teacherSelection(205);
  2403. for(let page=0;page<2;page++){component.loadMoreSelection();await harness.fixture.whenStable();}
  2404. const original=api.post.bind(api),requests:Record<string,unknown>[]=[];let failed=false;
  2405. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2406. if(action==='e_add_words'){
  2407. requests.push(params);
  2408. if(String(params['wordsId']).split(',').length>100)return throwError(()=>new Error('单次最多操作 100 个单词'));
  2409. if(requests.length===2&&!failed){failed=true;return throwError(()=>new Error('第二批网络中断'));}
  2410. }
  2411. return original(action,params);
  2412. }) as typeof api.post);
  2413. for(const word of component.words())component.markWordKnown(word);
  2414. component.startSelected();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2415. expect(component.newlyKnownWords().length).toBe(105);
  2416. expect(component.coursePassCounts()?.[1]).toBe(100);
  2417. expect(component.submitting()).toBeFalse();
  2418. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');
  2419. component.startSelected();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2420. expect(requests.map(p=>String(p['wordsId']).split(',').length)).toEqual([100,100,100,5]);
  2421. expect(requests[2]['requestKey']).toBe(requests[1]['requestKey']);
  2422. expect(api.courseIncrements.size).toBe(205);
  2423. expect([...api.courseIncrements.values()].every(n=>n===1)).toBeTrue();
  2424. expect(component.coursePassCount(1)).toBe(205);
  2425. });
  2426. it('selects the visible words, allows exceptions, then saves known words and trains only exceptions', async () => {
  2427. const {api,harness,component}=await teacherSelection(8);
  2428. const view=()=>harness.routeNativeElement!;
  2429. const select=view().querySelector('.bulk-select-toggle') as HTMLButtonElement;
  2430. expect(select).not.toBeNull();select?.click();harness.fixture.detectChanges();
  2431. expect(view().querySelectorAll('.word-select-check[aria-pressed="true"]').length).toBe(8);
  2432. expect(component.selected().size).toBe(0); // Temporary bulk checks do not change the actual learning selection.
  2433. const checks=view().querySelectorAll<HTMLButtonElement>('.word-select-check');checks[1].click();checks[6].click();harness.fixture.detectChanges();
  2434. (view().querySelector('.bulk-assessment .known-button') as HTMLButtonElement).click();
  2435. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2436. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  2437. const learning=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2438. expect(learning.words().map(w=>w.wordId).sort()).toEqual(['1002','1007']);
  2439. expect([...api.courseIncrements.keys()].sort()).toEqual(['1001','1003','1004','1005','1006','1008']);
  2440. });
  2441. it('saves all-known words and opens the learned pass without creating an empty learning round', async () => {
  2442. const {api,harness,component}=await teacherSelection(8);
  2443. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2444. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement)?.click();
  2445. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2446. expect(api.courseIncrements.size).toBe(8);
  2447. expect(component.coursePass()).toBe(1);
  2448. expect(component.visibleCourseWords().length).toBe(8);
  2449. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');
  2450. });
  2451. it('keeps bulk unknown checks intact when they exceed a round and clears them across pass switches', async () => {
  2452. const {api,harness,component}=await teacherSelection(101);
  2453. component.loadMoreSelection();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2454. component.toggleWord(component.words()[100]);
  2455. const toast=spyOn(TestBed.inject(PlatformService),'toast');
  2456. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2457. (harness.routeNativeElement!.querySelector('.bulk-assessment .unknown-button') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2458. expect(toast).toHaveBeenCalledWith(jasmine.stringMatching(/100/),'error');
  2459. expect(harness.routeNativeElement!.querySelectorAll('.word-select-check[aria-pressed="true"]').length).toBe(100);
  2460. expect(component.selected().size).toBe(1);expect(api.courseIncrements.size).toBe(0);
  2461. component.selectCoursePass(1);await harness.fixture.whenStable();harness.fixture.detectChanges();
  2462. expect(harness.routeNativeElement!.querySelector('.bulk-assessment')).toBeNull();
  2463. component.selectCoursePass(0);await harness.fixture.whenStable();harness.fixture.detectChanges();
  2464. expect(harness.routeNativeElement!.querySelectorAll('.word-select-check[aria-pressed="true"]').length).toBe(0);
  2465. });
  2466. it('uses select-all only for loaded words and guards decisions while saving', async () => {
  2467. const {api,harness,component}=await teacherSelection(105);
  2468. const original=api.post.bind(api),response=new Subject<ApiEnvelope<unknown>>();
  2469. const post=spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>action==='e_add_words'?response:original(action,params)) as typeof api.post);
  2470. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2471. expect(harness.routeNativeElement!.querySelectorAll('.word-select-check[aria-pressed="true"]').length).toBe(100);
  2472. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2473. expect(component.submitting()).toBeTrue();
  2474. component.startSelected();component.selectCoursePass(1);
  2475. expect(component.coursePass()).toBe(0);
  2476. expect(post.calls.allArgs().filter(([action])=>action==='e_add_words').length).toBe(1);
  2477. response.next({retcode:1,result:{affected:100}});response.complete();await harness.fixture.whenStable();
  2478. expect(post.calls.allArgs().filter(([action])=>action==='e_add_words').length).toBe(1);
  2479. });
  2480. it('preserves an ambiguous committed batch key by freezing decisions until retry resolves', async () => {
  2481. const {api,harness,component}=await teacherSelection(205);
  2482. for(let page=0;page<2;page++){component.loadMoreSelection();await harness.fixture.whenStable();}
  2483. const original=api.post.bind(api),completed=new Map<string,Observable<ApiEnvelope<any>>>(),requests:Record<string,unknown>[]=[];let lost=false;
  2484. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2485. if(action!=='e_add_words')return original(action,params);
  2486. requests.push(params);const key=String(params['requestKey']);
  2487. if(completed.has(key))return completed.get(key)!;
  2488. const saved=original(action,params);completed.set(key,saved);
  2489. if(!lost){lost=true;return throwError(()=>new Error('服务端已保存但响应丢失'));}
  2490. return saved;
  2491. }) as typeof api.post);
  2492. const first=component.words()[0];
  2493. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2494. for (const word of component.bulkCandidates().slice(100)) component.toggleWord(word);
  2495. harness.fixture.detectChanges();
  2496. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement).click();
  2497. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2498. expect(harness.routeNativeElement!.querySelector('.selection-retry-note')?.textContent).toContain('尚待确认');
  2499. expect(harness.routeNativeElement!.querySelector('.selection-header .primary-button')?.textContent).toContain('重试保存');
  2500. expect(api.courseIncrements.size).toBe(100);
  2501. component.markWordUnknown(first);component.toggleWord(first);component.selectCoursePass(1);component.loadMoreSelection();
  2502. expect(component.selectionAssessment()[first.id]).toBe('known');expect(component.selected().size).toBe(0);expect(component.coursePass()).toBe(0);
  2503. component.startSelected();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2504. expect(requests[1]['requestKey']).toBe(requests[0]['requestKey']);
  2505. expect(requests[1]['wordsId']).toBe(requests[0]['wordsId']);
  2506. expect(api.courseIncrements.size).toBe(205);expect([...api.courseIncrements.values()].every(n=>n===1)).toBeTrue();
  2507. expect(component.coursePass()).toBe(1);expect(harness.routeNativeElement!.querySelector('.selection-retry-note')).toBeNull();
  2508. });
  2509. it('rebases pending pages after saving known words without skipping remaining vocabulary or selections', async () => {
  2510. const {api,harness,component}=await teacherSelection(250);
  2511. const view=()=>harness.routeNativeElement!;
  2512. const checks=()=>view().querySelectorAll<HTMLButtonElement>('.word-select-check');
  2513. checks()[99].click(); // Preserve an existing individual learning choice.
  2514. (view().querySelector('.bulk-select-toggle') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2515. for(let i=60;i<100;i++)checks()[i].click();harness.fixture.detectChanges();
  2516. (view().querySelector('.bulk-assessment .known-button') as HTMLButtonElement).click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2517. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');expect(api.courseIncrements.size).toBe(60);
  2518. const get=api.get.bind(api);let failed=false;
  2519. spyOn(api,'get').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2520. if(action==='e_ck_list'&&Number(params['cpage'])===1&&!failed){failed=true;return throwError(()=>new Error('刷新第一页失败'));}
  2521. return get(action,params);
  2522. }) as typeof api.get);
  2523. component.loadMoreSelection();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2524. expect(component.error()).toBe('');expect(view().querySelector('.word-refine-item')).not.toBeNull();
  2525. component.loadMoreSelection();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2526. component.loadMoreSelection();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2527. expect(component.selectionTotal()).toBe(190);
  2528. expect(component.visibleCourseWords().map(w=>Number(w.wordId)).sort((a,b)=>a-b)).toEqual(Array.from({length:190},(_,i)=>1061+i));
  2529. expect(component.selected().has('1100')).toBeTrue();
  2530. });
  2531. it('treats an individual unknown decision as an exception to bulk known', async () => {
  2532. const {api,harness}=await teacherSelection(3);
  2533. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2534. (harness.routeNativeElement!.querySelector('.word-refine-item .unknown-button') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2535. expect(harness.routeNativeElement!.querySelector('.word-select-check')?.getAttribute('aria-pressed')).toBe('false');
  2536. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement).click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2537. const learning=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2538. expect(learning.words().map(w=>w.wordId)).toEqual(['1001']);expect([...api.courseIncrements.keys()].sort()).toEqual(['1002','1003']);
  2539. });
  2540. it('starts a valid bulk unknown selection without marking those words learned', async () => {
  2541. const {api,harness}=await teacherSelection(3);
  2542. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2543. (harness.routeNativeElement!.querySelector('.bulk-assessment .unknown-button') as HTMLButtonElement).click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2544. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  2545. const learning=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2546. expect(learning.words().length).toBe(3);expect(api.courseIncrements.size).toBe(0);
  2547. });
  2548. for(const pass of [1,2]) {
  2549. it('bulk assesses learned pass '+pass+' and advances only recognized words by one pass', async () => {
  2550. const {api,harness,component}=await teacherSelection(4,pass);
  2551. const view=()=>harness.routeNativeElement!;
  2552. expect(view().querySelector('.bulk-select-toggle')).not.toBeNull();
  2553. expect(view().querySelectorAll('.word-refine-main .known-button').length).toBe(4);
  2554. (view().querySelector('.bulk-select-toggle') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2555. expect(view().querySelectorAll('.word-select-check[aria-pressed="true"]').length).toBe(4);
  2556. (view().querySelectorAll<HTMLButtonElement>('.word-select-check')[3]).click();harness.fixture.detectChanges();
  2557. (view().querySelector('.bulk-assessment .known-button') as HTMLButtonElement)?.click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2558. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  2559. const learning=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2560. expect(learning.words().map(w=>w.wordId)).toEqual(['1004']);
  2561. expect([...api.courseIncrements.keys()].sort()).toEqual(['1001','1002','1003']);
  2562. expect(component.coursePassCount(pass)).toBe(1);expect(component.coursePassCount(pass+1)).toBe(3);
  2563. expect(component.firstPassProgress()).toBe(100);
  2564. });
  2565. }
  2566. it('marks only the requested 20 course words known without learning the other 80', async () => {
  2567. const {api,harness,component} = await teacherSelection(100);
  2568. spyOn(TestBed.inject(PlatformService), 'toast');
  2569. const picker = harness.routeNativeElement!.querySelector<HTMLSelectElement>('.bulk-select-size')!;
  2570. picker.value='20';picker.dispatchEvent(new Event('change'));harness.fixture.detectChanges();
  2571. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2572. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement).click();
  2573. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2574. expect(api.courseIncrements.size).toBe(20);expect(component.selected().size).toBe(0);
  2575. expect(component.coursePassCounts()).toEqual([80,20,0,0]);
  2576. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_abc');
  2577. });
  2578. it('preserves individual wordbook choices when a quantity selection request fails', async () => {
  2579. spyOn(TestBed.inject(PlatformService), 'toast');
  2580. const api=TestBed.inject(ApiService), original=api.get.bind(api), pending=new Subject<ApiEnvelope<unknown>>();
  2581. let reads=0;
  2582. spyOn(api,'get').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2583. if(action!=='e_words_list')return original(action,params);
  2584. if(reads++)return pending;
  2585. return of({retcode:0,result:[{GeneralID:601,detail:[{GeneralID:701,Title:'apple',sy:'苹果'}]}],page:{itemCount:1,pendingCount:1,completedCount:0}});
  2586. }) as typeof api.get);
  2587. const harness=await RouterTestingHarness.create('/pages/member/starshop');
  2588. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2589. const component=harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2590. (harness.routeNativeElement!.querySelector('.word-select-list > button') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2591. (harness.routeNativeElement!.querySelector('.selection-header .quiet-button') as HTMLButtonElement).click();harness.fixture.detectChanges();
  2592. expect(component.selectionLoading()).toBeTrue();
  2593. pending.error(new Error('temporary failure'));harness.fixture.detectChanges();
  2594. expect([...component.selected()]).toEqual(['701']);expect(component.selectionLoading()).toBeFalse();
  2595. });
  2596. for (const entry of ['course-0', 'course-1', 'course-2', 'coach-wordbook', 'student-wordbook']) for (const startCount of [20,50,100]) {
  2597. it(`selects only the requested quantity and starts ${startCount} words for ${entry}`, async () => {
  2598. spyOn(TestBed.inject(PlatformService), 'toast');
  2599. let harness: RouterTestingHarness;
  2600. if (entry.startsWith('course-')) {
  2601. harness = (await teacherSelection(100, Number(entry.slice(-1)), entry === 'course-0' ? '901' : '')).harness;
  2602. } else {
  2603. if (entry === 'coach-wordbook') {
  2604. user.set({userId:300,groupId:3});session.groupId.set(3);
  2605. }
  2606. const api = TestBed.inject(ApiService), original = api.get.bind(api);
  2607. spyOn(api, 'get').and.callFake(((action: string, params: Record<string, unknown> = {}) => {
  2608. if (action === 'e_user_list') return of({retcode:0,result:[{userId:100,honeyName:'学员甲'}]});
  2609. if (action === 'e_words_list') {
  2610. const all = Array.from({length:100}, (_,i) => ({GeneralID:601+i,detail:[{GeneralID:1001+i,Title:'word-'+i,sy:'释义 '+i}]}));
  2611. const size = Number(params['psize']), page = Number(params['cpage']);
  2612. return of({retcode:0,result:all.slice((page-1)*size,page*size),page:{itemCount:100,pendingCount:100,completedCount:0,pageCount:Math.ceil(100/size)}});
  2613. }
  2614. return original(action,params);
  2615. }) as typeof api.get);
  2616. harness = await RouterTestingHarness.create('/pages/member/starshop');
  2617. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2618. }
  2619. const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2620. const picker = harness.routeNativeElement!.querySelector<HTMLSelectElement>('.bulk-select-size');
  2621. expect(picker).withContext('every editable selection entry has a quantity picker').not.toBeNull();
  2622. if (!picker) return;
  2623. expect(Array.from(picker.options).map(option => option.value)).toEqual(['20','50','100']);
  2624. expect(picker.value).toBe('100');
  2625. const clickAll = () => {
  2626. (harness.routeNativeElement!.querySelector('.bulk-select-toggle, .quiet-button') as HTMLButtonElement).click();
  2627. harness.fixture.detectChanges();
  2628. };
  2629. for (const count of [20,50,100]) {
  2630. picker.value = String(count);picker.dispatchEvent(new Event('change'));harness.fixture.detectChanges();
  2631. clickAll();
  2632. expect((component.bulkSelection() ?? component.selected()).size).toBe(count);
  2633. if (count < 100) {clickAll();expect((component.bulkSelection() ?? component.selected()).size).toBe(0);}
  2634. }
  2635. if (startCount !== 100) {
  2636. clickAll();picker.value = String(startCount);picker.dispatchEvent(new Event('change'));harness.fixture.detectChanges();clickAll();
  2637. }
  2638. const button = entry.startsWith('course-') ? '.bulk-assessment .unknown-button' : '.selection-header .primary-button';
  2639. (harness.routeNativeElement!.querySelector(button) as HTMLButtonElement).click();
  2640. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2641. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  2642. const pages = JSON.parse(localStorage.getItem(entry === 'coach-wordbook'
  2643. ? 'xiaoshu.learning.300.100.wordbook._page_word_orilist'
  2644. : entry === 'student-wordbook' ? 'xiaoshu.learning.100.100.practice._page_word_orilist'
  2645. : entry === 'course-0' ? 'xiaoshu.learning.300.100.901.unbound._page_word_orilist'
  2646. : 'xiaoshu.learning.300.100.practice._page_word_orilist') || '[]');
  2647. expect(pages.flat().length).toBe(startCount);
  2648. });
  2649. }
  2650. for (const entry of ['course', 'coach-wordbook', 'student-wordbook'] as const) {
  2651. it(`hides the answer on the third point-reading tap in every round for ${entry}`, async () => {
  2652. let harness: RouterTestingHarness;
  2653. const platform = TestBed.inject(PlatformService);
  2654. spyOn(platform, 'toast');
  2655. if (entry === 'course') {
  2656. const selection = await teacherSelection(2,0,'901');
  2657. harness = selection.harness;
  2658. selection.component.selected.set(new Set(selection.component.words().map(word => word.id)));
  2659. selection.component.startSelected();
  2660. } else {
  2661. if (entry === 'coach-wordbook') {
  2662. user.set({userId:300,groupId:3});session.groupId.set(3);session.student.set({userId:100,groupId:1});
  2663. }
  2664. const api = TestBed.inject(ApiService), original = api.get.bind(api);
  2665. spyOn(api, 'get').and.callFake(((action: string, params: Record<string, unknown> = {}) => {
  2666. if (action === 'e_user_list') return of({retcode:0,result:[{userId:100,honeyName:'学员甲'}]});
  2667. if (action === 'e_words_list') return of({retcode:0,result:[{GeneralID:601,detail:[{GeneralID:701,Title:'apple',sy:'苹果',yb:'/ˈæpəl/'}]},{GeneralID:602,detail:[{GeneralID:702,Title:'banana',sy:'香蕉',yb:'/bəˈnɑːnə/'}]}]});
  2668. return original(action,params);
  2669. }) as typeof api.get);
  2670. harness = await RouterTestingHarness.create('/pages/member/starshop' + (entry === 'coach-wordbook' ? '?wordbookStudentId=100' : ''));
  2671. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2672. for (const button of Array.from(harness.routeNativeElement!.querySelectorAll<HTMLButtonElement>('.word-select-list > button'))) button.click();
  2673. harness.fixture.detectChanges();
  2674. (harness.routeNativeElement!.querySelector('.selection-header .primary-button') as HTMLButtonElement).click();
  2675. }
  2676. await harness.fixture.whenStable();harness.fixture.detectChanges();
  2677. expect(TestBed.inject(Router).url).toContain('/pages/stu/stu_con');
  2678. const component = harness.fixture.debugElement.query(By.directive(LearningPageComponent)).componentInstance as LearningPageComponent;
  2679. expect(component.words().length).toBe(2);
  2680. component.words.update(words => words.map(word => ({...word,phonetic:word.phonetic || '/wɜːd/'})));
  2681. spyOn(component,'play').and.resolveTo();
  2682. for (const step of [1,2,3] as const) {
  2683. expect(component.studyStep()).toBe(step);harness.fixture.detectChanges();
  2684. const first = component.words()[0], row = harness.routeNativeElement!.querySelector<HTMLButtonElement>('.repeat-list > button')!;
  2685. const answer = () => row.querySelector('small:not(.study-phonetic)');
  2686. expect(row.querySelector('strong')?.textContent).toBe(step===3 ? first.meaning : first.word);
  2687. expect(answer()).toBeNull();
  2688. row.click();harness.fixture.detectChanges();expect(answer()).toBeNull();
  2689. if(step!==3)expect(row.querySelector('.study-phonetic')?.textContent).toBe(first.phonetic);
  2690. row.click();harness.fixture.detectChanges();expect(answer()?.textContent).toBe(step===3 ? first.word : first.meaning);
  2691. row.click();harness.fixture.detectChanges();expect(answer()).toBeNull();expect(row.querySelectorAll('.repeat-dots .done').length).toBe(3);
  2692. if(step!==3)expect(row.querySelector('.study-phonetic')?.textContent).toBe(first.phonetic);
  2693. row.click();harness.fixture.detectChanges();expect(answer()).toBeNull();expect(component.repetitions()[first.id]).toBe(3);
  2694. if(step<3){for(const [index,word] of component.words().entries())if(index>0)for(let tap=0;tap<3;tap++)component.repeatWord(word,index);}
  2695. }
  2696. });
  2697. }
  2698. it('uses different save identities for consecutive learned passes and leaves the third pass read-only', async () => {
  2699. const {api,harness,component}=await teacherSelection(2,1);
  2700. spyOn(TestBed.inject(PlatformService),'toast'); // Two consecutive saves test state, not toast dismissal timers.
  2701. const original=api.post.bind(api),saved=new Map<string,Observable<ApiEnvelope<any>>>(),keys:string[]=[];
  2702. spyOn(api,'post').and.callFake(((action:string,params:Record<string,unknown>={})=>{
  2703. if(action!=='e_add_words')return original(action,params);
  2704. const key=String(params['requestKey']);keys.push(key);if(saved.has(key))return saved.get(key)!;
  2705. const result=original(action,params);saved.set(key,result);return result;
  2706. }) as typeof api.post);
  2707. for(const expectedPass of [2,3]){
  2708. (harness.routeNativeElement!.querySelector('.bulk-select-toggle') as HTMLButtonElement)?.click();harness.fixture.detectChanges();
  2709. (harness.routeNativeElement!.querySelector('.bulk-assessment .known-button') as HTMLButtonElement)?.click();await harness.fixture.whenStable();harness.fixture.detectChanges();
  2710. expect(component.coursePass()).toBe(expectedPass);expect(component.visibleCourseWords().length).toBe(2);
  2711. }
  2712. expect(keys.length).toBe(2);expect(new Set(keys).size).toBe(2);
  2713. expect([...api.courseIncrements.values()]).toEqual([2,2]);
  2714. expect(component.coursePassCount(3)).toBe(2);expect(component.coursePassCount(0)).toBe(0);
  2715. expect(harness.routeNativeElement!.querySelector('.bulk-select-toggle')).toBeNull();
  2716. expect(harness.routeNativeElement!.querySelector('.word-select-check')).toBeNull();
  2717. expect(harness.routeNativeElement!.querySelector('.word-assessment')).toBeNull();
  2718. component.toggleBulkSelection();component.applyBulkAssessment('known');
  2719. expect(keys.length).toBe(2);
  2720. });
  2721. });