@davoodmehraban89 / LifeMate / commits / 6832503
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: complete phase 4 guide safety and guardian summary API

davoodmehraban89 committed Oct 5, 2026 at 16:12 UTC 6832503b12b1ec902edb93817e8dd0c280da4fc9
1 file changed +285 -16
backend/src/phase4.js
+285 -16
@@ -1,19 +1,288 @@
1 import express from 'express';
2
3 -const clampText=(v,n=4000)=>String(v??'').trim().slice(0,n);
4 -const safetyClass=(text)=>{const t=text.toLowerCase();return /(خودکشی|خودم را بکشم|self[- ]?harm|suicide|kill myself)/i.test(t)?'urgent_review':/(غمگین|اضطراب|استرس|sad|anxious|stress)/i.test(t)?'supportive':'ordinary'};
5 -const localGuide=(kind,text,klass)=>{if(klass==='urgent_review')return 'من نمی‌توانم جای کمک فوری یا متخصص را بگیرم. اگر خطر فوری وجود دارد، همین حالا با یک فرد قابل اعتماد در نزدیکی خود یا خدمات اضطراری محلی تماس بگیر. می‌توانیم فقط روی قدم امن بعدی تمرکز کنیم.';if(kind==='study')return `پیشنهاد مطالعه: هدف را به یک بخش ۲۵ دقیقه‌ای کوچک تبدیل کن، بعد ۵ دقیقه استراحت و در پایان سه نکته را بدون نگاه‌کردن مرور کن. موضوع فعلی: ${text.slice(0,180)}`;if(kind==='planner')return 'پیشنهاد برنامه‌ریزی: فقط سه اولویت امروز را انتخاب کن؛ کار سخت‌تر را به کوچک‌ترین اقدام قابل شروع بشکن و زمان واقع‌بینانه برای استراحت نگه دار.';return 'می‌توانم برای خودبازتابی و عادت‌های حمایتی کمک کنم، نه تشخیص پزشکی. احساس را نام‌گذاری کن، شدت آن را بسنج و یک اقدام کوچک مثل آب، استراحت، حرکت کوتاه یا صحبت با فرد قابل اعتماد انتخاب کن.'};
6 -
7 -export function createPhase4Router({pool,auth}){
8 - const r=express.Router(); r.use(auth);
9 - r.post('/learning/goals',async(req,res)=>{const title=clampText(req.body.title,240);if(!title)return res.status(400).json({error:'invalid_input'});const q=await pool.query('insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *',[req.identity.sub,req.body.subjectId||null,title,clampText(req.body.target,1000)||null]);res.status(201).json(q.rows[0])});
10 - r.get('/learning/goals',async(req,res)=>{const q=await pool.query("select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc",[req.identity.sub]);res.json({items:q.rows})});
11 - r.post('/learning/checkins',async(req,res)=>{const c=Number(req.body.confidence),d=Number(req.body.difficulty);if(!Number.isInteger(c)||c<1||c>5||!Number.isInteger(d)||d<1||d>5)return res.status(400).json({error:'invalid_input'});const q=await pool.query('insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values($1,$2,$3,$4,$5) returning *',[req.identity.sub,req.body.learningGoalId||null,c,d,clampText(req.body.note,2000)||null]);res.status(201).json(q.rows[0])});
12 - r.post('/wellbeing/checkins',async(req,res)=>{const m=Number(req.body.mood),e=Number(req.body.energy),s=Number(req.body.stress);if(![m,e,s].every(x=>Number.isInteger(x)&&x>=1&&x<=5))return res.status(400).json({error:'invalid_input'});const visibility=req.body.visibility==='guardian_summary'?'guardian_summary':'private';const q=await pool.query('insert into wellbeing_checkin(owner_user_id,mood,energy,stress,note,visibility) values($1,$2,$3,$4,$5,$6) returning id,mood,energy,stress,visibility,created_at',[req.identity.sub,m,e,s,clampText(req.body.note,2000)||null,visibility]);res.status(201).json(q.rows[0])});
13 - r.get('/wellbeing/checkins',async(req,res)=>{const q=await pool.query('select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30',[req.identity.sub]);res.json({items:q.rows})});
14 - r.post('/ai/sessions',async(req,res)=>{const kind=['study','planner','wellbeing'].includes(req.body.kind)?req.body.kind:null;if(!kind)return res.status(400).json({error:'invalid_kind'});const q=await pool.query('insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *',[req.identity.sub,kind]);res.status(201).json(q.rows[0])});
15 - r.post('/ai/sessions/:id/messages',async(req,res)=>{const text=clampText(req.body.message);if(!text)return res.status(400).json({error:'invalid_input'});const s=await pool.query("select * from ai_guide_session where id=$1 and owner_user_id=$2 and status='active'",[req.params.id,req.identity.sub]);if(!s.rowCount)return res.status(404).json({error:'session_not_found'});const klass=safetyClass(text);await pool.query("insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)",[req.params.id,text,klass]);const reply=localGuide(s.rows[0].guide_kind,text,klass);const q=await pool.query("insert into ai_guide_message(session_id,author,body,safety_class) values($1,'assistant',$2,$3) returning id,body,safety_class,created_at",[req.params.id,reply,klass]);res.json({...q.rows[0],advisory:true,medicalDiagnosis:false,automaticAction:false})});
16 - r.post('/ai/proposals',async(req,res)=>{const title=clampText(req.body.title,240);if(!title||!req.body.proposal||typeof req.body.proposal!=='object')return res.status(400).json({error:'invalid_input'});const q=await pool.query('insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *',[req.identity.sub,req.body.sessionId||null,title,req.body.proposal]);res.status(201).json(q.rows[0])});
17 - r.patch('/ai/proposals/:id',async(req,res)=>{const status=['accepted','rejected'].includes(req.body.status)?req.body.status:null;if(!status)return res.status(400).json({error:'invalid_status'});const q=await pool.query("update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *",[req.params.id,req.identity.sub,status]);if(!q.rowCount)return res.status(404).json({error:'proposal_not_found'});res.json(q.rows[0])});
18 - return r;
3 +const clampText = (value, max = 4000) =>
4 + String(value ?? '').trim().slice(0, max);
5 +
6 +function safetyClass(text) {
7 + const value = text.toLowerCase();
8 + if (/(خودکشی|خودم را بکشم|آسیب به خود|self[- ]?harm|suicide|kill myself)/i.test(value)) {
9 + return 'urgent_review';
10 + }
11 + if (/(غمگین|اضطراب|استرس|نگران|sad|anxious|stress|worried)/i.test(value)) {
12 + return 'supportive';
13 + }
14 + return 'ordinary';
15 +}
16 +
17 +function localGuide(kind, text, klass) {
18 + if (klass === 'urgent_review') {
19 + return 'من جای کمک فوری یا متخصص را نمی‌گیرم. اگر خطر فوری وجود دارد، همین حالا با یک فرد قابل اعتماد در نزدیکی خود یا خدمات اضطراری محلی تماس بگیر. می‌توانیم فقط روی قدم امن بعدی تمرکز کنیم.';
20 + }
21 + if (kind === 'study') {
22 + return `پیشنهاد مطالعه: هدف را به یک بخش ۲۵ دقیقه‌ای کوچک تبدیل کن، بعد ۵ دقیقه استراحت و در پایان سه نکته را بدون نگاه‌کردن مرور کن. موضوع فعلی: ${text.slice(0, 180)}`;
23 + }
24 + if (kind === 'planner') {
25 + return 'پیشنهاد برنامه‌ریزی: فقط سه اولویت امروز را انتخاب کن؛ کار سخت‌تر را به کوچک‌ترین اقدام قابل شروع بشکن و برای استراحت زمان واقعی نگه دار.';
26 + }
27 + return 'می‌توانم برای خودبازتابی، ارتباط سالم و عادت‌های حمایتی کمک کنم، نه تشخیص پزشکی. احساس را نام‌گذاری کن، شدت آن را بسنج و یک اقدام کوچک مثل آب، استراحت، حرکت کوتاه یا صحبت با فرد قابل اعتماد انتخاب کن.';
28 +}
29 +
30 +async function providerGuide(kind, text, klass) {
31 + if (klass === 'urgent_review') return localGuide(kind, text, klass);
32 +
33 + const apiKey = process.env.AI_API_KEY;
34 + const baseUrl = process.env.AI_BASE_URL;
35 + const model = process.env.AI_MODEL;
36 + if (!apiKey || !baseUrl || !model) {
37 + return localGuide(kind, text, klass);
38 + }
39 +
40 + const system = [
41 + 'You are LifeMate, an age-appropriate Persian companion.',
42 + 'You are advisory, not a doctor, therapist, diagnostician, or emergency service.',
43 + 'For study, guide step-by-step and avoid simply giving final homework answers.',
44 + 'For planning, propose realistic options and preserve user agency.',
45 + 'For wellbeing, be calm, supportive, non-clinical, and encourage trusted human support when appropriate.',
46 + 'Never claim to know hidden mental state. Never expose private content to parents.',
47 + `Guide mode: ${kind}`,
48 + ].join(' ');
49 +
50 + const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
51 + method: 'POST',
52 + headers: {
53 + authorization: `Bearer ${apiKey}`,
54 + 'content-type': 'application/json',
55 + },
56 + body: JSON.stringify({
57 + model,
58 + temperature: 0.4,
59 + messages: [
60 + { role: 'system', content: system },
61 + { role: 'user', content: text },
62 + ],
63 + }),
64 + });
65 +
66 + if (!response.ok) return localGuide(kind, text, klass);
67 + const body = await response.json();
68 + const content = body?.choices?.[0]?.message?.content;
69 + return clampText(content, 6000) || localGuide(kind, text, klass);
70 +}
71 +
72 +async function guardianRelationship(pool, familyId, guardianUserId, minorUserId) {
73 + const result = await pool.query(
74 + `select 1
75 + from guardian_relationship g
76 + join family_membership gm
77 + on gm.family_id=g.family_id
78 + and gm.user_id=g.guardian_user_id
79 + and gm.ended_at is null
80 + join family_membership mm
81 + on mm.family_id=g.family_id
82 + and mm.user_id=g.minor_user_id
83 + and mm.ended_at is null
84 + where g.family_id=$1
85 + and g.guardian_user_id=$2
86 + and g.minor_user_id=$3
87 + and g.active=true`,
88 + [familyId, guardianUserId, minorUserId],
89 + );
90 + return result.rowCount > 0;
91 +}
92 +
93 +export function createPhase4Router({ pool, auth }) {
94 + const router = express.Router();
95 + router.use(auth);
96 +
97 + router.post('/learning/goals', async (req, res) => {
98 + const title = clampText(req.body.title, 240);
99 + if (!title) return res.status(400).json({ error: 'invalid_input' });
100 + const result = await pool.query(
101 + 'insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *',
102 + [
103 + req.identity.sub,
104 + req.body.subjectId || null,
105 + title,
106 + clampText(req.body.target, 1000) || null,
107 + ],
108 + );
109 + res.status(201).json(result.rows[0]);
110 + });
111 +
112 + router.get('/learning/goals', async (req, res) => {
113 + const result = await pool.query(
114 + "select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc",
115 + [req.identity.sub],
116 + );
117 + res.json({ items: result.rows });
118 + });
119 +
120 + router.post('/learning/checkins', async (req, res) => {
121 + const confidence = Number(req.body.confidence);
122 + const difficulty = Number(req.body.difficulty);
123 + if (
124 + !Number.isInteger(confidence) ||
125 + confidence < 1 ||
126 + confidence > 5 ||
127 + !Number.isInteger(difficulty) ||
128 + difficulty < 1 ||
129 + difficulty > 5
130 + ) {
131 + return res.status(400).json({ error: 'invalid_input' });
132 + }
133 + const result = await pool.query(
134 + 'insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values($1,$2,$3,$4,$5) returning *',
135 + [
136 + req.identity.sub,
137 + req.body.learningGoalId || null,
138 + confidence,
139 + difficulty,
140 + clampText(req.body.note, 2000) || null,
141 + ],
142 + );
143 + res.status(201).json(result.rows[0]);
144 + });
145 +
146 + router.post('/wellbeing/checkins', async (req, res) => {
147 + const mood = Number(req.body.mood);
148 + const energy = Number(req.body.energy);
149 + const stress = Number(req.body.stress);
150 + if (![mood, energy, stress].every((x) => Number.isInteger(x) && x >= 1 && x <= 5)) {
151 + return res.status(400).json({ error: 'invalid_input' });
152 + }
153 + const visibility =
154 + req.body.visibility === 'guardian_summary' ? 'guardian_summary' : 'private';
155 + const result = await pool.query(
156 + 'insert into wellbeing_checkin(owner_user_id,mood,energy,stress,note,visibility) values($1,$2,$3,$4,$5,$6) returning id,mood,energy,stress,visibility,created_at',
157 + [
158 + req.identity.sub,
159 + mood,
160 + energy,
161 + stress,
162 + clampText(req.body.note, 2000) || null,
163 + visibility,
164 + ],
165 + );
166 + res.status(201).json(result.rows[0]);
167 + });
168 +
169 + router.get('/wellbeing/checkins', async (req, res) => {
170 + const result = await pool.query(
171 + 'select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30',
172 + [req.identity.sub],
173 + );
174 + res.json({ items: result.rows });
175 + });
176 +
177 + router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', async (req, res) => {
178 + const allowed = await guardianRelationship(
179 + pool,
180 + req.params.familyId,
181 + req.identity.sub,
182 + req.params.minorUserId,
183 + );
184 + if (!allowed) return res.status(403).json({ error: 'forbidden' });
185 +
186 + const summary = await pool.query(
187 + `select
188 + count(*)::int as checkin_count,
189 + round(avg(mood)::numeric,2) as mood_average,
190 + round(avg(energy)::numeric,2) as energy_average,
191 + round(avg(stress)::numeric,2) as stress_average,
192 + min(created_at) as window_start,
193 + max(created_at) as window_end
194 + from wellbeing_checkin
195 + where owner_user_id=$1
196 + and visibility='guardian_summary'
197 + and created_at >= now()-interval '14 days'`,
198 + [req.params.minorUserId],
199 + );
200 + const safety = await pool.query(
201 + `select count(*)::int as open_urgent_count,max(created_at) as latest_urgent_at
202 + from wellbeing_safety_event
203 + where owner_user_id=$1 and status='open'`,
204 + [req.params.minorUserId],
205 + );
206 + res.json({
207 + summary: summary.rows[0],
208 + safety: safety.rows[0],
209 + rawNotesIncluded: false,
210 + rawConversationIncluded: false,
211 + medicalDiagnosis: false,
212 + });
213 + });
214 +
215 + router.post('/ai/sessions', async (req, res) => {
216 + const kind = ['study', 'planner', 'wellbeing'].includes(req.body.kind)
217 + ? req.body.kind
218 + : null;
219 + if (!kind) return res.status(400).json({ error: 'invalid_kind' });
220 + const result = await pool.query(
221 + 'insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *',
222 + [req.identity.sub, kind],
223 + );
224 + res.status(201).json(result.rows[0]);
225 + });
226 +
227 + router.post('/ai/sessions/:id/messages', async (req, res) => {
228 + const text = clampText(req.body.message);
229 + if (!text) return res.status(400).json({ error: 'invalid_input' });
230 + const session = await pool.query(
231 + "select * from ai_guide_session where id=$1 and owner_user_id=$2 and status='active'",
232 + [req.params.id, req.identity.sub],
233 + );
234 + if (!session.rowCount) return res.status(404).json({ error: 'session_not_found' });
235 +
236 + const klass = safetyClass(text);
237 + await pool.query(
238 + "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)",
239 + [req.params.id, text, klass],
240 + );
241 + if (klass === 'urgent_review') {
242 + await pool.query(
243 + "insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values($1,$2,'urgent_review')",
244 + [req.identity.sub, req.params.id],
245 + );
246 + }
247 +
248 + const reply = await providerGuide(session.rows[0].guide_kind, text, klass);
249 + const result = await pool.query(
250 + "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'assistant',$2,$3) returning id,body,safety_class,created_at",
251 + [req.params.id, reply, klass],
252 + );
253 + res.json({
254 + ...result.rows[0],
255 + advisory: true,
256 + medicalDiagnosis: false,
257 + automaticAction: false,
258 + providerMode: process.env.AI_API_KEY ? 'configured' : 'local_fallback',
259 + });
260 + });
261 +
262 + router.post('/ai/proposals', async (req, res) => {
263 + const title = clampText(req.body.title, 240);
264 + if (!title || !req.body.proposal || typeof req.body.proposal !== 'object') {
265 + return res.status(400).json({ error: 'invalid_input' });
266 + }
267 + const result = await pool.query(
268 + 'insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *',
269 + [req.identity.sub, req.body.sessionId || null, title, req.body.proposal],
270 + );
271 + res.status(201).json(result.rows[0]);
272 + });
273 +
274 + router.patch('/ai/proposals/:id', async (req, res) => {
275 + const status = ['accepted', 'rejected'].includes(req.body.status)
276 + ? req.body.status
277 + : null;
278 + if (!status) return res.status(400).json({ error: 'invalid_status' });
279 + const result = await pool.query(
280 + "update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *",
281 + [req.params.id, req.identity.sub, status],
282 + );
283 + if (!result.rowCount) return res.status(404).json({ error: 'proposal_not_found' });
284 + res.json(result.rows[0]);
285 + });
286 +
287 + return router;
288 }