108 lines
2.9 KiB
JavaScript
108 lines
2.9 KiB
JavaScript
const express = require('express');
|
|
const router = express.Router();
|
|
const AuditLog = require('../models/AuditLog');
|
|
|
|
/**
|
|
* GET /api/audit-logs
|
|
* Get audit logs with optional filtering
|
|
*
|
|
* Query parameters:
|
|
* - table: Filter by table name (e.g., 'mortality_records')
|
|
* - recordId: Filter by specific record ID
|
|
* - startDate: Filter by start date (YYYY-MM-DD)
|
|
* - endDate: Filter by end date (YYYY-MM-DD)
|
|
* - limit: Maximum number of logs to return (default: 50)
|
|
* - offset: Number of logs to skip for pagination (default: 0)
|
|
*/
|
|
router.get('/', async (req, res) => {
|
|
try {
|
|
const { table, recordId, startDate, endDate, limit = 50, offset = 0 } = req.query;
|
|
|
|
let logs;
|
|
|
|
// Filter by specific record
|
|
if (table && recordId) {
|
|
logs = await AuditLog.getByRecord(table, recordId);
|
|
}
|
|
// Filter by date range
|
|
else if (startDate && endDate) {
|
|
logs = await AuditLog.getByDateRange(
|
|
table || null,
|
|
startDate,
|
|
endDate,
|
|
parseInt(limit, 10)
|
|
);
|
|
}
|
|
// Filter by table
|
|
else if (table) {
|
|
logs = await AuditLog.getByTable(
|
|
table,
|
|
parseInt(limit, 10),
|
|
parseInt(offset, 10)
|
|
);
|
|
}
|
|
// Get recent logs across all tables
|
|
else {
|
|
logs = await AuditLog.getRecent(parseInt(limit, 10));
|
|
}
|
|
|
|
// Get total count for pagination
|
|
let totalCount = logs.length;
|
|
if (table && !recordId) {
|
|
totalCount = await AuditLog.getCount(table);
|
|
}
|
|
|
|
res.json({
|
|
success: true,
|
|
data: logs,
|
|
pagination: {
|
|
total: totalCount,
|
|
limit: parseInt(limit, 10),
|
|
offset: parseInt(offset, 10),
|
|
hasMore: totalCount > (parseInt(offset, 10) + logs.length)
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('Error fetching audit logs:', error);
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
});
|
|
|
|
/**
|
|
* GET /api/audit-logs/count
|
|
* Get count of audit logs for a table
|
|
*
|
|
* Query parameters:
|
|
* - table: Table name (required)
|
|
*/
|
|
router.get('/count', async (req, res) => {
|
|
try {
|
|
const { table } = req.query;
|
|
|
|
if (!table) {
|
|
return res.status(400).json({
|
|
success: false,
|
|
error: 'table parameter is required'
|
|
});
|
|
}
|
|
|
|
const count = await AuditLog.getCount(table);
|
|
|
|
res.json({
|
|
success: true,
|
|
count
|
|
});
|
|
} catch (error) {
|
|
console.error('Error counting audit logs:', error);
|
|
res.status(500).json({
|
|
success: false,
|
|
error: error.message
|
|
});
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|