server.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const express = require('express');
  2. const sqlite3 = require('sqlite3').verbose();
  3. const cors = require('cors');
  4. const app = express();
  5. const port = 3001;
  6. app.use(cors());
  7. app.use(express.json());
  8. const db = new sqlite3.Database('./attendance.db', (err) => {
  9. if (err) {
  10. console.error(err.message);
  11. }
  12. console.log('Connected to the attendance database.');
  13. });
  14. db.run(`CREATE TABLE IF NOT EXISTS attendance (
  15. id INTEGER PRIMARY KEY AUTOINCREMENT,
  16. employee_id TEXT,
  17. check_in DATETIME,
  18. check_out DATETIME
  19. )`);
  20. app.post('/check-in', (req, res) => {
  21. const { employee_id } = req.body;
  22. const check_in = new Date().toISOString();
  23. db.run(`INSERT INTO attendance (employee_id, check_in) VALUES (?, ?)`, [employee_id, check_in], function(err) {
  24. if (err) {
  25. return res.status(500).json({ error: err.message });
  26. }
  27. res.json({ id: this.lastID, employee_id, check_in });
  28. });
  29. });
  30. app.post('/check-out', (req, res) => {
  31. const { employee_id } = req.body;
  32. const check_out = new Date().toISOString();
  33. db.run(`UPDATE attendance SET check_out = ? WHERE employee_id = ? AND check_out IS NULL`, [check_out, employee_id], function(err) {
  34. if (err) {
  35. return res.status(500).json({ error: err.message });
  36. }
  37. res.json({ employee_id, check_out });
  38. });
  39. });
  40. app.get('/attendance/:employee_id', (req, res) => {
  41. const { employee_id } = req.params;
  42. db.all(`SELECT * FROM attendance WHERE employee_id = ? ORDER BY check_in DESC LIMIT 7`, [employee_id], (err, rows) => {
  43. if (err) {
  44. return res.status(500).json({ error: err.message });
  45. }
  46. res.json(rows);
  47. });
  48. });
  49. app.get('/report/:employee_id', (req, res) => {
  50. const { employee_id } = req.params;
  51. db.all(`SELECT * FROM attendance WHERE employee_id = ? AND check_in >= date('now', '-7 days')`, [employee_id], (err, rows) => {
  52. if (err) {
  53. return res.status(500).json({ error: err.message });
  54. }
  55. const report = rows.reduce((acc, row) => {
  56. if (row.check_in && row.check_out) {
  57. const duration = new Date(row.check_out) - new Date(row.check_in);
  58. acc.total_hours += duration / (1000 * 60 * 60);
  59. acc.days_worked += 1;
  60. }
  61. return acc;
  62. }, { total_hours: 0, days_worked: 0 });
  63. res.json(report);
  64. });
  65. });
  66. app.listen(port, () => {
  67. console.log(`Server running at http://localhost:${port}`);
  68. });