Browse Source

Skip unauthorized lesson batch requests from study history

彭峰 1 hour ago
parent
commit
931c639640

+ 15 - 0
projects/xiaoshu-mobile/src/app/core/home-learning-modules.integration.spec.ts

@@ -759,6 +759,21 @@ describe('home learning modules', () => {
     expect(play).not.toHaveBeenCalled();
   });
 
+  it('opens historical words without requesting lesson batches the account cannot view', async () => {
+    const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
+    const post = api.post.bind(api);
+    spyOn(api, 'post').and.callFake((action, params) => action === 'e_record_detail'
+      ? of({ retcode: 0, result: [{ GeneralID: 1001, Title: 'apple' }], addon: [{ GeneralID: 901, canReadLessonStudy: false }] }) as never
+      : post(action, params));
+    const get = spyOn(api, 'get').and.callThrough();
+    const harness = await RouterTestingHarness.create();
+    await harness.navigateByUrl('/pages/his/his_words?id=201');
+    await harness.fixture.whenStable();
+    expect(api.post).toHaveBeenCalledWith('e_record_detail', { id: '201', includeLessonStudyAccess: true });
+    expect(get).not.toHaveBeenCalledWith('app_lesson_study', { orderId: '901' });
+    expect(harness.routeNativeElement?.textContent).toContain('apple');
+  });
+
   it('pages through all words in a history record without requesting a course unit', async () => {
     const api = TestBed.inject(ApiService) as unknown as LearningModulesApiService;
     const originalPost = api.post.bind(api);

+ 7 - 2
projects/xiaoshu-mobile/src/app/features/learning/learning-page.component.ts

@@ -1677,7 +1677,7 @@ export class LearningPageComponent implements OnInit, OnDestroy {
     }
 
     if (this.meta.path === 'pages/his/his_words') {
-      this.api.post<unknown>('e_record_detail', { id: this.query('id') }).pipe(finalize(() => this.loading.set(false))).subscribe({
+      this.api.post<unknown>('e_record_detail', { id: this.query('id'), includeLessonStudyAccess: true }).pipe(finalize(() => this.loading.set(false))).subscribe({
         next: ({ result, addon }) => {
           const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
           this.historyPreviewWords = words;
@@ -1686,7 +1686,12 @@ export class LearningPageComponent implements OnInit, OnDestroy {
           const sourceAddon = this.findList(addon)[0];
           if (sourceAddon) {
             this.orderInfo.set(sourceAddon);
-            if (sourceAddon['GeneralID']) this.api.get<any>('app_lesson_study', {orderId: String(sourceAddon['GeneralID'])}).subscribe({next: ({result}) => this.historySources.set(lessonStudySources(result)), error: () => this.historySources.set([])});
+            if (sourceAddon['GeneralID'] && sourceAddon['canReadLessonStudy'] !== false) {
+              this.api.get<any>('app_lesson_study', { orderId: String(sourceAddon['GeneralID']) }).subscribe({
+                next: ({ result }) => this.historySources.set(lessonStudySources(result)),
+                error: () => this.historySources.set([]),
+              });
+            }
           }
         },
         error: (error: ApiError) => this.error.set(error.message),

+ 9 - 0
scripts/deploy-admin-functions.mjs

@@ -2677,6 +2677,15 @@ async function recordDetailData(input, current) {
   if (!storedWords.length && !notesReview) storedWords = await legacyStudyRecordWords(id,number(record.userId ?? record.UserID)); const ids = [...new Set(storedWords.map((item) => String(item && (item.GeneralID ?? item.generalId ?? item.id) || '')).filter(Boolean))]; let wordRows = [];
   if (ids.length) wordRows = await Psql.query('SELECT c.*, row_to_json(v) AS "__addon" FROM "CommonModel" c LEFT JOIN "VocabularyWord" v ON v."company" = $1 AND CAST(v."id" AS text) = CAST(c."itemId" AS text) WHERE c."company" = $1 AND CAST(c."modelId" AS text) = \'52\' AND CAST(c."generalId" AS text) = ANY($2::text[])', [DEFAULT_COMPANY_ID, ids]);
   const details = new Map(wordRows.map((row) => { const normalized = normalizeWordRow(row); return [String(normalized.GeneralID || normalized.generalId), normalized]; })); const words = storedWords.map((item) => { const raw = item && typeof item === 'object' ? safe(item) : {}; const wordId = String(raw.GeneralID ?? raw.generalId ?? raw.id ?? ''); const detail = details.get(wordId) || legacyAliases({ generalId: wordId, title: raw.Title || raw.title || '' }, 'CommonModel'); return { ...detail, ...raw, GeneralID: number(wordId, wordId), Title: raw.Title || raw.title || detail.Title || detail.title || '', detail: [detail] }; });
+  if (order && input.includeLessonStudyAccess === true) {
+    try {
+      await authorizeBusinessRow(current, order, ['szyh'], ['pl']);
+      order.canReadLessonStudy = true;
+    } catch (error) {
+      if (Number(error.status) !== 403) throw error;
+      order.canReadLessonStudy = false;
+    }
+  }
   return { words, addon: order ? [{...order, ...(notesReview ? {reviewContentMode:'notes'} : {})}] : [], record };
 }
 async function newWordPage(input, current) {

+ 11 - 2
scripts/tests/writing-review-detail.test.mjs

@@ -3,14 +3,15 @@ import assert from 'node:assert/strict';
 import {readFileSync} from 'node:fs';
 import vm from 'node:vm';
 const source=readFileSync(new URL('../deploy-admin-functions.mjs',import.meta.url),'utf8').match(/const appGatewayCode = String.raw`([\s\S]*?)\n`;/)[1];
-function context({category='primary_writing',learned=0,student=20,status=30,authorized=true,words='[]'}={}) {
+function context({category='primary_writing',learned=0,student=20,status=30,authorized=true,words='[]',orderDenial=0}={}) {
  let legacyCalls=0;
  const ctx=vm.createContext({Parse:{},Psql:{query:async()=>[{company:'co',generalId:100,__addon:{userId:20,dsid:200,xxqs:words,learned}}]}});
  vm.runInContext(source+'\n'+readFileSync(new URL('../cloud/mobile-teaching.js',import.meta.url),'utf8'),ctx);
  ctx.authorizeLearningRecordAccess=async()=>{if(!authorized)throw Error('无权查看');};
  ctx.orderDetailRow=async()=>({szyh:student,dszt:status,courseCategoryKey:category});
+ ctx.authorizeBusinessRow=async()=>{if(orderDenial)throw Object.assign(Error('预约不可读'),{status:orderDenial});};
  ctx.legacyStudyRecordWords=async()=>{legacyCalls++;return[];};
- return {run:()=>ctx.recordDetailData({id:100},{}),legacyCalls:()=>legacyCalls};
+ return {run:(includeLessonStudyAccess=false)=>ctx.recordDetailData({id:100,includeLessonStudyAccess},{}),legacyCalls:()=>legacyCalls};
 }
 for(const category of ['primary_writing','middle_writing','high_writing'])test(category+' empty confirmed source is an intentional notes review',async()=>{
  const c=context({category}),result=await c.run();assert.equal(result.words.length,0);assert.equal(result.addon[0].reviewContentMode,'notes');assert.equal(c.legacyCalls(),0);
@@ -19,3 +20,11 @@ for(const options of [{category:'word'},{learned:1},{student:21},{status:10}])te
  const c=context(options),result=await c.run();assert.equal(result.addon[0].reviewContentMode,undefined);assert.equal(c.legacyCalls(),1);
 });
 test('notes review still requires source record authorization',async()=>{const c=context({authorized:false});await assert.rejects(c.run(),/无权查看/);assert.equal(c.legacyCalls(),0);});
+
+test('authorized learning words can be read without permission to view lesson study batches', async () => {
+ const detail=await context({orderDenial:403}).run(true);
+ assert.equal(detail.addon[0].canReadLessonStudy,false);
+ assert.equal(detail.addon[0].reviewContentMode,'notes');
+ assert.equal((await context().run(true)).addon[0].canReadLessonStudy,true);
+ assert.equal((await context({orderDenial:403}).run()).addon[0].canReadLessonStudy,undefined);
+});