-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
405 lines (361 loc) · 12.5 KB
/
server.js
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
const express = require("express");
const cors = require("cors");
const { readFile, writeFile } = require("fs");
const path = require("path");
const transporter = require("./email.js");
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/"); // Specify the uploads folder
},
filename: (req, file, cb) => {
// Preserve the original filename
const uniqueSuffix = `${Date.now()}-${Math.round(
Math.random() * 1e9
)}`;
const originalName = file.originalname;
cb(null, `${uniqueSuffix}-${originalName}`); // Append timestamp to avoid overwriting
},
});
const upload = multer({ storage: storage }); // Temporary directory for uploaded files
const app = express();
const PORT = 3000; // Choose a port number
app.use(cors());
app.use(express.json()); // Use express.json() for parsing JSON bodies
// File paths to the JSON data
const OPPORTUNITIES_FILE = path.join(
__dirname,
"opportunityData.json"
);
const ACCOUNTS_FILE = path.join(__dirname, "accountData.json");
const APPLICATIONS_FILE = path.join(
__dirname,
"applicationsData.json"
);
// Default route for '/'
app.get("/", (req, res) => {
res.send(
"Welcome to the API. Use /opportunities, /accounts, /applications or /smart-search to fetch data."
);
});
// GET endpoint to fetch all opportunities
app.get("/opportunities", (req, res) => {
readFile(OPPORTUNITIES_FILE, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).send("Error reading data");
}
res.json(JSON.parse(data));
});
});
// POST endpoint to add a new opportunity
app.post("/opportunities", (req, res) => {
readFile(OPPORTUNITIES_FILE, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).json({
status: "error",
message: "Error reading data file.",
});
}
try {
const opportunities = JSON.parse(data);
const newOpportunity = req.body;
opportunities.push(newOpportunity);
writeFile(
OPPORTUNITIES_FILE,
JSON.stringify(opportunities, null, 2),
(writeErr) => {
if (writeErr) {
console.error("Error writing file:", writeErr);
return res.status(500).json({
status: "error",
message: "Error saving opportunity data.",
});
}
res.status(201).json({
status: "success",
data: newOpportunity,
});
}
);
} catch (parseErr) {
console.error("Error parsing JSON:", parseErr);
res.status(500).json({
status: "error",
message: "Error parsing data file.",
});
}
});
});
// GET endpoint to fetch all accounts
app.get("/accounts", (req, res) => {
readFile(ACCOUNTS_FILE, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).send("Error reading data");
}
res.json(JSON.parse(data));
});
});
// POST endpoint to add a new account
app.post("/accounts", (req, res) => {
readFile(ACCOUNTS_FILE, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return res.status(500).json({
status: "error",
message: "Error reading data file.",
});
}
try {
const accounts = JSON.parse(data);
const newAccount = req.body;
// Add the new account to the array
accounts.push(newAccount);
// Write the updated accounts array back to the file
writeFile(
ACCOUNTS_FILE,
JSON.stringify(accounts, null, 2),
(writeErr) => {
if (writeErr) {
console.error("Error writing file:", writeErr);
return res.status(500).json({
status: "error",
message: "Error saving account data.",
});
}
res.status(201).json({
status: "success",
data: newAccount,
});
}
);
} catch (parseErr) {
console.error("Error parsing JSON:", parseErr);
res.status(500).json({
status: "error",
message: "Error parsing data file.",
});
}
});
});
const readJSONFile = async (filePath) => {
return new Promise((resolve, reject) => {
readFile(filePath, "utf-8", (err, data) => {
if (err) return reject(err);
try {
resolve(JSON.parse(data));
} catch (parseError) {
reject(parseError);
}
});
});
};
// GET endpoint to fetch all applications
app.get("/applications", (req, res) => {
readFile(APPLICATIONS_FILE, "utf8", (err, data) => {
if (err) {
console.error("Error reading applications file:", err);
return res.status(500).send("Error reading applications data");
}
res.json(JSON.parse(data));
});
});
app.post(
"/applications",
upload.single("cvUpload"),
async (req, res) => {
try {
const { userId, opportunityId } = req.body;
const file = req.file; // Access the uploaded file
console.log("Received application data:", {
userId,
opportunityId,
});
const date = new Date();
const applicationDate = date.toISOString().split("T")[0];
// Generate application data
const newApplication = {
application_id: `${Date.now()}`,
user_id: userId,
opportunity_id: opportunityId,
application_date: applicationDate,
};
// Read existing applications from file
readFile(APPLICATIONS_FILE, "utf8", (err, data) => {
const applications = err ? [] : JSON.parse(data);
// Add the new application
applications.push(newApplication);
// Write back the updated applications array
writeFile(
APPLICATIONS_FILE,
JSON.stringify(applications, null, 2),
(writeErr) => {
if (writeErr) {
console.error(
"Error writing to applications file:",
writeErr
);
return res.status(500).json({
status: "error",
message: "Failed to save application data.",
});
}
console.log(
"Application saved successfully:",
newApplication
);
}
);
});
// Fetch user and opportunity data
const accounts = await readJSONFile(ACCOUNTS_FILE);
const user = accounts.find((account) => account.id === userId);
if (!user)
return res.status(404).json({ error: "User not found" });
const opportunities = await readJSONFile(OPPORTUNITIES_FILE);
const opportunity = opportunities.find(
(opp) => opp.id == opportunityId
);
if (!opportunity || !opportunity.contactPersonEmail) {
return res
.status(404)
.json({ error: "Opportunity or contact email not found" });
}
const studentName = user.name_and_surname;
const studentEmail = user.email;
const universityName = user.university_name || "N/A";
const universityLocation = user.university_location || "N/A";
const telekomEmail = opportunity.contactPersonEmail;
const opportunityTitle = opportunity.title;
// Email to Telekom employee
const telekomMailOptions = {
from: "[email protected]",
to: telekomEmail,
subject: `New Application for ${opportunityTitle} through Student Platform`,
html: `<h1>New Application Received</h1>
<h3>${studentName} has applied for <b>${opportunityTitle}</b> opportunity.</h3>
<p><b>Applicant:</b> ${studentName} (${studentEmail})</p>
<p><b>University:</b> ${universityName}, ${universityLocation}</p>
<p><b>Note:</b> If provided, CV will be attached</p>`,
attachments: file
? [{ path: file.path, filename: file.originalname }]
: [],
};
// Email to student
const studentMailOptions = {
from: "[email protected]",
to: studentEmail,
subject: `Application Confirmation for ${opportunityTitle}`,
html: `<h1>Application Confirmation</h1>
<h3>Thank you for applying for <b>${opportunityTitle} opportunity</b>.</h3>
<p><b>Opportunity:</b> ${opportunityTitle}</p>
<p><b>Contact Person Email:</b> ${telekomEmail}</p>
<p><b>Your Name:</b> ${studentName}</p>
<p><b>Your Email:</b> ${studentEmail}</p>
<p><b>University:</b> ${universityName}, ${universityLocation}</p>`,
attachments: file
? [{ path: file.path, filename: file.originalname }]
: [],
};
// Send emails
console.log("Sending emails...");
await transporter.sendMail(telekomMailOptions);
await transporter.sendMail(studentMailOptions);
// Cleanup: Delete the uploaded file
if (file) {
const fs = require("fs");
fs.unlink(file.path, (err) => {
if (err) console.error("Failed to delete file:", err);
});
}
res.status(200).json({ message: "Emails sent successfully!" });
console.log(
"Email sent succesfully!\nApplication processed successfully!"
);
} catch (error) {
console.error("Error handling application:", error);
res
.status(500)
.json({ error: "Error processing the application" });
}
}
);
app.post("/smart-search", async (req, res) => {
try {
const { query } = req.body;
console.log(query);
if (!query)
return res.status(400).json({ error: "Query is required" });
// Read JSON data from files
const accounts = await readJSONFile(ACCOUNTS_FILE);
const opportunities = await readJSONFile(OPPORTUNITIES_FILE);
const applications = await readJSONFile(APPLICATIONS_FILE);
// Merge data into a human-readable prompt
const documents = applications.map((app) => {
const user =
accounts.find((acc) => acc.id === app.user_id) || {};
const opportunity =
opportunities.find((opp) => opp.id == app.opportunity_id) ||
{};
return `[ID: ${app.application_id}] Applicant "${user.name_and_surname}" from University "${user.university_name}" located at "${user.university_location}" applied for "${opportunity.title}" opportunity from "${opportunity.location}" on application date of "${app.application_date}".`;
});
const prompt = `Find the most relevant matches for this query: "${query}". Here are the applications:\n${documents.join(
"\n"
)}\n\nPlease return only the application IDs that match the query. Provide the IDs in the following format:\n\n"Matching IDs: [1, 2, 3]"`;
console.log(prompt);
// Send the prompt to the DeepSeek AI model
const response = await fetch(
"http://127.0.0.1:11434/api/generate",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "nezahatkorkmaz/deepseek-v3:latest",
prompt,
stream: false,
}),
}
);
if (!response.ok) {
throw new Error(`DeepSeek API error: ${response.statusText}`);
}
const responseData = await response.json();
const deepSeekResponse = responseData.response;
// Extract matching application IDs
const match = deepSeekResponse.match(/Matching IDs: \[(.*?)\]/);
const matchingIds = match
? match[1].split(",").map((id) => id.trim())
: [];
// Filter applications based on IDs and enrich them with full data
const enrichedResults = applications
.filter((app) => matchingIds.includes(app.application_id))
.map((app) => {
const user =
accounts.find((acc) => acc.id === app.user_id) || {};
const opportunity =
opportunities.find((opp) => opp.id == app.opportunity_id) ||
{};
return {
application_id: app.application_id,
application_date: app.application_date,
applicant_name: user.name_and_surname,
applicant_email: user.email,
university_name: user.university_name,
university_location: user.university_location,
opportunity_title: opportunity.title,
opportunity_location: opportunity.location,
};
});
res.json(enrichedResults);
} catch (error) {
console.error("Error performing smart search:", error);
res.status(500).json({ error: "Failed to perform smart search" });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});