Repository navigation
Expand file tree
/
Copy pathprofile.js
More file actions
294 lines (228 loc) · 7.6 KB
/
Copy pathprofile.js
File metadata and controls
294 lines (228 loc) · 7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// profile.js
// MindMetrics Profile + Prediction API (Node.js + MongoDB)
const express = require("express");
const cors = require("cors");
const { MongoClient } = require("mongodb");
require("dotenv").config(); // 🔐 LOADS .env VARIABLES
console.log("Gemini Key Loaded:", !!process.env.GEMINI_API_KEY);
const app = express();
app.use(cors({ origin: "*" }));
app.use(express.json({ limit: "25mb" }));
// ------------- CONFIG -------------
const MONGO_URI =
process.env.MONGO_URI ||
"mongodb+srv://rohit127634_db_user:9y23ssKikk6H0CCO@cluster0.7koxajh.mongodb.net/?retryWrites=true&w=majority";
const DB_NAME = "MindMatrics";
const USERS_COLLECTION = "users";
const PREDICTIONS_COLLECTION = "predictions";
// ----------------------------------
// Create MongoDB client (IMPORTANT)
const client = new MongoClient(MONGO_URI);
let db, usersCollection, predictionsCollection;
// ---------------- DB INIT ----------------
async function initDb() {
try {
await client.connect();
console.log("✅ Connected to MongoDB");
db = client.db(DB_NAME);
usersCollection = db.collection(USERS_COLLECTION);
// Check if predictions collection exists
const collections = await db.listCollections({}, { nameOnly: true }).toArray();
const names = collections.map((c) => c.name);
if (!names.includes(PREDICTIONS_COLLECTION)) {
await db.createCollection(PREDICTIONS_COLLECTION);
console.log("📁 Created predictions collection");
}
predictionsCollection = db.collection(PREDICTIONS_COLLECTION);
// Ensure each user gets only one prediction per day
await predictionsCollection.createIndex(
{ email: 1, date: 1 },
{ unique: true }
);
console.log("🔐 Index ensured: predictions(email + date)");
} catch (err) {
console.error("❌ DB Init Error:", err);
process.exit(1);
}
}
initDb();
/* -------------------------
PROFILE API
------------------------- */
app.get("/get-profile-by-email/:email", async (req, res) => {
const email = req.params.email;
if (!email) return res.json({ status: "error", error: "Email missing" });
try {
const user = await usersCollection.findOne({ email });
if (!user) return res.json({ status: "empty" });
res.json({ status: "success", profile: user });
} catch (err) {
console.error("❌ Query Error:", err);
res.json({ status: "error", error: err.message });
}
});
app.post("/save-profile-by-email", async (req, res) => {
const { email, fullName, phone, bio, dob, age, gender, profileImage } = req.body;
if (!email) return res.json({ status: "error", error: "Email required" });
try {
const ageNumber = age ? Number(age) : null;
const data = {
email,
fullName: fullName || null,
phone: phone || null,
bio: bio || null,
dob: dob || null,
age: Number.isFinite(ageNumber) ? ageNumber : null,
gender: gender || null,
profileImage: profileImage || null,
updatedAt: new Date(),
};
await usersCollection.updateOne(
{ email },
{ $set: data },
{ upsert: true }
);
console.log("✅ Profile saved:", email);
res.json({ status: "success", email });
} catch (err) {
console.error("❌ Save Error:", err);
res.json({ status: "error", error: err.message });
}
});
/* -------------------------
PREDICTION API
------------------------- */
app.post("/savePrediction", async (req, res) => {
try {
const { email, prediction, inputs } = req.body;
const timestampIncoming = req.body.timestamp
? new Date(req.body.timestamp)
: new Date();
const dateStr =
req.body.date || timestampIncoming.toISOString().split("T")[0];
if (!email)
return res.status(400).json({ status: "error", error: "Email required" });
// Fetch user details (name, age)
const user = await usersCollection.findOne({ email });
const name = user?.fullName || email.split("@")[0];
const age = user?.age ?? null;
const doc = {
email,
name,
age,
prediction: prediction || {},
inputs: inputs || {},
timestamp: timestampIncoming,
date: dateStr,
updatedAt: new Date(),
};
// Upsert (one prediction per day)
const filter = { email, date: dateStr };
const update = {
$set: doc,
$setOnInsert: { createdAt: new Date() },
};
const result = await predictionsCollection.updateOne(filter, update, {
upsert: true,
});
console.log(`✅ Prediction saved for ${email} on ${dateStr}`);
res.json({
status: "success",
email,
date: dateStr,
updated: result.modifiedCount,
created: result.upsertedCount,
});
} catch (err) {
console.error("❌ Prediction Save Error:", err);
res.status(500).json({ status: "error", error: err.message });
}
});
app.get("/get-predictions/:email", async (req, res) => {
const email = req.params.email;
if (!email) return res.json({ status: "error", error: "Email missing" });
try {
const items = await predictionsCollection
.find({ email })
.sort({ date: -1 })
.toArray();
res.json({ status: "success", predictions: items });
} catch (err) {
console.error("❌ Fetch Error:", err);
res.json({ status: "error", error: err.message });
}
});
/* -------------------------
AI BEHAVIORAL INSIGHTS API
------------------------- */
/* -------- AI BEHAVIORAL INSIGHTS API -------- */
const { GoogleGenAI } = require("@google/genai");
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
app.post("/behavioralInsights", async (req, res) => {
try {
const { email } = req.body;
if (!email) return res.status(400).json({ error: "Email is required" });
const logs = await predictionsCollection
.find({ email })
.sort({ timestamp: -1 })
.limit(60)
.toArray();
if (logs.length === 0) {
return res.json({
patterns: {
warning: "Not enough data to identify behavioral patterns.",
positive: "Once you have more prediction entries, insights will appear here.",
suggestion: "Use the prediction tool regularly to unlock personalized insights.",
},
});
}
const compactLogs = logs.map(doc => ({
date: doc.date,
stressScore: Number(doc.prediction?.stressScore || 0),
whatsapp: doc.inputs?.whatsapp || 0,
instagram: doc.inputs?.instagram || 0,
youtube: doc.inputs?.youtube || 0,
sentimentScore: doc.inputs?.sentimentScore || 0,
dayType: doc.inputs?.dayType || "0"
}));
const prompt = `
Analyze the following stress prediction logs from a user:
${JSON.stringify(compactLogs)}
Identify:
1) A WARNING pattern
2) A POSITIVE pattern
3) An ACTIONABLE suggestion
Return JSON ONLY:
{
"warning": "...",
"positive": "...",
"suggestion": "..."
}
`;
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: prompt,
});
let raw = response.candidates[0].content.parts[0].text.trim();
// Remove ```json and ``` blocks if Gemini adds them
raw = raw.replace(/```json|```/g, "").trim();
let patterns = JSON.parse(raw);
return res.json({ patterns });
} catch (err) {
console.error("❌ Behavioral Insights Error:", err);
return res.status(500).json({ error: "Internal Server Error" });
}
});
/* -------------------------
ROOT ROUTE
------------------------- */
app.get("/", (req, res) => {
res.send("✅ MindMetrics Profile & Prediction API Running");
});
/* -------------------------
START SERVER
------------------------- */
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
});