LifeMate — Personal, Family & Learning Companion

feat/weekly-planner-android
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
js 56 lines 6.29 KB
Raw
1 import test, { after } from 'node:test';
2 import assert from 'node:assert/strict';
3 import fs from 'node:fs';
4 import crypto from 'node:crypto';
5 import { stableBookKey } from '../src/learning_catalog.js';
6 import os from 'node:os';
7 import path from 'node:path';
8 import { spawnSync } from 'node:child_process';
9 import pg from 'pg';
10 if (!process.env.DATABASE_URL) throw new Error('learning tests require synthetic PostgreSQL');
11 const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
12 const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'lifeguide-catalog-'));
13 after(async () => { fs.rmSync(temp, { recursive: true, force: true }); await pool.end(); });
14 function dataset() { return { schemaVersion:1,sourcesReviewed:0,books:[{ bookCode:'599',grade:5,subjectCode:'math',titleFa:'کتاب آزمایشی مستقل',trackCodes:['common'],schoolYear:'1405-1406',sourceUrl:'http://www.chap.sch.ir/',sourceEvidenceUrl:'http://www.chap.sch.ir/',variant:'standard',editionVerification:'verified',sequenceVerification:'official_toc',alignmentNotesFa:'Synthetic fixture, no approved real teaching.',units:[{ unitKey:'lesson-01',titleFa:'درس آزمایشی',orderIndex:1,indexKind:'lesson',sourceEvidenceUrl:'http://www.chap.sch.ir/',videos:[{ aparatId:'Ab123',titleFa:'ویدیوی آزمایشی',creatorName:'Synthetic Teacher',creatorUrl:'https://www.aparat.com/synthetic_teacher',sourceEvidenceUrl:'https://www.aparat.com/v/Ab123',verificationStatus:'metadata_verified',pedagogicalReview:'unverified',durationSeconds:60,freeAccess:true,checkedAt:'2026-10-09T10:00:00Z',qualityNotesFa:'Synthetic metadata only.' }] }] }],providers:[],observations:[] }; }
15 function run(data) { const file=path.join(temp,'fixture.json');fs.writeFileSync(file,JSON.stringify(data));return spawnSync(process.execPath,['scripts/import-learning-catalog.js','--file',file],{cwd:new URL('../',import.meta.url),env:process.env,encoding:'utf8'}); }
16 test('offline importer keeps repeat IDs stable, HTTP evidence exact and metadata resources draft',async()=>{
17 const data=dataset(),first=run(data);assert.equal(first.status,0,first.stderr);
18 const read=async()=>(await pool.query("select t.id,t.source_evidence_url,u.id unit_id,v.id video_id,v.publication_status from textbook_catalog t join learning_unit u on u.textbook_id=t.id join learning_video_resource v on v.unit_id=u.id where t.book_code='599'")).rows;
19 const rows=await read();assert.equal(rows.length,1);assert.equal(rows[0].source_evidence_url,'http://www.chap.sch.ir/');assert.equal(rows[0].publication_status,'draft');assert.equal(run(data).status,0);assert.deepEqual(await read(),rows);
20 });
21 test('invalid hashes and provider injection fail before catalogue mutation',async()=>{
22 // Other fixture tests write to this shared synthetic database concurrently.
23 // Scope the invariant to a unique rejected book, not a global row count.
24 const code=String(crypto.randomInt(10000000,100000000));
25 const book={...dataset().books[0],bookCode:code};
26 const key=stableBookKey(book);
27 const snapshot=async()=>({
28 books:(await pool.query('select id from textbook_catalog where stable_book_key=$1',[key])).rows,
29 subjects:(await pool.query('select id from curriculum_subject where code=$1',[key])).rows,
30 });
31 const before=await snapshot();
32 assert.deepEqual(before,{books:[],subjects:[]});
33 for(const change of [v=>{v.aparatId='../bad?token=x';},v=>{v.creatorUrl='https://www.aparat.com.evil.test/teacher';}]){
34 const data=dataset();
35 data.books[0].bookCode=code;
36 change(data.books[0].units[0].videos[0]);
37 const result=run(data);
38 assert.notEqual(result.status,0);
39 assert.match(result.stderr,/invalid_catalog_(aparat_hash|video_source)/);
40 assert.deepEqual(await snapshot(),before,'rejected fixture must not write its book or subject');
41 }
42 });
43 test('publication rejects incomplete pedagogical review despite free metadata',async()=>{await assert.rejects(pool.query("update learning_video_resource set publication_status='published',review_record='{}'::jsonb where aparat_id='Ab123'"),{code:'23514'});});
44 function fullReview(row){return {reviewerName:'Synthetic local reviewer',reviewedAt:'2026-10-09T10:00:00Z',bookCode:'599',schoolYear:'1405-1406',unitKey:'lesson-01',bookEvidenceUrl:'http://www.chap.sch.ir/',unitEvidenceUrl:'http://www.chap.sch.ir/',materialHash:row.material_hash,watchedEntireVideo:true,editionAligned:true,accuracyApproved:true,suitabilityApproved:true,embedRightsApproved:true,questionCoverageReviewed:true,alignmentNotes:'Synthetic alignment evidence',accuracyNotes:'Synthetic accuracy evidence',suitabilityNotes:'Synthetic age suitability',embedRightsEvidence:'Synthetic rights fixture, never a real permission',questionCoverageNotes:'Synthetic question coverage'};}
45 test('full review cannot publish null-free or mismatched material; unchanged import preserves review and changed content invalidates it',async()=>{
46 const row=(await pool.query("select * from learning_video_resource where aparat_id='Ab123'")).rows[0];const record=fullReview(row);
47 try{
48 await assert.rejects(pool.query("update learning_video_resource set publication_status='published',pedagogical_review='full_reviewed',free_access=null,review_record=$2 where id=$1",[row.id,record]),{code:'23514'});
49 for(const patch of [{watchedEntireVideo:false},{reviewerName:''},{schoolYear:'1404-1405'},{unitKey:'lesson-02'},{materialHash:'0'.repeat(64)},{reviewedAt:'2999-01-01T00:00:00Z'}])await assert.rejects(pool.query("update learning_video_resource set publication_status='published',pedagogical_review='full_reviewed',review_record=$2 where id=$1",[row.id,{...record,...patch}]),{code:'23514'});
50 await pool.query("update learning_video_resource set publication_status='published',pedagogical_review='full_reviewed',review_record=$2 where id=$1",[row.id,record]);
51 const same=dataset();same.books[0].units[0].videos[0].checkedAt='2026-10-09T10:01:00Z';assert.equal(run(same).status,0);
52 assert.equal((await pool.query('select publication_status from learning_video_resource where id=$1',[row.id])).rows[0].publication_status,'published');
53 same.books[0].units[0].titleFa='Changed unit teaching scope';assert.equal(run(same).status,0);
54 const changed=(await pool.query('select publication_status,review_record from learning_video_resource where id=$1',[row.id])).rows[0];assert.equal(changed.publication_status,'draft');assert.equal(changed.review_record,null);
55 }finally{run(dataset());}
56 });