LifeMate — Personal, Family & Learning Companion
feat: make final router independently mountable
davoodmehraban89 committed
Oct 5, 2026 at 19:41 UTC
8f4f20dc1b36c298fe2cfe35a28fc0128bf259bd
1 file changed
+29
-146
backend/src/phase6.js
+29
-146
@@ -1,151 +1,34 @@
1
import express from 'express';
2
-
3
-const stages = {
4
- primary_1: [1, 3, 0],
5
- primary_2: [4, 6, 3],
6
- secondary_1: [7, 9, 6],
7
- secondary_2: [10, 12, 9],
8
-};
9
-
10
-function educationForGrade(grade) {
11
- const n = Number(grade);
12
- for (const [stage, [min, max, offset]] of Object.entries(stages)) {
13
- if (Number.isInteger(n) && n >= min && n <= max) return { stage, nationalGrade: n, localYear: n - offset };
14
- }
15
- return null;
2
+import jwt from 'jsonwebtoken';
3
+
4
+const stages = { primary_1:[1,3,0], primary_2:[4,6,3], secondary_1:[7,9,6], secondary_2:[10,12,9] };
5
+function educationForGrade(grade){ const n=Number(grade); for(const [stage,[min,max,offset]] of Object.entries(stages)){ if(Number.isInteger(n)&&n>=min&&n<=max)return{stage,nationalGrade:n,localYear:n-offset}; } return null; }
6
+function validPersona(value){ return ['mother','father','child','adult'].includes(value); }
7
+function trustedTextbookUrl(value){ try{ const url=new URL(value); return url.protocol==='https:'&&['chap.sch.ir','medu.gov.ir'].includes(url.hostname); }catch{return false;} }
8
+
9
+function localAuth(pool){
10
+ return async (req,res,next)=>{ try{
11
+ const raw=req.headers.authorization?.replace(/^Bearer\s+/i,'');
12
+ const identity=jwt.verify(raw,process.env.JWT_SECRET,{audience:'lifemate-api',issuer:'lifemate'});
13
+ const session=await pool.query('select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',[identity.sid,identity.sub]);
14
+ if(!session.rowCount)return res.status(401).json({error:'session_invalid'});
15
+ req.identity=identity; next();
16
+ }catch{return res.status(401).json({error:'unauthorized'});} };
17
}
18
18
-function validPersona(value) {
19
- return ['mother', 'father', 'child', 'adult'].includes(value);
20
-}
21
-
22
-function trustedTextbookUrl(value) {
23
- try {
24
- const url = new URL(value);
25
- return url.protocol === 'https:' && ['chap.sch.ir', 'medu.gov.ir'].includes(url.hostname);
26
- } catch {
27
- return false;
28
- }
29
-}
30
-
31
-export function createPhase6Router({ pool, auth }) {
32
- const router = express.Router();
33
-
34
- router.get('/me/iran-profile', auth, async (req, res) => {
35
- const r = await pool.query(
36
- `select p.user_id,p.display_name,p.birth_date,p.household_persona,p.sex,
37
- e.stage,e.national_grade,e.local_year,e.school_name,e.school_year
38
- from profile p left join education_profile e on e.user_id=p.user_id
39
- where p.user_id=$1`,
40
- [req.identity.sub],
41
- );
42
- res.json(r.rows[0] ?? {});
43
- });
44
-
45
- router.patch('/me/iran-profile', auth, async (req, res) => {
46
- const persona = req.body.householdPersona;
47
- const sex = req.body.sex;
48
- if (persona != null && !validPersona(persona)) return res.status(400).json({ error: 'invalid_persona' });
49
- if (sex != null && !['female', 'male', 'unspecified'].includes(sex)) return res.status(400).json({ error: 'invalid_sex' });
50
- await pool.query(
51
- `update profile set household_persona=coalesce($2,household_persona),
52
- sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,
53
- [req.identity.sub, persona ?? null, sex ?? null, req.body.birthDate ?? null],
54
- );
55
- res.status(204).end();
56
- });
57
-
58
- router.put('/me/education', auth, async (req, res) => {
59
- const mapped = educationForGrade(req.body.nationalGrade);
60
- if (!mapped || (req.body.stage && req.body.stage !== mapped.stage)) {
61
- return res.status(400).json({ error: 'invalid_grade_stage' });
62
- }
63
- const schoolYear = String(req.body.schoolYear ?? '1405-1406');
64
- const r = await pool.query(
65
- `insert into education_profile(user_id,stage,national_grade,local_year,school_name,school_year)
66
- values($1,$2,$3,$4,$5,$6)
67
- on conflict(user_id) do update set stage=excluded.stage,national_grade=excluded.national_grade,
68
- local_year=excluded.local_year,school_name=excluded.school_name,school_year=excluded.school_year,updated_at=now()
69
- returning *`,
70
- [req.identity.sub, mapped.stage, mapped.nationalGrade, mapped.localYear, req.body.schoolName ?? null, schoolYear],
71
- );
72
- res.json(r.rows[0]);
73
- });
74
-
75
- router.get('/education/catalog', auth, async (req, res) => {
76
- const grade = Number(req.query.grade ?? 7);
77
- const schoolYear = String(req.query.schoolYear ?? '1405-1406');
78
- if (!educationForGrade(grade)) return res.status(400).json({ error: 'invalid_grade' });
79
- const r = await pool.query(
80
- `select s.id,s.code,s.name_fa,s.national_grade,s.school_year,
81
- t.title_fa,t.publisher,t.source_url,t.redistribution_status
82
- from curriculum_subject s left join textbook_catalog t on t.curriculum_subject_id=s.id
83
- where s.country_code='IR' and s.national_grade=$1 and s.school_year=$2 order by s.sort_order,s.name_fa`,
84
- [grade, schoolYear],
85
- );
86
- const rows = r.rows.map((row) => ({ ...row, source_url: trustedTextbookUrl(row.source_url) ? row.source_url : null }));
87
- res.json({ grade, mapping: educationForGrade(grade), subjects: rows });
88
- });
89
-
90
- router.get('/calendar/iran', auth, async (req, res) => {
91
- const year = Number(req.query.year ?? 1405);
92
- if (!Number.isInteger(year) || year < 1300 || year > 1600) return res.status(400).json({ error: 'invalid_jalali_year' });
93
- const r = await pool.query(
94
- `select jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url
95
- from iran_calendar_event where jalali_year=$1 order by jalali_month,jalali_day,title_fa`,
96
- [year],
97
- );
98
- res.json({ year, weekStartsOn: 'saturday', weekendDays: ['thursday', 'friday'], statutoryWeeklyHoliday: 'friday', events: r.rows });
99
- });
100
-
101
- router.get('/me/notification-preferences', auth, async (req, res) => {
102
- await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing', [req.identity.sub]);
103
- const r = await pool.query('select * from notification_preference where user_id=$1', [req.identity.sub]);
104
- res.json(r.rows[0]);
105
- });
106
-
107
- router.patch('/me/notification-preferences', auth, async (req, res) => {
108
- await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing', [req.identity.sub]);
109
- const fields = {
110
- inAppBanner: 'in_app_banner', pushEnabled: 'push_enabled', plannerReminders: 'planner_reminders',
111
- schoolReminders: 'school_reminders', calendarReminders: 'calendar_reminders', cycleReminders: 'cycle_reminders',
112
- sensitivePreview: 'sensitive_preview',
113
- };
114
- for (const [input, column] of Object.entries(fields)) {
115
- if (typeof req.body[input] === 'boolean') {
116
- await pool.query(`update notification_preference set ${column}=$2,updated_at=now() where user_id=$1`, [req.identity.sub, req.body[input]]);
117
- }
118
- }
119
- const r = await pool.query('select * from notification_preference where user_id=$1', [req.identity.sub]);
120
- res.json(r.rows[0]);
121
- });
122
-
123
- // Deliberately owner-only. There is no family/guardian menstrual endpoint.
124
- router.get('/me/menstrual-cycles', auth, async (req, res) => {
125
- const r = await pool.query(
126
- 'select id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled,created_at,updated_at from menstrual_cycle_entry where owner_user_id=$1 order by starts_on desc limit 36',
127
- [req.identity.sub],
128
- );
129
- res.json({ entries: r.rows });
130
- });
131
-
132
- router.post('/me/menstrual-cycles', auth, async (req, res) => {
133
- if (!req.body.startsOn) return res.status(400).json({ error: 'starts_on_required' });
134
- const symptoms = Array.isArray(req.body.symptoms) ? req.body.symptoms.slice(0, 20).map(String) : [];
135
- const r = await pool.query(
136
- `insert into menstrual_cycle_entry(owner_user_id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled)
137
- values($1,$2::date,$3::date,$4::date,$5::text[],$6,$7) returning id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled`,
138
- [req.identity.sub, req.body.startsOn, req.body.endsOn ?? null, req.body.predictedNextOn ?? null, symptoms, req.body.notes ?? null, req.body.reminderEnabled === true],
139
- );
140
- res.status(201).json(r.rows[0]);
141
- });
142
-
143
- router.delete('/me/menstrual-cycles/:id', auth, async (req, res) => {
144
- await pool.query('delete from menstrual_cycle_entry where id=$1 and owner_user_id=$2', [req.params.id, req.identity.sub]);
145
- res.status(204).end();
146
- });
147
-
19
+export function createPhase6Router({pool,auth}){
20
+ const router=express.Router(); const requireAuth=auth??localAuth(pool);
21
+ router.get('/me/iran-profile',requireAuth,async(req,res)=>{ const r=await pool.query(`select p.user_id,p.display_name,p.birth_date,p.household_persona,p.sex,e.stage,e.national_grade,e.local_year,e.school_name,e.school_year from profile p left join education_profile e on e.user_id=p.user_id where p.user_id=$1`,[req.identity.sub]); res.json(r.rows[0]??{}); });
22
+ router.patch('/me/iran-profile',requireAuth,async(req,res)=>{ const persona=req.body.householdPersona,sex=req.body.sex; if(persona!=null&&!validPersona(persona))return res.status(400).json({error:'invalid_persona'}); if(sex!=null&&!['female','male','unspecified'].includes(sex))return res.status(400).json({error:'invalid_sex'}); await pool.query(`update profile set household_persona=coalesce($2,household_persona),sex=coalesce($3,sex),birth_date=coalesce($4::date,birth_date),updated_at=now() where user_id=$1`,[req.identity.sub,persona??null,sex??null,req.body.birthDate??null]); res.status(204).end(); });
23
+ router.put('/me/education',requireAuth,async(req,res)=>{ const mapped=educationForGrade(req.body.nationalGrade); if(!mapped||(req.body.stage&&req.body.stage!==mapped.stage))return res.status(400).json({error:'invalid_grade_stage'}); const schoolYear=String(req.body.schoolYear??'1405-1406'); const r=await pool.query(`insert into education_profile(user_id,stage,national_grade,local_year,school_name,school_year) values($1,$2,$3,$4,$5,$6) on conflict(user_id) do update set stage=excluded.stage,national_grade=excluded.national_grade,local_year=excluded.local_year,school_name=excluded.school_name,school_year=excluded.school_year,updated_at=now() returning *`,[req.identity.sub,mapped.stage,mapped.nationalGrade,mapped.localYear,req.body.schoolName??null,schoolYear]); res.json(r.rows[0]); });
24
+ router.get('/education/catalog',requireAuth,async(req,res)=>{ const grade=Number(req.query.grade??7),schoolYear=String(req.query.schoolYear??'1405-1406'); if(!educationForGrade(grade))return res.status(400).json({error:'invalid_grade'}); const r=await pool.query(`select s.id,s.code,s.name_fa,s.national_grade,s.school_year,t.title_fa,t.publisher,t.source_url,t.redistribution_status from curriculum_subject s left join textbook_catalog t on t.curriculum_subject_id=s.id where s.country_code='IR' and s.national_grade=$1 and s.school_year=$2 order by s.sort_order,s.name_fa`,[grade,schoolYear]); res.json({grade,mapping:educationForGrade(grade),subjects:r.rows.map(row=>({...row,source_url:trustedTextbookUrl(row.source_url)?row.source_url:null}))}); });
25
+ router.get('/calendar/iran',requireAuth,async(req,res)=>{ const year=Number(req.query.year??1405); if(!Number.isInteger(year)||year<1300||year>1600)return res.status(400).json({error:'invalid_jalali_year'}); const r=await pool.query(`select jalali_year,jalali_month,jalali_day,title_fa,is_official_holiday,source_name,source_url from iran_calendar_event where jalali_year=$1 order by jalali_month,jalali_day,title_fa`,[year]); res.json({year,weekStartsOn:'saturday',weekendDays:['thursday','friday'],statutoryWeeklyHoliday:'friday',events:r.rows}); });
26
+ router.get('/me/notification-preferences',requireAuth,async(req,res)=>{ await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing',[req.identity.sub]); const r=await pool.query('select * from notification_preference where user_id=$1',[req.identity.sub]); res.json(r.rows[0]); });
27
+ router.patch('/me/notification-preferences',requireAuth,async(req,res)=>{ await pool.query('insert into notification_preference(user_id) values($1) on conflict do nothing',[req.identity.sub]); const fields={inAppBanner:'in_app_banner',pushEnabled:'push_enabled',plannerReminders:'planner_reminders',schoolReminders:'school_reminders',calendarReminders:'calendar_reminders',cycleReminders:'cycle_reminders',sensitivePreview:'sensitive_preview'}; for(const [input,column] of Object.entries(fields)){if(typeof req.body[input]==='boolean')await pool.query(`update notification_preference set ${column}=$2,updated_at=now() where user_id=$1`,[req.identity.sub,req.body[input]]);} const r=await pool.query('select * from notification_preference where user_id=$1',[req.identity.sub]); res.json(r.rows[0]); });
28
+ // Owner-private wellness records; no relationship-based read path is exposed.
29
+ router.get('/me/menstrual-cycles',requireAuth,async(req,res)=>{ const r=await pool.query('select id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled,created_at,updated_at from menstrual_cycle_entry where owner_user_id=$1 order by starts_on desc limit 36',[req.identity.sub]); res.json({entries:r.rows}); });
30
+ router.post('/me/menstrual-cycles',requireAuth,async(req,res)=>{ if(!req.body.startsOn)return res.status(400).json({error:'starts_on_required'}); const symptoms=Array.isArray(req.body.symptoms)?req.body.symptoms.slice(0,20).map(String):[]; const r=await pool.query(`insert into menstrual_cycle_entry(owner_user_id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled) values($1,$2::date,$3::date,$4::date,$5::text[],$6,$7) returning id,starts_on,ends_on,predicted_next_on,symptoms,notes,reminder_enabled`,[req.identity.sub,req.body.startsOn,req.body.endsOn??null,req.body.predictedNextOn??null,symptoms,req.body.notes??null,req.body.reminderEnabled===true]); res.status(201).json(r.rows[0]); });
31
+ router.delete('/me/menstrual-cycles/:id',requireAuth,async(req,res)=>{ await pool.query('delete from menstrual_cycle_entry where id=$1 and owner_user_id=$2',[req.params.id,req.identity.sub]); res.status(204).end(); });
32
return router;
33
}
150
-
151
-export { educationForGrade, trustedTextbookUrl };
34
+export {educationForGrade,trustedTextbookUrl};