-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.js
More file actions
255 lines (218 loc) · 8.49 KB
/
Copy pathbackend.js
File metadata and controls
255 lines (218 loc) · 8.49 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
// Import required libraries
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const nodemailer = require("nodemailer");
// Initialize the app
const app = express();
// Middleware
app.use(cors());
app.use(bodyParser.json());
// MongoDB Connection
const MONGO_URI = "mongodb://localhost:27017/attendance"; // Replace with your MongoDB connection string if using MongoDB Atlas
mongoose
.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("MongoDB connection error:", err));
// Mongoose Schema and Model for Attendance
const attendanceSchema = new mongoose.Schema({
name: { type: String, required: true },
employeeId: { type: String, required: true },
email: { type: String, required: true }, // Assuming email is required for sending warnings
date: { type: String, required: true },
timeIn: { type: String, required: true },
timeOut: { type: String, required: true },
comments: { type: String, default: "" },
lastPresentDate: { type: Date, required: true }, // Track the last present date for absences
submittedAt: { type: Date, default: Date.now },
});
const Attendance = mongoose.model("Attendance", attendanceSchema);
const employeeSchema = new mongoose.Schema({
name: { type: String, required: true }, // Employee's full name
employeeId: { type: String, required: true, unique: true }, // Unique ID for each employee
email: { type: String, required: true, unique: true }, // Email address for communication
department: { type: String, required: true }, // Department name (e.g., HR, IT)
designation: { type: String, required: true }, // Job title (e.g., Manager, Developer)
joiningDate: { type: Date, required: true }, // Date of joining
lastPresentDate: { type: Date, default: null }, // Last date the employee was present (can be updated dynamically)
contactNumber: { type: String, required: true }, // Employee's contact number
address: { type: String, default: "" }, // Residential address (optional)
status: { type: String, enum: ["Active", "Inactive"], default: "Active" }, // Employee status
});
const Employee = mongoose.model("Employee", employeeSchema);
module.exports = Employee;
// Email configuration
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "your-email@gmail.com", // Your email
pass: "your-email-password", // Your email password or app-specific password
},
});
// Function to send warning email
function sendWarningEmail(employee) {
const mailOptions = {
from: "your-email@gmail.com",
to: employee.email, // Email of the employee
subject: "Warning: Unreported Absence",
text: `Dear ${employee.name},\n\nWe have noticed that you have been absent for more than one day without prior notice. Please report to HR or provide a valid reason.\n\nRegards,\nHR Team`,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error(`Error sending email to ${employee.name}:`, error);
} else {
console.log(`Email sent to ${employee.name}:`, info.response);
}
});
}
// Route to check absences and send warnings
app.get("/check-absences", async (req, res) => {
try {
const today = new Date();
const employees = await Attendance.find();
employees.forEach((employee) => {
const lastPresentDate = new Date(employee.lastPresentDate);
const daysAbsent = (today - lastPresentDate) / (1000 * 3600 * 24); // Calculate days absent
if (daysAbsent > 1) {
sendWarningEmail(employee); // Send warning email if absent for more than 1 day
}
});
res.json({ message: "Warning emails sent for absentees." });
} catch (error) {
console.error("Error checking absences:", error);
res.status(500).json({ message: "An error occurred while checking absences." });
}
});
// Routes
// Add Attendance Record
app.post("/api/attendance", async (req, res) => {
const { name, employeeId, email, date, timeIn, timeOut, comments } = req.body;
// Validate required fields
if (!name || !employeeId || !email || !date || !timeIn || !timeOut) {
return res.status(400).json({ message: "All required fields must be filled" });
}
try {
const existingRecord = await Attendance.findOne({ employeeId, date });
if (existingRecord) {
return res.status(409).json({ message: "Record already exists for this date." });
}
const newRecord = new Attendance({
name,
employeeId,
email,
date,
timeIn,
timeOut,
comments,
lastPresentDate: date, // Update last present date to the current record's date
});
await newRecord.save();
res.status(201).json({ message: "Record added successfully" });
} catch (error) {
console.error("Error saving record:", error);
res.status(500).json({ message: "An error occurred while saving the record." });
}
});
// Get All Attendance Records
app.get("/api/attendance", async (req, res) => {
try {
const records = await Attendance.find();
res.json(records);
} catch (error) {
console.error("Error fetching records:", error);
res.status(500).json({ message: "An error occurred while fetching records." });
}
});
// Create a new employee
app.post("/api/employees", async (req, res) => {
const { name, employeeId, email, department, designation, joiningDate, contactNumber, address } = req.body;
// Validate required fields
if (!name || !employeeId || !email || !department || !designation || !joiningDate || !contactNumber) {
return res.status(400).json({ message: "All required fields must be filled." });
}
try {
const newEmployee = new Employee({
name,
employeeId,
email,
department,
designation,
joiningDate,
contactNumber,
address,
});
await newEmployee.save();
res.status(201).json({ message: "Employee added successfully", employee: newEmployee });
} catch (error) {
console.error("Error adding employee:", error);
res.status(500).json({ message: "An error occurred while adding the employee." });
}
});
// Get all employees
app.get("/api/employees", async (req, res) => {
try {
const employees = await Employee.find();
res.json(employees);
} catch (error) {
console.error("Error fetching employees:", error);
res.status(500).json({ message: "An error occurred while fetching employees." });
}
});
// Get a specific employee by ID
app.get("/employees/:id", async (req, res) => {
try {
const employee = await Employee.findById(req.params.id);
if (!employee) {
return res.status(404).json({ message: "Employee not found." });
}
res.json(employee);
} catch (error) {
console.error("Error fetching employee:", error);
res.status(500).json({ message: "An error occurred while fetching the employee." });
}
});
// Update an employee
app.put("/employees/:id", async (req, res) => {
try {
const updatedEmployee = await Employee.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
if (!updatedEmployee) {
return res.status(404).json({ message: "Employee not found." });
}
res.json({ message: "Employee updated successfully", employee: updatedEmployee });
} catch (error) {
console.error("Error updating employee:", error);
res.status(500).json({ message: "An error occurred while updating the employee." });
}
});
// Delete an employee
app.delete("/employees/:id", async (req, res) => {
try {
const deletedEmployee = await Employee.findByIdAndDelete(req.params.id);
if (!deletedEmployee) {
return res.status(404).json({ message: "Employee not found." });
}
res.json({ message: "Employee deleted successfully" });
} catch (error) {
console.error("Error deleting employee:", error);
res.status(500).json({ message: "An error occurred while deleting the employee." });
}
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
const cron = require("node-cron");
// Schedule the absence check daily at 8 AM
cron.schedule("0 8 * * *", () => {
console.log("Running daily absence check...");
attendanceData.forEach((employee) => {
const today = new Date();
const lastPresentDate = new Date(employee.lastPresent);
const daysAbsent = (today - lastPresentDate) / (1000 * 3600 * 24);
if (daysAbsent > 1) {
sendWarningEmail(employee);
}
});
});