Files
nur-falah-prevention/e2e-khairat-lifestyle.cjs
wmj 9cb0793347 fix: Qibla not detecting device compass on iOS and Android
Two real bugs, both explaining 'didn't detect compass':

1. iOS: DeviceOrientationEvent.requestPermission() was called *after*
   the async geolocation round-trip resolved. Safari's user-activation
   grant for sensor permissions expires almost immediately, so by the
   time a GPS fix comes back (often several seconds), the permission
   call silently fails with no prompt ever shown. Now requested
   synchronously inside the button's click handler, before geolocation
   starts.

2. Android: the heading was only accepted when e.absolute === true, but
   many Android browsers fire plain 'deviceorientation' with
   absolute:false even though alpha is a perfectly usable heading —
   compass detection silently never succeeded on those devices at all.
   Now accepts alpha regardless of the absolute flag, falling back to
   it when webkitCompassHeading (iOS) isn't present.

Also fixed a duplicate-listener bug: clicking 'Refresh location'
repeatedly re-registered deviceorientation listeners without removing
the previous ones, stacking duplicates on every retry.

Verified live: dispatched a synthetic non-absolute deviceorientation
event (the exact Android failure shape) against the deployed app —
compass detection now activates correctly where it previously stayed
silently stuck on the no-sensor fallback. Added as a permanent
regression assertion in e2e-khairat-lifestyle.cjs (16/16).
2026-08-14 15:23:17 +08:00

181 lines
11 KiB
JavaScript

