LifeMate — Personal, Family & Learning Companion

docs/offline-data-rescue-options
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
cjs 185 lines 13.7 KB
Raw
1 // Compiled Flutter, verified local TLS, real HTTP/PostgreSQL. Synthetic only.
2 // Credentials stay in the private fixture file; API responses are never mocked.
3 const assert = require('node:assert/strict');
4 const fs = require('node:fs');
5 const path = require('node:path');
6 const https = require('node:https');
7 const crypto = require('node:crypto');
8 const {execFileSync} = require('node:child_process');
9 const {chromium} = require('playwright');
10 const {Client} = require('../../../backend/node_modules/pg');
11
12 const fixture = JSON.parse(fs.readFileSync(process.env.LG_WEEKLY_FIXTURE || '/tmp/lifeguide-weekly-browser-qa/fixture.json','utf8'));
13 assert(fixture.syntheticOnly === true && fixture.email.endsWith('@example.test'));
14 const database = new URL(fixture.databaseUrl);
15 assert(database.hostname === '127.0.0.1' && database.port === '55449' &&
16 /^\/lifeguide_weekly_browser_test_[a-f0-9]{16}$/.test(database.pathname), 'Disposable loopback fixture only');
17 const origin = process.env.LG_WEEKLY_ORIGIN || 'https://127.0.0.1:8449';
18 assert.equal(new URL(origin).hostname,'127.0.0.1');
19 assert.equal(new URL(origin).protocol,'https:');
20 const ca = fs.readFileSync(process.env.LG_TEST_CA_FILE || '/tmp/lifeguide-weekly-browser-qa/ca.crt');
21 const out = path.resolve(process.argv[2] || '/tmp/lifeguide-weekly-browser-evidence');
22 fs.mkdirSync(out,{recursive:true});
23 const root = path.resolve(__dirname,'../../..');
24 const main = path.join(root,'apps/lifemate/build/web/main.dart.js');
25 const compiledHash = () => crypto.createHash('sha256').update(fs.readFileSync(main)).digest('hex');
26 const mainAtStart = compiledHash();
27 const db = new Client({connectionString:database.href});
28 const checks = [], errors = [], origins = new Set();
29 let browser, page, stage = 'startup';
30 const record = name => { checks.push({name,result:'PASS'}); console.log('PASS ' + name); };
31 const weekdayNames = {1:'دوشنبه',2:'سه‌شنبه',3:'چهارشنبه',4:'پنجشنبه',5:'جمعه',6:'شنبه',7:'یکشنبه'};
32 const localDay = new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());
33 const firstWeekday = new Date(localDay + 'T00:00:00Z').getUTCDay() || 7;
34 const secondWeekday = (firstWeekday + 1) % 7 + 1;
35 function api(method,endpoint,body,token) {
36 return new Promise((resolve,reject) => {
37 const data = body === undefined ? null : Buffer.from(JSON.stringify(body));
38 const req = https.request(origin + '/api' + endpoint,{method,ca,rejectUnauthorized:true,
39 headers:{...(data ? {'content-type':'application/json','content-length':data.length} : {}),
40 ...(token ? {authorization:'Bearer ' + token} : {})}},res => {
41 assert(res.socket.authorized); let text = '';
42 res.on('data',chunk => text += chunk); res.on('end',() => {
43 try { resolve({status:res.statusCode,body:JSON.parse(text)}); } catch { reject(Error('Non-JSON API response')); }
44 });
45 }); req.setTimeout(15000,() => req.destroy(Error('Local API timeout'))); req.on('error',reject); req.end(data);
46 });
47 }
48 async function click(locator) {
49 await locator.waitFor({state:'attached',timeout:20000});
50 // Flutter semantics activation; physical hit targets are checked separately.
51 await locator.evaluate(element => element.click());
52 }
53 const button = name => page.getByRole('button',{name,exact:typeof name === 'string'});
54 async function enter(locator,value) {
55 await locator.focus();
56 await locator.press('ControlOrMeta+A');
57 await locator.press('Backspace');
58 // Real keyboard input keeps Flutter's controller and native semantics input
59 // in agreement across rebuilds; setting textarea.value alone is insufficient.
60 await locator.pressSequentially(value);
61 }
62 async function text(value) {
63 await page.waitForFunction(value => document.body.textContent.includes(value) ||
64 [...document.querySelectorAll('[aria-label]')].some(e => e.getAttribute('aria-label').includes(value)),value,{timeout:25000});
65 }
66 async function semantics() {
67 await page.waitForFunction(() => !document.getElementById('startup-status'),null,{timeout:60000});
68 const placeholder = page.locator('flt-semantics-placeholder');
69 if (await placeholder.count()) await placeholder.evaluate(e => e.click());
70 }
71 async function timeInput(locator,hour,minute) {
72 await click(locator);
73 await page.getByLabel('ساعت',{exact:true}).waitFor({state:'attached'});
74 await enter(page.getByLabel('ساعت',{exact:true}),String(hour).padStart(2,'0'));
75 await enter(page.getByLabel('دقیقه',{exact:true}),String(minute).padStart(2,'0'));
76 await click(button(/^(تأیید|تایید|OK)$/));
77 await page.getByLabel('ساعت',{exact:true}).waitFor({state:'detached'});
78 }
79 async function waitForDatabaseTitle(id,title) {
80 for (let i=0;i<60;i++) {
81 const row = (await db.query('select title from plan_item where id=$1',[id])).rows[0];
82 if (row?.title === title) return;
83 await new Promise(resolve => setTimeout(resolve,500));
84 }
85 throw Error('Server did not acknowledge offline occurrence edit');
86 }
87 (async () => {
88 await db.connect();
89 const owner = (await db.query('select identity_subject,is_managed_child from app_user where id=$1',[fixture.userId])).rows[0];
90 assert(owner?.identity_subject.startsWith('weekly-browser:') && owner.is_managed_child === false);
91 // The dedicated, verified fixture contains no user data. Make reruns isolated.
92 await db.query('delete from planner_series where owner_user_id=$1',[fixture.userId]);
93 const login = await api('POST','/v1/auth/login',{email:fixture.email,password:fixture.password});
94 assert.equal(login.status,200); const token = login.body.accessToken; assert.equal(typeof token,'string');
95 browser = await chromium.launch({executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH || '/usr/bin/chromium',args:['--no-sandbox']});
96 const context = await browser.newContext({viewport:{width:390,height:844},timezoneId:'Asia/Tehran',ignoreHTTPSErrors:false});
97 page = await context.newPage();
98 page.on('pageerror',() => errors.push('JavaScript page error'));
99 page.on('request',request => { const u=new URL(request.url()); if (/^https?:/.test(u.protocol)) origins.add(u.origin); });
100 stage='login';
101 const response = await page.goto(origin,{waitUntil:'networkidle',timeout:60000}); assert.equal(response.status(),200); await semantics();
102 await page.getByLabel('ایمیل یا شماره تلفن',{exact:true}).fill(fixture.email);
103 await page.getByLabel('رمز عبور',{exact:true}).fill(fixture.password);
104 await click(button('ورود'));
105 await page.getByRole('tab',{name:'برنامه',exact:true}).waitFor({timeout:30000});
106 await text('قدم بعدی');
107 await page.screenshot({path:path.join(out,'LifeGuide-weekly-home.png')});
108 record('verified HTTPS login to compiled Flutter with synthetic standard minor account');
109
110 stage='weekly create';
111 await click(page.getByRole('tab',{name:'برنامه',exact:true}));
112 await click(button('برنامهٔ تکراری'));
113 const title = 'مدرسهٔ ساختگی هفتگی ' + Date.now().toString(36);
114 await enter(page.getByLabel('عنوان',{exact:true}),title);
115 await click(button(/^نوع/)); await click(page.getByRole('menuitem',{name:'رویداد',exact:true}));
116 await click(page.getByRole('checkbox',{name:weekdayNames[secondWeekday],exact:true}));
117 const firstGroup = page.getByRole('group',{name:weekdayNames[firstWeekday],exact:true});
118 const secondGroup = page.getByRole('group',{name:weekdayNames[secondWeekday],exact:true});
119 await timeInput(firstGroup.getByRole('button',{name:/^پایان:/}),12,0);
120 await timeInput(secondGroup.getByRole('button',{name:/^شروع:/}),10,0);
121 await timeInput(secondGroup.getByRole('button',{name:/^پایان:/}),14,0);
122 await click(button(/^یادآوری هر نوبت/)); await click(page.getByRole('menuitem',{name:'۵ دقیقه پیش از شروع',exact:true}));
123 await page.screenshot({path:path.join(out,'LifeGuide-weekly-editor.png')});
124 await click(button('ثبت برنامه')); await text(title);
125 const series = (await db.query('select id,frequency,slots,timezone from planner_series where owner_user_id=$1 and title=$2',[fixture.userId,title])).rows;
126 assert.equal(series.length,1); const seriesId=series[0].id;
127 assert.equal(series[0].frequency,'weekly'); assert.equal(series[0].timezone,'Asia/Tehran');
128 assert.deepEqual(series[0].slots,[{weekday:firstWeekday,start:'08:00',end:'12:00'},{weekday:secondWeekday,start:'10:00',end:'14:00'}].sort((a,b) => a.weekday-b.weekday));
129 const items = (await db.query('select p.*,p.original_occurrence_date::text as day from plan_item p where p.series_id=$1 order by p.original_occurrence_date',[seriesId])).rows;
130 let expectedCount=0;
131 for(let n=0;n<60;n++){const d=new Date(Date.parse(localDay+'T00:00:00Z')+n*86400000);if([firstWeekday,secondWeekday].includes(d.getUTCDay()||7))expectedCount++;}
132 assert.equal(items.length,expectedCount);
133 assert(items.every(i => i.owner_user_id===fixture.userId && i.visibility==='private' && i.family_id===null));
134 const occurrence=items.find(i=>i.day===localDay); assert(occurrence);
135 const read=await api('GET','/v1/plan-items/'+occurrence.id,undefined,token);
136 assert.equal(read.status,200);assert.equal(read.body.series_id,seriesId);assert.equal(read.body.ends_at,occurrence.ends_at.toISOString());
137 assert.equal((await db.query('select count(*)::int n from reminder r join plan_item p on p.id=r.plan_item_id where p.series_id=$1',[seriesId])).rows[0].n,expectedCount);
138 await text('میلادی');
139 await text('تا 12:00');
140 await page.screenshot({path:path.join(out,'LifeGuide-weekly-schedule.png')});
141 record('UI creates weekly school with different weekday hours; actual REST and PostgreSQL confirm private unique occurrences');
142
143 stage='complete one';await click(button('انجام شد'));await button('برگرداندن به برنامه').waitFor({timeout:20000});
144 assert.equal((await api('GET','/v1/plan-items/'+occurrence.id,undefined,token)).body.status,'completed');
145 assert.equal((await db.query("select count(*)::int n from plan_item where series_id=$1 and status='completed'",[seriesId])).rows[0].n,1);
146 record('ticking one occurrence leaves every other occurrence independently planned');
147
148 stage='restart';await page.reload({waitUntil:'networkidle'});await semantics();
149 await click(page.getByRole('tab',{name:'برنامه',exact:true}));await text(title);await button('برگرداندن به برنامه').waitFor();
150 record('page restart restores authenticated server-backed weekly record and completion');
151
152 stage='offline edit';
153 // ListTile navigation is a pointer target on Flutter's canvas; activate its
154 // visible center rather than dispatching a synthetic DOM click to its label.
155 await button(new RegExp('^'+title)).click({force:true});await text('جزئیات تکلیف');
156 await click(button('ویرایش تکلیف'));const edited=title+' ویرایش آفلاین';await enter(page.getByLabel('عنوان',{exact:true}),edited);
157 await context.setOffline(true);await click(button('ذخیره'));await text('در انتظار تأیید سرور');
158 assert.equal((await db.query('select title from plan_item where id=$1',[occurrence.id])).rows[0].title,title);
159 record('offline occurrence edit is durably pending while PostgreSQL remains unchanged');
160 await context.setOffline(false);await click(button('برگشتن').last());await waitForDatabaseTitle(occurrence.id,edited);
161 const fresh=await api('GET','/v1/plan-items/'+occurrence.id,undefined,token);assert.equal(fresh.body.title,edited);
162 assert.equal(fresh.body.status,'completed');assert.equal(fresh.body.series_id,seriesId);
163 const finalRows=(await db.query('select id,title,status,original_occurrence_date::text as day from plan_item where series_id=$1',[seriesId])).rows;
164 assert.equal(finalRows.length,expectedCount);assert.equal(new Set(finalRows.map(i=>i.day)).size,expectedCount);
165 assert.equal(finalRows.filter(i=>i.title===edited).length,1);assert.equal(finalRows.filter(i=>i.status==='completed').length,1);
166 await page.reload({waitUntil:'networkidle'});await semantics();await click(page.getByRole('tab',{name:'برنامه',exact:true}));await text(edited);
167 await page.screenshot({path:path.join(out,'LifeGuide-weekly-reopened.png')});
168 record('reconnect and subsequent restart retain one edited occurrence without duplicate generation');
169 assert.deepEqual(errors,[]);assert.deepEqual([...origins].filter(o=>o!==origin),[]);
170 assert.equal(compiledHash(),mainAtStart,'Compiled assets changed during acceptance; rerun the final build');
171 fs.writeFileSync(path.join(out,'verification.json'),JSON.stringify({status:'VERIFIED_LOCAL_SYNTHETIC_ONLY',
172 sourceHead:execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim(),
173 compiledMainSha256:mainAtStart,
174 browser:await browser.version(),tlsVerified:true,apiResponsesIntercepted:false,checks,
175 recurrence:{frequency:'weekly',timezone:'Asia/Tehran',slots:series[0].slots,occurrenceCount:expectedCount,completedCount:1},
176 offlineEditFields:['title'],javascriptErrors:errors,externalRuntimeOrigins:[],
177 unverified:['physical Android/iPhone/Safari','background OS alarms','managed-child private planner authorization','offline cold start','production deployment']},null,2));
178 })().catch(async error => {
179 const message=String(error.message).replaceAll(fixture.password,'[fixture credential]');
180 console.error('FAIL '+stage+': '+message);
181 if(page) await page.screenshot({path:path.join(out,'failure-diagnostic.png')}).catch(()=>{});
182 if(page) fs.writeFileSync(path.join(out,'failure-semantics.json'),JSON.stringify(await page.locator('[role],[aria-label]').evaluateAll(es => es.map(e => ({role:e.getAttribute('role'),label:e.getAttribute('aria-label'),text:e.textContent}))),null,2));
183 fs.writeFileSync(path.join(out,'failure.json'),JSON.stringify({status:'FAILED_LOCAL_SYNTHETIC',stage,message,checks},null,2));
184 process.exitCode=1;
185 }).finally(async()=>{if(browser)await browser.close();await db.end();});