forked from coryhouse/ps-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-server.js
More file actions
822 lines (714 loc) · 28.8 KB
/
Copy pathserver-server.js
File metadata and controls
822 lines (714 loc) · 28.8 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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const pool = require('./db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const nodemailer = require('nodemailer');
const JWT_SECRET = process.env.JWT_SECRET || 'visitor_app_jwt_secret_change_in_production';
// ================= AUTH MIDDLEWARE =================
const authenticate = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch {
return res.status(401).json({ error: 'Invalid or expired token' });
}
};
const requireAdmin = (req, res, next) => {
if (req.user?.role !== 'admin') return res.status(403).json({ error: 'Admin access required' });
next();
};
const app = express();
const PORT = process.env.PORT || 5000;
// ================= MIDDLEWARE =================
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// ================= HELPERS =================
const generateOtp = () => Math.floor(100000 + Math.random() * 900000).toString();
const normalizePhone = (v) => (v ? v.replace(/\D/g, '') : '');
const isPhone = (v) => /^\+?[0-9][0-9\-\s().]{5,}$/.test(v);
// ================= OTP STORE =================
const otpStore = {};
// ================= SMTP =================
const smtpEnabled =
process.env.SMTP_HOST &&
process.env.SMTP_USER &&
process.env.SMTP_PASS &&
process.env.OTP_FROM_EMAIL;
const transporter = smtpEnabled
? nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT) || 587,
secure: process.env.SMTP_SECURE === 'true',
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
})
: null;
const sendOtpEmail = async (to, otp) => {
if (!transporter) throw new Error("SMTP not configured");
const htmlContent = `
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: 'Roboto Condensed', Arial, sans-serif; background: #f4f4f4; }
.container { max-width: 500px; margin: 0 auto; background: #fff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.header { text-align: center; color: #ff8a00; margin-bottom: 20px; }
.otp-box { background: #0c1530; color: #ff8a00; padding: 20px; border-radius: 8px; text-align: center; margin: 20px 0; border: 2px solid #ff8a00; }
.otp-text { font-size: 32px; font-weight: bold; letter-spacing: 2px; }
.footer { text-align: center; color: #666; font-size: 12px; margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>🔐 Visitor Manager - Password Reset</h2>
</div>
<p>Hello,</p>
<p>You requested a password reset for your Visitor Manager account.</p>
<p><strong>Your OTP (One-Time Password) is:</strong></p>
<div class="otp-box">
<div class="otp-text">${otp}</div>
</div>
<p style="color: #999;">⏱️ This OTP is valid for <strong>10 minutes</strong>.</p>
<p><strong>⚠️ Security Notice:</strong></p>
<ul>
<li>Never share your OTP with anyone</li>
<li>Visitor Manager team will never ask for your OTP</li>
<li>If you didn't request this, please ignore this email</li>
</ul>
<div class="footer">
<p>© 2024 Visitor Manager. All rights reserved.</p>
</div>
</div>
</body>
</html>
`;
await transporter.sendMail({
from: process.env.OTP_FROM_EMAIL,
to,
subject: '🔐 Your Password Reset OTP - Visitor Manager',
html: htmlContent,
});
};
// ================= HEALTH =================
app.get('/health', async (req, res) => {
res.json({ status: 'ok' });
});
// ================= AUTH =================
// SIGNUP
app.post('/signup', async (req, res) => {
try {
const { name, email, password, phone_number } = req.body;
if (!name || !email || !password)
return res.status(400).json({ error: 'All fields required' });
const exists = await pool.query(
'SELECT id FROM users WHERE email=$1',
[email.toLowerCase()]
);
if (exists.rows.length)
return res.status(409).json({ error: 'User exists' });
const hash = await bcrypt.hash(password, 10);
const result = await pool.query(
'INSERT INTO users(name,email,password,phone_number) VALUES($1,$2,$3,$4) RETURNING id,name,email',
[name, email.toLowerCase(), hash, normalizePhone(phone_number)]
);
res.json({ user: result.rows[0] });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Signup failed' });
}
});
// LOGIN
app.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const result = await pool.query(
'SELECT * FROM users WHERE email=$1',
[email.toLowerCase()]
);
if (!result.rows.length)
return res.status(401).json({ error: 'Invalid credentials' });
const user = result.rows[0];
const match = await bcrypt.compare(password, user.password);
if (!match)
return res.status(401).json({ error: 'Invalid credentials' });
// Fetch assigned locations for regular users
const locResult = await pool.query(
`SELECT l.name FROM locations l
JOIN user_locations ul ON ul.location_id = l.id
WHERE ul.user_id = $1`,
[user.id]
);
const assignedLocations = locResult.rows.map((r) => r.name);
const token = jwt.sign(
{ id: user.id, name: user.name, email: user.email, role: user.role },
JWT_SECRET,
{ expiresIn: '12h' }
);
res.json({
token,
user: { id: user.id, name: user.name, email: user.email, role: user.role, assignedLocations },
});
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Login failed' });
}
});
// ================= PASSWORD RESET =================
// SEND OTP
app.post('/api/send-otp', async (req, res) => {
try {
const { email } = req.body;
if (!email) {
return res.status(400).json({ success: false, message: 'Email is required' });
}
// Check if user exists
const result = await pool.query(
'SELECT id FROM users WHERE email=$1',
[email.toLowerCase()]
);
if (!result.rows.length) {
return res.status(404).json({ success: false, message: 'Email not registered' });
}
// Generate OTP
const otp = generateOtp();
otpStore[email.toLowerCase()] = {
otp,
timestamp: Date.now(),
};
// Send email
await sendOtpEmail(email, otp);
console.log(`✅ OTP sent to ${email}: ${otp}`);
res.json({
success: true,
message: 'OTP sent to your email successfully',
});
} catch (error) {
console.error('❌ Error sending OTP:', error);
res.status(500).json({
success: false,
message: 'Failed to send OTP',
error: error.message,
});
}
});
// VERIFY OTP
app.post('/api/verify-otp', (req, res) => {
try {
const { email, otp } = req.body;
if (!email || !otp) {
return res.status(400).json({ success: false, message: 'Email and OTP required' });
}
const storedData = otpStore[email.toLowerCase()];
if (!storedData) {
return res.status(400).json({ success: false, message: 'No OTP request found' });
}
// Check if OTP expired (10 minutes)
if (Date.now() - storedData.timestamp > 10 * 60 * 1000) {
delete otpStore[email.toLowerCase()];
return res.status(400).json({ success: false, message: 'OTP expired' });
}
// Verify OTP
if (storedData.otp !== otp) {
return res.status(400).json({ success: false, message: 'Invalid OTP' });
}
// OTP verified successfully
delete otpStore[email.toLowerCase()];
res.json({
success: true,
message: 'OTP verified successfully',
});
} catch (error) {
console.error('❌ Error verifying OTP:', error);
res.status(500).json({
success: false,
message: 'Verification failed',
error: error.message,
});
}
});
// RESET PASSWORD
app.post('/api/reset-password', async (req, res) => {
try {
const { email, newPassword } = req.body;
if (!email || !newPassword) {
return res.status(400).json({ success: false, message: 'Email and password required' });
}
// Check if user exists
const result = await pool.query(
'SELECT id FROM users WHERE email=$1',
[email.toLowerCase()]
);
if (!result.rows.length) {
return res.status(404).json({ success: false, message: 'User not found' });
}
// Hash new password
const hash = await bcrypt.hash(newPassword, 10);
// Update password in database
await pool.query(
'UPDATE users SET password=$1 WHERE email=$2',
[hash, email.toLowerCase()]
);
console.log(`✅ Password reset for ${email}`);
res.json({
success: true,
message: 'Password reset successfully',
});
} catch (error) {
console.error('❌ Error resetting password:', error);
res.status(500).json({
success: false,
message: 'Password reset failed',
error: error.message,
});
}
});
// ================= VISITORS =================
app.get('/visitors/next-id', authenticate, async (req, res) => {
try {
const r = await pool.query('SELECT COALESCE(MAX(id), 0) + 1 AS n FROM visitors');
const num = String(r.rows[0].n).padStart(4, '0');
res.json({ visitorId: `BCNMV-${num}` });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch next ID' });
}
});
app.post('/visitor', async (req, res) => {
try {
const {
date,
in_time,
name,
coming_from,
company,
location,
phone_number,
purpose,
person_to_meet,
scheduled,
out_time,
photo,
} = req.body;
// Validation for mandatory fields
if (!date) return res.status(400).json({ error: 'Date is required' });
if (!in_time) return res.status(400).json({ error: 'In time is required' });
if (!name) return res.status(400).json({ error: 'Visitor name is required' });
if (!coming_from) return res.status(400).json({ error: 'Coming from is required' });
if (!company) return res.status(400).json({ error: 'Company is required' });
if (!phone_number) return res.status(400).json({ error: 'Phone number is required' });
if (!purpose) return res.status(400).json({ error: 'Purpose is required' });
if (!person_to_meet) return res.status(400).json({ error: 'Person to meet is required' });
if (!scheduled) return res.status(400).json({ error: 'Scheduled status is required' });
if (!location) return res.status(400).json({ error: 'Location is required' });
if (!photo) return res.status(400).json({ error: 'Photo is required' });
const insertResult = await pool.query(
`INSERT INTO visitors
(date, in_time, name, coming_from, company, location, phone_number, purpose, person_to_meet, scheduled, out_time, photo)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
RETURNING *`,
[date, in_time, name, coming_from, company, location, phone_number, purpose, person_to_meet, scheduled, out_time || null, photo]
);
const row = insertResult.rows[0];
const visitorId = `BCNMV-${String(row.id).padStart(4, '0')}`;
await pool.query('UPDATE visitors SET visitor_id = $1 WHERE id = $2', [visitorId, row.id]);
row.visitor_id = visitorId;
res.json(row);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to add visitor' });
}
});
app.get('/visitors', authenticate, async (req, res) => {
try {
let result;
if (req.user.role === 'admin') {
result = await pool.query('SELECT * FROM visitors ORDER BY id DESC');
} else {
const locResult = await pool.query(
`SELECT l.name FROM locations l JOIN user_locations ul ON ul.location_id = l.id WHERE ul.user_id = $1`,
[req.user.id]
);
const locs = locResult.rows.map((r) => r.name);
if (locs.length === 0) return res.json([]);
result = await pool.query(
'SELECT * FROM visitors WHERE location = ANY($1) ORDER BY id DESC',
[locs]
);
}
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch visitors' });
}
});
app.delete('/visitors/:id', authenticate, async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query(
'DELETE FROM visitors WHERE id=$1 RETURNING id',
[id]
);
if (result.rows.length === 0)
return res.status(404).json({ error: 'Visitor not found' });
res.json({ message: 'Visitor deleted successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to delete visitor' });
}
});
app.patch('/visitors/:id/out-time', authenticate, async (req, res) => {
try {
const { id } = req.params;
const { out_time } = req.body;
if (!out_time) return res.status(400).json({ error: 'out_time is required' });
const result = await pool.query(
'UPDATE visitors SET out_time = $1 WHERE id = $2 RETURNING id, out_time',
[out_time, id]
);
if (result.rows.length === 0) return res.status(404).json({ error: 'Visitor not found' });
res.json(result.rows[0]);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to update out time' });
}
});
// ================= CONSIGNMENTS =================
app.get('/consignments/next-gp', authenticate, async (req, res) => {
try {
const r = await pool.query('SELECT COALESCE(MAX(id), 0) + 1 AS n FROM consignments');
const num = String(r.rows[0].n).padStart(4, '0');
res.json({ gpNumber: `BCNM-${num}` });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch next GP number' });
}
});
app.post('/consignment', async (req, res) => {
try {
const {
date,
type,
document_number,
document_type,
in_time,
vehicle_number,
driver_contact,
qty,
package_type,
comment,
photo,
security_name,
location,
} = req.body;
// Validation for mandatory fields
if (!date) return res.status(400).json({ error: 'Date is required' });
if (!type) return res.status(400).json({ error: 'Type is required' });
if (!document_number) return res.status(400).json({ error: 'Document Number is required' });
if (!document_type) return res.status(400).json({ error: 'Document Type is required' });
if (!in_time) return res.status(400).json({ error: 'In-Time is required' });
if (!vehicle_number) return res.status(400).json({ error: 'Vehicle Number is required' });
if (!driver_contact) return res.status(400).json({ error: 'Driver Contact is required' });
if (!qty) return res.status(400).json({ error: 'Qty is required' });
if (!package_type) return res.status(400).json({ error: 'Package Type is required' });
if (!comment) return res.status(400).json({ error: 'Comment is required' });
if (!photo) return res.status(400).json({ error: 'Photo is required' });
if (!security_name) return res.status(400).json({ error: 'Security Name is required' });
const insertResult = await pool.query(
`INSERT INTO consignments
(date, type, document_number, document_type, in_time, vehicle_number, driver_contact, qty, package_type, comment, photo, security_name, location)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
RETURNING *`,
[date, type, document_number, document_type, in_time, vehicle_number, driver_contact, qty, package_type, comment, photo, security_name, location || null]
);
const row = insertResult.rows[0];
const gpNumber = `BCNM-${String(row.id).padStart(4, '0')}`;
await pool.query('UPDATE consignments SET gp_number = $1 WHERE id = $2', [gpNumber, row.id]);
row.gp_number = gpNumber;
res.json(row);
} catch (err) {
console.error("CONS ERROR:", err);
res.status(500).json({ error: 'Failed to add consignment' });
}
});
app.get('/consignments', authenticate, async (req, res) => {
try {
let result;
if (req.user.role === 'admin') {
result = await pool.query('SELECT * FROM consignments ORDER BY id DESC');
} else {
const locResult = await pool.query(
`SELECT l.name FROM locations l JOIN user_locations ul ON ul.location_id = l.id WHERE ul.user_id = $1`,
[req.user.id]
);
const locs = locResult.rows.map((r) => r.name);
if (locs.length === 0) return res.json([]);
result = await pool.query(
'SELECT * FROM consignments WHERE location = ANY($1) ORDER BY id DESC',
[locs]
);
}
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch consignments' });
}
});
app.delete('/consignments/:id', authenticate, async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query(
'DELETE FROM consignments WHERE id=$1 RETURNING id',
[id]
);
if (result.rows.length === 0)
return res.status(404).json({ error: 'Consignment not found' });
res.json({ message: 'Consignment deleted successfully' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to delete consignment' });
}
});
// ================= LOCATIONS (Admin) =================
app.get('/admin/locations', authenticate, requireAdmin, async (req, res) => {
try {
const result = await pool.query('SELECT * FROM locations ORDER BY name ASC');
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch locations' });
}
});
app.post('/admin/locations', authenticate, requireAdmin, async (req, res) => {
try {
const { name } = req.body;
if (!name || !name.trim()) return res.status(400).json({ error: 'Location name is required' });
const result = await pool.query('INSERT INTO locations (name) VALUES ($1) RETURNING *', [name.trim()]);
res.status(201).json({ message: 'Location created', location: result.rows[0] });
} catch (err) {
if (err.code === '23505') return res.status(409).json({ error: 'Location already exists' });
res.status(500).json({ error: 'Failed to create location' });
}
});
app.delete('/admin/locations/:id', authenticate, requireAdmin, async (req, res) => {
try {
const id = Number(req.params.id);
const result = await pool.query('DELETE FROM locations WHERE id = $1 RETURNING *', [id]);
if (result.rowCount === 0) return res.status(404).json({ error: 'Location not found' });
res.json({ message: 'Location deleted' });
} catch (err) {
res.status(500).json({ error: 'Failed to delete location' });
}
});
// ================= USERS (Admin) =================
app.get('/admin/users', authenticate, requireAdmin, async (req, res) => {
try {
const result = await pool.query(
`SELECT u.id, u.name, u.email, u.role, u.created_at,
COALESCE(json_agg(json_build_object('id', l.id, 'name', l.name)) FILTER (WHERE l.id IS NOT NULL), '[]') AS locations
FROM users u
LEFT JOIN user_locations ul ON ul.user_id = u.id
LEFT JOIN locations l ON l.id = ul.location_id
GROUP BY u.id ORDER BY u.created_at DESC`
);
res.json(result.rows);
} catch (err) {
res.status(500).json({ error: 'Failed to fetch users' });
}
});
app.post('/admin/users', authenticate, requireAdmin, async (req, res) => {
try {
const { name, email, password, phone_number, role, locationIds } = req.body;
if (!name || !email || !password) return res.status(400).json({ error: 'Name, email, and password are required' });
const userRole = ['admin', 'user'].includes(role) ? role : 'user';
const existing = await pool.query('SELECT id FROM users WHERE email = $1', [email.toLowerCase()]);
if (existing.rows.length > 0) return res.status(409).json({ error: 'User already exists' });
const hashedPassword = await bcrypt.hash(password, 10);
const normalizedPhone = phone_number ? normalizePhone(phone_number) : null;
const userResult = await pool.query(
'INSERT INTO users (name, email, password, phone_number, role) VALUES ($1, $2, $3, $4, $5) RETURNING id, name, email, role',
[name, email.toLowerCase(), hashedPassword, normalizedPhone, userRole]
);
const newUserId = userResult.rows[0].id;
if (Array.isArray(locationIds) && locationIds.length > 0 && userRole === 'user') {
for (const locId of locationIds) {
await pool.query('INSERT INTO user_locations (user_id, location_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [newUserId, locId]);
}
}
res.status(201).json({ message: 'User created', user: userResult.rows[0] });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to create user' });
}
});
app.delete('/admin/users/:id', authenticate, requireAdmin, async (req, res) => {
try {
const id = Number(req.params.id);
if (id === req.user.id) return res.status(400).json({ error: 'Cannot delete your own admin account' });
const result = await pool.query('DELETE FROM users WHERE id = $1 RETURNING *', [id]);
if (result.rowCount === 0) return res.status(404).json({ error: 'User not found' });
res.json({ message: 'User deleted' });
} catch (err) {
res.status(500).json({ error: 'Failed to delete user' });
}
});
app.put('/admin/users/:id/locations', authenticate, requireAdmin, async (req, res) => {
try {
const userId = Number(req.params.id);
const { locationIds } = req.body;
if (!Array.isArray(locationIds)) return res.status(400).json({ error: 'locationIds must be an array' });
await pool.query('DELETE FROM user_locations WHERE user_id = $1', [userId]);
for (const locId of locationIds) {
await pool.query('INSERT INTO user_locations (user_id, location_id) VALUES ($1, $2) ON CONFLICT DO NOTHING', [userId, locId]);
}
res.json({ message: 'Locations updated' });
} catch (err) {
res.status(500).json({ error: 'Failed to update locations' });
}
});
// ================= DROPDOWN OPTIONS =================
app.get('/dropdown-options', authenticate, async (req, res) => {
try {
const { category } = req.query;
const result = category
? await pool.query('SELECT id, value FROM dropdown_options WHERE category = $1 ORDER BY value ASC', [category])
: await pool.query('SELECT id, category, value FROM dropdown_options ORDER BY category, value ASC');
res.json(result.rows);
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to fetch dropdown options' });
}
});
app.post('/admin/dropdown-options', authenticate, requireAdmin, async (req, res) => {
try {
const { category, value } = req.body;
if (!category || !value || !value.trim()) return res.status(400).json({ error: 'Category and value are required' });
const result = await pool.query(
'INSERT INTO dropdown_options (category, value) VALUES ($1, $2) RETURNING *',
[category, value.trim()]
);
res.status(201).json(result.rows[0]);
} catch (err) {
if (err.code === '23505') return res.status(409).json({ error: 'Option already exists' });
if (err.code === '23514') return res.status(400).json({ error: 'Invalid category. Use: purpose, person_to_meet, or security_name' });
console.error(err);
res.status(500).json({ error: 'Failed to create option' });
}
});
app.delete('/admin/dropdown-options/:id', authenticate, requireAdmin, async (req, res) => {
try {
const id = Number(req.params.id);
if (isNaN(id)) return res.status(400).json({ error: 'Invalid ID' });
const result = await pool.query('DELETE FROM dropdown_options WHERE id = $1 RETURNING *', [id]);
if (result.rowCount === 0) return res.status(404).json({ error: 'Option not found' });
res.json({ message: 'Option deleted' });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'Failed to delete option' });
}
});
// ================= REPORTS =================
// GET VISITORS REPORT BY DATE RANGE
app.get('/reports/visitors', async (req, res) => {
try {
const { startDate, endDate } = req.query;
if (!startDate || !endDate) {
return res.status(400).json({ error: 'Start date and end date are required' });
}
console.log(`📊 Fetching visitors from ${startDate} to ${endDate}`);
const result = await pool.query(
`SELECT id, date, visitor_id, name, coming_from, company, location,
phone_number, purpose, person_to_meet, scheduled, out_time, photo
FROM visitors
WHERE DATE(date) BETWEEN $1::DATE AND $2::DATE
ORDER BY date DESC`,
[startDate, endDate]
);
// Convert photos to base64 if they're buffers
const rows = result.rows.map(row => {
if (row.photo) {
try {
// If photo is a Buffer, convert to base64
if (Buffer.isBuffer(row.photo)) {
console.log(`Converting Buffer photo of size: ${row.photo.length}`);
row.photo = 'data:image/jpeg;base64,' + row.photo.toString('base64');
}
// If it's already a string, check if it needs the prefix
else if (typeof row.photo === 'string' && !row.photo.includes('data:image')) {
row.photo = 'data:image/jpeg;base64,' + row.photo;
}
} catch (photoErr) {
console.warn(`Failed to convert photo for visitor ${row.id}:`, photoErr.message);
row.photo = null;
}
}
return row;
});
console.log(`✅ Found ${result.rows.length} visitor records`);
res.json(rows);
} catch (err) {
console.error('❌ Visitor report error:', err);
res.status(500).json({ error: 'Failed to fetch visitor report', details: err.message });
}
});
// GET CONSIGNMENTS REPORT BY DATE RANGE
app.get('/reports/consignments', async (req, res) => {
try {
const { startDate, endDate } = req.query;
if (!startDate || !endDate) {
return res.status(400).json({ error: 'Start date and end date are required' });
}
console.log(`📊 Fetching consignments from ${startDate} to ${endDate}`);
const result = await pool.query(
`SELECT id, date, gp_number, type, document_number, document_type,
in_time, vehicle_number, driver_contact, qty, package_type,
comment, security_name, photo
FROM consignments
WHERE DATE(date) BETWEEN $1::DATE AND $2::DATE
ORDER BY date DESC`,
[startDate, endDate]
);
// Convert photos to base64 if they're buffers
const rows = result.rows.map(row => {
if (row.photo) {
try {
// If photo is a Buffer, convert to base64
if (Buffer.isBuffer(row.photo)) {
console.log(`Converting Buffer photo of size: ${row.photo.length}`);
row.photo = 'data:image/jpeg;base64,' + row.photo.toString('base64');
}
// If it's already a string, check if it needs the prefix
else if (typeof row.photo === 'string' && !row.photo.includes('data:image')) {
row.photo = 'data:image/jpeg;base64,' + row.photo;
}
} catch (photoErr) {
console.warn(`Failed to convert photo for consignment ${row.id}:`, photoErr.message);
row.photo = null;
}
}
return row;
});
console.log(`✅ Found ${result.rows.length} consignment records`);
res.json(rows);
} catch (err) {
console.error('❌ Consignment report error:', err);
res.status(500).json({ error: 'Failed to fetch consignment report', details: err.message });
}
});
// ================= 404 =================
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// ================= START =================
app.listen(PORT, () => {
console.log(`🚀 Server running on http://localhost:${PORT}`);
console.log(`📧 Email configured: ${process.env.SMTP_USER}`);
});