// Verifies the Khairat/emergency-contacts round and the lifestyle-companion
// tabs (Qibla, Prayer Times, Locate, Quran, Neighbourhood) against the live
// backend. Geolocation-dependent tabs use Playwright's mocked geolocation
// (Kuala Lumpur coordinates) rather than the real device.
const { chromium } = require('playwright');
const { signInFreshFamily, gotoTab } = require('./e2e-auth-helper.cjs');
const BASE = 'https://moslem04.falahos.my/';
const results = [];
const consoleErrors = [];
function record(name, pass, detail = '') { results.push({ name, pass, detail }); console.log(`${pass ? 'PASS' : 'FAIL'} ${name}${detail ? ' — ' + detail : ''}`); }
async function main() {
const browser = await chromium.launch();
const context = await browser.newContext({
viewport: { width: 390, height: 844 },
geolocation: { latitude: 3.1390, longitude: 101.6869 }, // Kuala Lumpur
permissions: ['geolocation']
});
const page = await context.newPage();
page.on('console', m => { if (m.type() === 'error') consoleErrors.push(m.text()); });
page.on('pageerror', e => consoleErrors.push(e.message));
await signInFreshFamily(page, BASE, 'e2e-khairat');
// ── Khairat ──
await gotoTab(page, 'Khairat');
await page.waitForTimeout(600);
await page.locator('.field:has-text("Scheme name") input').fill('Kariah Khairat Kematian Masjid Al-Falah');
await page.locator('.field:has-text("Organization") input').fill('Masjid Al-Falah');
await page.locator('button.btn-primary', { hasText: 'Add khairat membership' }).click();
await page.waitForTimeout(1000);
const khairatRowVisible = await page.locator('.khairat-row', { hasText: 'Kariah Khairat Kematian' }).isVisible().catch(() => false);
record('Khairat: membership added and listed', khairatRowVisible);
await page.locator('.fund-card .field:has-text("Target amount") input').fill('5000');
await page.locator('.fund-card .field:has-text("Current balance") input').fill('1250');
await page.waitForTimeout(1000);
const fundProgressVisible = await page.locator('.fund-progress-label', { hasText: '25%' }).isVisible().catch(() => false);
record('Khairat: emergency fund progress bar computes correctly (1250/5000 = 25%)', fundProgressVisible);
// ── Trusted contacts with category + email ──
await gotoTab(page, 'Assets');
await page.waitForTimeout(500);
await page.locator('.contacts-section .field:has-text("Name") input').fill('Masjid Al-Falah Office');
await page.locator('.contacts-section .field:has-text("Category") select').selectOption('mosque');
await page.locator('.contacts-section .field:has-text("Email") input').fill('office@example-mosque.test');
await page.locator('.contacts-section button.btn-secondary', { hasText: 'Add trusted contact' }).click();
await page.waitForTimeout(1000);
const contactCategoryVisible = await page.locator('.contact-row', { hasText: 'Masjid Al-Falah Office' }).locator('.contact-category', { hasText: 'mosque' }).isVisible().catch(() => false);
record('Trusted Contacts: category badge shows on the new contact', contactCategoryVisible);
// ── Qibla ──
await gotoTab(page, 'Qibla');
await page.waitForTimeout(500);
await page.locator('button.btn-primary', { hasText: 'Find Qibla direction' }).click();
await page.waitForTimeout(2000);
const bearingVisible = await page.locator('.bearing-readout strong').isVisible().catch(() => false);
const bearingText = bearingVisible ? await page.locator('.bearing-readout strong').textContent() : '';
record('Qibla: computes a bearing from Kuala Lumpur (expect ~292° toward Makkah)', bearingVisible && /29[0-5]°/.test(bearingText), bearingText);
const distanceVisible = await page.locator('.distance-note', { hasText: 'km to Makkah' }).isVisible().catch(() => false);
record('Qibla: shows distance to Makkah', distanceVisible);
// Regression guard: many Android browsers fire plain 'deviceorientation'
// with absolute:false even though alpha is a usable heading — a prior
// version required absolute:true and silently never detected the compass
// on those devices. Simulate exactly that event shape.
const staticNoteBeforeSensor = await page.locator('.static-note').isVisible().catch(() => false);
record('Qibla: shows the no-sensor fallback note before any orientation event', staticNoteBeforeSensor);
await page.evaluate(() => {
const evt = new Event('deviceorientation');
Object.defineProperty(evt, 'alpha', { value: 90 });
Object.defineProperty(evt, 'absolute', { value: false });
window.dispatchEvent(evt);
});
await page.waitForTimeout(500);
const staticNoteAfterSensor = await page.locator('.static-note').isVisible().catch(() => false);
record('Qibla: accepts a non-absolute deviceorientation event as a valid compass reading (Android)', !staticNoteAfterSensor);
// ── Prayer Times ──
await gotoTab(page, 'Prayer Times');
await page.waitForTimeout(500);
await page.locator('button.btn-primary', { hasText: "Calculate today's prayer times" }).click();
await page.waitForTimeout(2000);
const fajrVisible = await page.locator('.time-row', { hasText: 'Fajr' }).locator('.time-value').isVisible().catch(() => false);
const timesInOrder = await page.locator('.times-list').innerText();
record('Prayer Times: computes all 6 times for Kuala Lumpur', fajrVisible && /Fajr[\s\S]*Sunrise[\s\S]*Dhuhr[\s\S]*Asr[\s\S]*Maghrib[\s\S]*Isha/.test(timesInOrder), timesInOrder.replace(/\n/g, ' '));
// ── Locate (mosque + halal search via live OpenStreetMap Overpass) ──
await gotoTab(page, 'Locate');
await page.waitForTimeout(500);
await page.locator('button.btn-primary', { hasText: 'Search nearby' }).click();
await page.waitForTimeout(10000); // live Overpass API call, across mirrors if the first is down
const locateResultOrEmpty = await page.locator('.results-list, .empty').isVisible().catch(() => false);
record('Locate: mosque search completes (real results or honest empty state)', locateResultOrEmpty);
// Halal food specifically: OSM tagging is sparse for this category
// globally, but Kuala Lumpur at this test coordinate is known to have
// real diet:halal=yes data (~30 results) — asserting a non-zero count
// here catches a mirror silently returning an empty-but-"successful"
// response, which looks identical to a legitimate empty search otherwise.
await page.locator('.category-toggle button', { hasText: 'Halal food' }).click();
await page.locator('button.btn-primary', { hasText: 'Search nearby' }).click();
await page.waitForTimeout(10000);
const halalResultCount = await page.locator('.result-row').count();
record('Locate: halal food search returns real results at a known-good test location', halalResultCount > 0, `${halalResultCount} results`);
// ── Quran ──
await gotoTab(page, 'Quran');
await page.waitForTimeout(2000);
const surahListVisible = await page.locator('.surah-row', { hasText: 'Al-Faatiha' }).isVisible().catch(() => false);
record('Quran: Surah list loads from the public API (Al-Faatiha present)', surahListVisible);
if (surahListVisible) {
await page.locator('.surah-row', { hasText: 'Al-Faatiha' }).click();
await page.waitForTimeout(2000);
const ayahVisible = await page.locator('.ayah-row').first().isVisible().catch(() => false);
const arabicVisible = await page.locator('.ayah-arabic').first().isVisible().catch(() => false);
record('Quran: opening a Surah loads Arabic text and translation', ayahVisible && arabicVisible);
}
// ── Neighbourhood board ──
// Neighbourhoods are scoped to the user account, not the family — the
// shared e2e owner account may already belong to one from a prior run,
// in which case the create/join form is behind the "add another" toggle.
await gotoTab(page, 'Neighbourhood');
await page.waitForTimeout(600);
const addToggleVisible = await page.locator('.add-toggle').isVisible().catch(() => false);
if (addToggleVisible) await page.locator('.add-toggle').click();
await page.waitForTimeout(300);
const nName = `Kariah Test ${Date.now()}`;
await page.locator('.form-card .field:has-text("Name") input').fill(nName);
await page.locator('button.btn-primary', { hasText: 'Create & get a join code' }).click();
await page.waitForTimeout(1000);
const joinCodeVisible = await page.locator('.join-code', { hasText: 'Join code:' }).isVisible().catch(() => false);
record('Neighbourhood: creating one generates a join code', joinCodeVisible);
await page.locator('.form-card .field:has-text("Title") input').fill('Friday khutbah reminder');
await page.locator('button.btn-primary', { hasText: 'Post announcement' }).click();
await page.waitForTimeout(1000);
const postVisible = await page.locator('.post-row', { hasText: 'Friday khutbah reminder' }).isVisible().catch(() => false);
record('Neighbourhood: posting an announcement shows it in the board', postVisible);
// Join-by-code isolation: a second account joining via the real code should see the same post
const joinCodeText = await page.locator('.join-code').textContent();
const code = joinCodeText.replace('Join code:', '').trim();
// signInFreshFamily always signs in as the same fixed e2e owner account
// (just a new family) — since neighbourhoods are user-scoped, this "second
// account" already belongs to the neighbourhood created above, so the
// join form is behind the same toggle as before.
const secondContext = await browser.newContext({ viewport: { width: 390, height: 844 } });
const secondPage = await secondContext.newPage();
await signInFreshFamily(secondPage, BASE, 'e2e-khairat-neighbour2');
await gotoTab(secondPage, 'Neighbourhood');
await secondPage.waitForTimeout(600);
const secondAddToggleVisible = await secondPage.locator('.add-toggle').isVisible().catch(() => false);
if (secondAddToggleVisible) await secondPage.locator('.add-toggle').click();
await secondPage.waitForTimeout(300);
await secondPage.locator('.form-card .field:has-text("Join code") input').fill(code);
await secondPage.locator('button.btn-secondary', { hasText: 'Join' }).click();
await secondPage.waitForTimeout(1000);
const secondSeesPost = await secondPage.locator('.post-row', { hasText: 'Friday khutbah reminder' }).isVisible().catch(() => false);
record('Neighbourhood: a second account joining by code sees the same posts', secondSeesPost);
await secondContext.close();
// A 504/429/503 while trying one Overpass mirror before falling through to
// the next is the fallback mechanism working as designed, not a bug — the
// browser still logs the failed fetch as a console error either way, so
// filter those specific expected-noise lines out of this assertion.
const realConsoleErrors = consoleErrors.filter(e => !/overpass.*(429|503|504)|Gateway Timeout|Too Many Requests/i.test(e));
record('No uncaught JS console errors during full session', realConsoleErrors.length === 0, realConsoleErrors.slice(0, 5).join(' || '));
await browser.close();
const passCount = results.filter(r => r.pass).length;
const failCount = results.length - passCount;
console.log(`\n${passCount} passed, ${failCount} failed, ${results.length} total`);
if (failCount > 0) results.filter(r => !r.pass).forEach(r => console.log(` - ${r.name}: ${r.detail}`));
process.exit(failCount > 0 ? 1 : 0);
}
main().catch(e => { console.error('SCRIPT ERROR:', e); process.exit(2); });