Spaces:
Paused
Paused
File size: 2,703 Bytes
8e71870 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | /**
* Complaint Controller - Admin Resolution of User Issues (PostgreSQL)
*/
const { getPool } = require('../db');
const { eventBus, EVENTS } = require('../services/eventBus');
/**
* List all complaints in the system
*/
async function list(req, res) {
const { status, limit = 50, offset = 0 } = req.query;
const pool = getPool();
if (!pool) return res.status(500).json({ error: 'Database not connected' });
try {
let query = 'SELECT c.*, u.name as user_name FROM complaints c JOIN users u ON c.user_id = u.id WHERE 1=1';
const params = [];
let paramCounter = 1;
if (status) {
query += ` AND c.status = $${paramCounter++}`;
params.push(status);
}
query += ` ORDER BY c.created_at DESC LIMIT $${paramCounter++} OFFSET $${paramCounter++}`;
params.push(parseInt(limit), parseInt(offset));
const result = await pool.query(query, params);
res.json({ success: true, count: result.rows.length, data: result.rows });
} catch (error) {
console.error('[Complaint List Error]', error.message);
res.status(500).json({ error: 'Failed to fetch complaints' });
}
}
/**
* Get complaint by ID
*/
async function show(req, res) {
const { id } = req.params;
const pool = getPool();
if (!pool) return res.status(500).json({ error: 'Database not connected' });
try {
const query = 'SELECT c.*, u.name as user_name, u.email as user_email FROM complaints c JOIN users u ON c.user_id = u.id WHERE c.id = $1';
const result = await pool.query(query, [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Complaint not found' });
}
res.json({ success: true, data: result.rows[0] });
} catch (error) {
console.error('[Complaint Get Error]', error.message);
res.status(500).json({ error: 'Failed to fetch complaint' });
}
}
/**
* Update complaint status (Resolve)
*/
async function update(req, res) {
const { id } = req.params;
const { status, resolution } = req.body;
const pool = getPool();
if (!pool) return res.status(500).json({ error: 'Database not connected' });
try {
const query = 'UPDATE complaints SET status = $2, resolution = $3, updated_at = NOW() WHERE id = $1';
await pool.query(query, [id, status, resolution || '']);
if (status === 'resolved') {
eventBus.emit(EVENTS.COMPLAINT_RESOLVED, { complaint_id: id });
}
res.json({ success: true, message: `Complaint status updated to ${status}` });
} catch (error) {
console.error('[Complaint Update Error]', error.message);
res.status(500).json({ error: 'Failed to update complaint' });
}
}
module.exports = { list, show, update };
|