Scheduled Jobs
Background cron jobs that run on a schedule — fine calculation, overdue detection, and automated notifications.
Scheduled Jobs
The SLMS backend runs background cron jobs using the node-cron library. These jobs automate recurring tasks like fine calculation and overdue detection without manual intervention.
Directory
All scheduled job modules live in backend/jobs/.
| File | Schedule | Description |
|---|---|---|
fineCalculator.js | Daily at midnight (0 0 * * *) | Calculates and upserts fines for overdue transactions |
Fine Calculator
File: backend/jobs/fineCalculator.js
Purpose
Automatically detects overdue book loans and creates or updates fine records. Runs daily at midnight UTC.
Schedule
0 0 * * * (Every day at 00:00)Algorithm
1. Fetch the dynamic fine rate from SystemConfig (key: FINE_RATE_PER_DAY)
└─ Default: $1.00/day if not configured
2. Query all active transactions where:
└─ returnedAt === null AND dueDate < now
3. For each overdue transaction:
a. Calculate days overdue = ceil((now - dueDate) / 1 day)
b. Calculate fine amount = daysOverdue × fineRate
c. If an UNPAID fine already exists for this transaction:
└─ Update the amount (fines grow daily)
d. If no UNPAID fine exists:
└─ Create a new Fine record
└─ Create a WARNING notification to the user:
"An overdue fine of $X has been generated..."
4. Log the number of processed transactionsDynamic Fine Rate
The fine rate per day is read from the SystemConfig collection at runtime:
const config = await SystemConfig.findOne({ key: 'FINE_RATE_PER_DAY' });
const fineRate = config ? Number(config.value) : 1.0;This allows admins to adjust fine rates through the System Config API without restarting the server.
Error Handling
If the cron job fails, it:
- Logs the error to console
- Creates an audit log entry with action
SECURITY_EVENTand statusFAILURE - Does not crash the server — errors are caught and contained
Initialization
The cron job is started in backend/src/app.js:
const { startFineCronJob } = require('../jobs/fineCalculator');
startFineCronJob();Database Dependencies
| Model | Usage |
|---|---|
Transaction | Queried for overdue loans (returnedAt: null, dueDate < now) |
Fine | Created or updated with calculated amounts |
Notification | Created to alert users of new fines |
SystemConfig | Read for dynamic fine rate |
Testing
You can manually trigger the fine calculation without waiting for the cron schedule:
const { calculateOverdueFines } = require('./jobs/fineCalculator');
await calculateOverdueFines();