-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
111 lines (95 loc) · 3.47 KB
/
index.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
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyParser = require('body-parser');
// Middleware
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(express.static('public'));
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/makerspace', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch(err => {
console.error('Connection error', err);
});
// Visitor Schema and Model
const visitorSchema = new mongoose.Schema({
visitorId: { type: Number, unique: true }, // Field to store visitor ID
timestamp: { type: Date, default: Date.now },
});
// Pre-save middleware to assign visitorId
visitorSchema.pre('save', async function (next) {
// Find the highest current visitorId
const lastVisitor = await Visitor.findOne().sort({ visitorId: -1 });
// If there are no visitors yet, start at 1; otherwise, increment the last visitorId
this.visitorId = lastVisitor ? lastVisitor.visitorId + 1 : 1;
next();
});
const Visitor = mongoose.model('Visitor', visitorSchema);
// Route to handle QR code scan and count visitor with quantity input
app.get('/scan-success', (req, res) => {
res.render('success', { showQuantityForm: true }); // Show form to input quantity
});
// Route to handle the form submission with quantity
app.post('/scan-success', async (req, res) => {
const quantity = parseInt(req.body.quantity, 10); // Get the quantity of people
if (isNaN(quantity) || quantity <= 0) {
return res.status(400).send('Invalid quantity.');
}
try {
// Create visitor records based on the input quantity
for (let i = 0; i < quantity; i++) {
const visitor = new Visitor();
await visitor.save();
}
res.render('success', { showQuantityForm: false }); // Hide form after successful submission
} catch (err) {
console.error('Error saving visitors:', err);
res.status(500).send('Error saving visitors');
}
});
// Admin route to see visitor count and filter by date
app.get('/admin', async (req, res) => {
try {
const selectedDate = req.query.date; // Get the selected date from query parameters
let filteredVisitors = [];
let visitorCount = await Visitor.countDocuments(); // Total count of all visitors
if (selectedDate) {
// Find visitors for the selected date
const startOfDay = new Date(selectedDate);
const endOfDay = new Date(selectedDate);
endOfDay.setDate(endOfDay.getDate() + 1);
filteredVisitors = await Visitor.find({
timestamp: { $gte: startOfDay, $lt: endOfDay },
}).sort({ visitorId: 1 });
}
res.render('admin', {
count: visitorCount, // Total visitors (all time)
filteredVisitors, // Visitors for the selected date
selectedDate, // The date selected in the filter
});
} catch (err) {
res.status(500).send('Error fetching visitor data');
}
});
// Route to clear all visitor data
app.post('/admin/clear', async (req, res) => {
try {
await Visitor.deleteMany({}); // Deletes all records in the Visitor collection
res.redirect('/admin'); // Redirect back to the admin page after clearing
} catch (err) {
console.error('Error clearing visitor data:', err);
res.status(500).send('Error clearing visitor data');
}
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});