File size: 1,154 Bytes
8c7b7ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const dayjs = require('dayjs');
const { GatePass, Employee, Vendor } = require('../models');

async function gateSync(req, res, next) {
  try {
    const { barcode } = req.params;

    const gatePass = await GatePass.findOne({ barcode }).sort({ created_at: -1 }).lean();
    if (!gatePass) {
      return res.status(404).json({ message: 'Pass not found' });
    }

    const employee = await Employee.findById(gatePass.employee_id, { name: 1, vendor_id: 1 }).lean();
    if (!employee) {
      return res.status(404).json({ message: 'Employee not found' });
    }

    const vendor = await Vendor.findById(employee.vendor_id, { name: 1 }).lean();

    const isExpired = dayjs(gatePass.expiry_date).isBefore(dayjs().startOf('day'));
    const status = gatePass.status === 'Active' && !isExpired
      ? 'VALID'
      : (isExpired ? 'EXPIRED' : gatePass.status);

    return res.json({
      name: employee.name,
      contractor: vendor?.name || 'N/A',
      expiry_date: gatePass.expiry_date ? dayjs(gatePass.expiry_date).format('DD/MM/YYYY') : null,
      status
    });
  } catch (error) {
    return next(error);
  }
}

module.exports = { gateSync };