payments.js 4.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const express = require('express');
  2. const db = require('../db');
  3. const { authMiddleware } = require('../auth');
  4. const router = express.Router();
  5. router.use(authMiddleware);
  6. router.get('/', (req, res) => {
  7. const { lease_id } = req.query;
  8. let query = `
  9. SELECT p.*, l.rent_amount, l.charges_amount,
  10. pr.name as property_name, pr.address as property_address, pr.city as property_city,
  11. t.first_name as tenant_first_name, t.last_name as tenant_last_name
  12. FROM payments p
  13. JOIN leases l ON p.lease_id = l.id
  14. JOIN properties pr ON l.property_id = pr.id
  15. JOIN tenants t ON l.tenant_id = t.id
  16. WHERE p.user_id = ?
  17. `;
  18. const params = [req.userId];
  19. if (lease_id) { query += ' AND p.lease_id = ?'; params.push(lease_id); }
  20. query += ' ORDER BY p.period_year DESC, p.period_month DESC';
  21. res.json(db.prepare(query).all(...params));
  22. });
  23. router.post('/', (req, res) => {
  24. const { lease_id, period_month, period_year, rent_paid, charges_paid, payment_date, payment_method, notes,
  25. is_prorata, prorata_days, prorata_total_days, charge_regularization } = req.body;
  26. if (!lease_id || !period_month || !period_year || rent_paid === undefined || !payment_date)
  27. return res.status(400).json({ error: 'Champs requis manquants' });
  28. const lease = db.prepare('SELECT id FROM leases WHERE id = ? AND user_id = ?').get(lease_id, req.userId);
  29. if (!lease) return res.status(403).json({ error: 'Bail non autorisé' });
  30. const existing = db.prepare(
  31. 'SELECT id FROM payments WHERE lease_id = ? AND period_month = ? AND period_year = ?'
  32. ).get(lease_id, period_month, period_year);
  33. if (existing) return res.status(409).json({ error: 'Un paiement existe déjà pour cette période' });
  34. const regularization = parseFloat(charge_regularization || 0);
  35. const result = db.prepare(`
  36. INSERT INTO payments (lease_id, user_id, period_month, period_year, rent_paid, charges_paid, payment_date, payment_method, notes,
  37. is_prorata, prorata_days, prorata_total_days, charge_regularization)
  38. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  39. `).run(lease_id, req.userId, period_month, period_year, rent_paid, charges_paid || 0,
  40. payment_date, payment_method || 'virement', notes || null,
  41. is_prorata ? 1 : 0, prorata_days || null, prorata_total_days || null, regularization);
  42. // If a regularization was applied, mark it as used
  43. if (regularization !== 0) {
  44. db.prepare(`
  45. UPDATE charge_regularizations SET applied_payment_id = ?
  46. WHERE lease_id = ? AND applied_payment_id IS NULL
  47. ORDER BY created_at ASC LIMIT 1
  48. `).run(result.lastInsertRowid, lease_id);
  49. }
  50. res.status(201).json({ id: result.lastInsertRowid });
  51. });
  52. router.delete('/:id', (req, res) => {
  53. const payment = db.prepare('SELECT id FROM payments WHERE id = ? AND user_id = ?').get(req.params.id, req.userId);
  54. if (!payment) return res.status(404).json({ error: 'Paiement non trouvé' });
  55. db.prepare('DELETE FROM payments WHERE id = ?').run(req.params.id);
  56. res.json({ success: true });
  57. });
  58. // Pending charge regularization for a lease
  59. router.get('/regularization/:lease_id', (req, res) => {
  60. const lease = db.prepare('SELECT id FROM leases WHERE id = ? AND user_id = ?').get(req.params.lease_id, req.userId);
  61. if (!lease) return res.status(404).json({ error: 'Bail non trouvé' });
  62. const rows = db.prepare(
  63. 'SELECT * FROM charge_regularizations WHERE lease_id = ? AND applied_payment_id IS NULL ORDER BY year DESC'
  64. ).all(req.params.lease_id);
  65. const total = rows.reduce((s, r) => s + r.amount, 0);
  66. res.json({ pending: rows, total: Math.round(total * 100) / 100 });
  67. });
  68. // Dashboard stats
  69. router.get('/stats', (req, res) => {
  70. const stats = db.prepare(`
  71. SELECT
  72. COUNT(DISTINCT l.id) as active_leases,
  73. SUM(l.rent_amount + l.charges_amount) as monthly_expected,
  74. (SELECT SUM(rent_paid + charges_paid) FROM payments WHERE user_id = ? AND period_year = strftime('%Y', 'now') AND period_month = strftime('%m', 'now')) as current_month_collected
  75. FROM leases l WHERE l.user_id = ? AND l.active = 1
  76. `).get(req.userId, req.userId);
  77. res.json(stats);
  78. });
  79. module.exports = router;