enterprise_assest_managemen.../node_api/routes/jobs.js

271 lines
7.2 KiB
JavaScript

// node_api/routes/jobs.js
const express = require('express');
const { jobManager } = require('../services/jobManager');
const { DepreciationJob } = require('../jobs/depreciationJob');
const { DepreciationDatabase } = require('../jobs/depreciationDatabase');
const { logger } = require('../utils/logger');
const router = express.Router();
/**
* Get job manager status and all job statuses
*/
router.get('/status', async (req, res) => {
try {
const status = jobManager.getJobStatuses();
res.json(status);
} catch (error) {
logger.error('Error getting job status:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Get job manager health check
*/
router.get('/health', async (req, res) => {
try {
const health = await jobManager.healthCheck();
const statusCode = health.status === 'healthy' ? 200 :
health.status === 'degraded' ? 206 : 500;
res.status(statusCode).json(health);
} catch (error) {
logger.error('Error getting job health:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Run a job manually
*/
router.post('/run/:jobName', async (req, res) => {
try {
const { jobName } = req.params;
const { calculationDate } = req.body;
if (!['depreciation'].includes(jobName)) {
return res.status(400).json({ error: 'Invalid job name' });
}
const result = await jobManager.runJobManually(jobName);
res.json({
success: true,
jobName,
result
});
} catch (error) {
logger.error(`Error running job manually: ${req.params.jobName}`, error);
res.status(500).json({ error: error.message });
}
});
/**
* Get job execution history
*/
router.get('/history/:jobName', async (req, res) => {
try {
const { jobName } = req.params;
const limit = parseInt(req.query.limit) || 50;
const history = await jobManager.getJobHistory(jobName, limit);
res.json(history);
} catch (error) {
logger.error(`Error getting job history: ${req.params.jobName}`, error);
res.status(500).json({ error: error.message });
}
});
/**
* Preview depreciation calculation for an asset
*/
router.get('/depreciation/preview/:assetId', async (req, res) => {
try {
const { assetId } = req.params;
const calculationDate = req.query.date ? new Date(req.query.date) : new Date();
const job = new DepreciationJob();
const preview = await job.previewDepreciation(assetId, calculationDate);
res.json(preview);
} catch (error) {
logger.error(`Error previewing depreciation for asset: ${req.params.assetId}`, error);
res.status(500).json({ error: error.message });
}
});
/**
* Run depreciation for a specific asset
*/
router.post('/depreciation/asset/:assetId', async (req, res) => {
try {
const { assetId } = req.params;
const { calculationDate } = req.body;
const job = new DepreciationJob();
const result = await job.runForAsset(assetId, calculationDate ? new Date(calculationDate) : new Date());
res.json({
success: true,
assetId,
result
});
} catch (error) {
logger.error(`Error running depreciation for asset: ${req.params.assetId}`, error);
res.status(500).json({ error: error.message });
}
});
/**
* Get depreciation summary for a period
*/
router.get('/depreciation/summary', async (req, res) => {
try {
const startDate = req.query.startDate ? new Date(req.query.startDate) : new Date(new Date().getFullYear(), new Date().getMonth(), 1);
const endDate = req.query.endDate ? new Date(req.query.endDate) : new Date();
const database = new DepreciationDatabase();
const summary = await database.getDepreciationSummary(startDate, endDate);
res.json({
period: {
startDate: startDate.toISOString(),
endDate: endDate.toISOString()
},
summary
});
} catch (error) {
logger.error('Error getting depreciation summary:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Get monthly depreciation report
*/
router.get('/depreciation/report/:year/:month', async (req, res) => {
try {
const year = parseInt(req.params.year);
const month = parseInt(req.params.month);
if (isNaN(year) || isNaN(month) || month < 1 || month > 12) {
return res.status(400).json({ error: 'Invalid year or month' });
}
const database = new DepreciationDatabase();
const report = await database.getMonthlyDepreciationReport(year, month);
res.json({
period: { year, month },
report
});
} catch (error) {
logger.error('Error getting monthly depreciation report:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Get depreciation issues (over-depreciated assets, calculation mismatches, etc.)
*/
router.get('/depreciation/issues', async (req, res) => {
try {
const database = new DepreciationDatabase();
const issues = await database.getDepreciationIssues();
res.json({
issues,
count: issues.length
});
} catch (error) {
logger.error('Error getting depreciation issues:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Fix depreciation calculation mismatches
*/
router.post('/depreciation/fix-mismatches', async (req, res) => {
try {
const database = new DepreciationDatabase();
const fixedCount = await database.fixCalculationMismatches();
res.json({
success: true,
message: `Fixed calculation mismatches for ${fixedCount} assets`,
fixedCount
});
} catch (error) {
logger.error('Error fixing calculation mismatches:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Get depreciation records for a specific asset
*/
router.get('/depreciation/asset/:assetId/records', async (req, res) => {
try {
const { assetId } = req.params;
const limit = parseInt(req.query.limit) || 50;
const database = new DepreciationDatabase();
const client = await database.pool.connect();
try {
const query = `
SELECT *
FROM asset_depreciation_records
WHERE asset_id = $1
ORDER BY depreciation_date DESC
LIMIT $2
`;
const result = await client.query(query, [assetId, limit]);
res.json({
assetId,
records: result.rows
});
} finally {
client.release();
}
} catch (error) {
logger.error(`Error getting depreciation records for asset: ${req.params.assetId}`, error);
res.status(500).json({ error: error.message });
}
});
/**
* Start job manager (admin only)
*/
router.post('/start', async (req, res) => {
try {
await jobManager.start();
res.json({
success: true,
message: 'Job manager started successfully'
});
} catch (error) {
logger.error('Error starting job manager:', error);
res.status(500).json({ error: error.message });
}
});
/**
* Stop job manager (admin only)
*/
router.post('/stop', async (req, res) => {
try {
await jobManager.stop();
res.json({
success: true,
message: 'Job manager stopped successfully'
});
} catch (error) {
logger.error('Error stopping job manager:', error);
res.status(500).json({ error: error.message });
}
});
module.exports = router;