Update server.js
This commit is contained in:
@@ -913,7 +913,7 @@ app.put('/api/expenses/:id', authenticateToken, requireAdmin, async (req, res) =
|
||||
// Get current DB shares to delete removed ones
|
||||
const [currentDbShares] = await connection.query('SELECT family_id FROM expense_shares WHERE expense_id = ?', [expenseId]);
|
||||
const currentFamilyIds = currentDbShares.map(s => s.family_id);
|
||||
const newFamilyIds = shares.map(s => s.familyId);
|
||||
const newFamilyIds = shares.map(s => s.family_id);
|
||||
|
||||
// A. Delete shares for families removed from list
|
||||
const toDelete = currentFamilyIds.filter(fid => !newFamilyIds.includes(fid));
|
||||
@@ -985,16 +985,27 @@ app.get('/api/expenses/:id/attachments/:attachmentId', authenticateToken, async
|
||||
});
|
||||
|
||||
app.post('/api/expenses/:id/pay', authenticateToken, async (req, res) => {
|
||||
const { amount, notes } = req.body;
|
||||
const { amount, notes, familyId: bodyFamilyId } = req.body;
|
||||
const expenseId = req.params.id;
|
||||
const userId = req.user.id;
|
||||
const connection = await pool.getConnection();
|
||||
|
||||
try {
|
||||
let familyId;
|
||||
|
||||
// Admin override logic: If familyId provided in body and user is admin, use it.
|
||||
// Otherwise, use logged-in user's family.
|
||||
if (bodyFamilyId) {
|
||||
if (req.user.role === 'admin' || req.user.role === 'poweruser') {
|
||||
familyId = bodyFamilyId;
|
||||
} else {
|
||||
return res.status(403).json({ message: 'Permission denied to pay for others' });
|
||||
}
|
||||
} else {
|
||||
// Find user's family
|
||||
const [users] = await connection.query('SELECT family_id FROM users WHERE id = ?', [userId]);
|
||||
const [users] = await connection.query('SELECT family_id FROM users WHERE id = ?', [req.user.id]);
|
||||
if (users.length === 0 || !users[0].family_id) return res.status(400).json({ message: 'User has no family assigned' });
|
||||
const familyId = users[0].family_id;
|
||||
familyId = users[0].family_id;
|
||||
}
|
||||
|
||||
// Find share
|
||||
const [shares] = await connection.query('SELECT * FROM expense_shares WHERE expense_id = ? AND family_id = ?', [expenseId, familyId]);
|
||||
@@ -1016,7 +1027,7 @@ app.post('/api/expenses/:id/pay', authenticateToken, async (req, res) => {
|
||||
// We use a special month/year or notes to distinguish
|
||||
await connection.query(
|
||||
'INSERT INTO payments (id, family_id, amount, date_paid, for_month, for_year, notes) VALUES (?, ?, ?, NOW(), 13, YEAR(NOW()), ?)',
|
||||
[uuidv4(), familyId, amount, `Spesa Straordinaria: ${notes || 'PayPal'}`]
|
||||
[uuidv4(), familyId, amount, `Spesa Straordinaria: ${notes || 'Pagamento Manuale'}`]
|
||||
);
|
||||
|
||||
await connection.commit();
|
||||
|
||||
Reference in New Issue
Block a user