LifeMate — Personal, Family & Learning Companion
feat: add final feature API
davoodmehraban89 committed
Oct 5, 2026 at 19:40 UTC
aba67dfb0c6ea60610da45b080fe14a1b069f350
1 file changed
+151
backend/src/phase6.js
new
+151
@@ -0,0 +1,151 @@
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;
16
+}
17
+
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
+
148
+ return router;
149
+}
150
+
151
+export { educationForGrade, trustedTextbookUrl };