Spaces:
Sleeping
Sleeping
File size: 7,032 Bytes
7e85d34 83f4356 13c80ac 83f4356 55ffa7e 83f4356 55ffa7e 83f4356 | 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | const { supabaseServiceRole: supabaseAdmin } = require('../config/supabase');
const { success, error, notFound, serverError } = require('../utils/response');
const { parsePagination } = require('../utils/pagination');
/**
* GET /api/admin/ngos — list NGOs with optional status filter
*/
async function listNgos(req, res) {
try {
const { page, limit, offset } = parsePagination(req.query);
const statusFilter = req.query.status; // 'pending', 'approved', 'rejected', 'suspended'
let query = supabaseAdmin
.from('ngo_profiles')
.select('*, profiles!ngo_profiles_id_fkey(username, display_name, email, phone, is_banned, created_at)', { count: 'exact' });
if (statusFilter) {
query = query.eq('status', statusFilter);
}
const { data, error: dbError, count } = await query
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1);
if (dbError) return error(res, dbError.message, 400);
return success(res, data, { page, limit, total: count });
} catch (err) {
console.error('listNgos error:', err);
return serverError(res);
}
}
/**
* PATCH /api/admin/ngos/:ngoId/approve
*/
async function approveNgo(req, res) {
try {
const { ngoId } = req.params;
const { data, error: dbError } = await supabaseAdmin
.from('ngo_profiles')
.update({
status: 'approved',
approved_by: req.user.id,
approved_at: new Date().toISOString(),
})
.eq('id', ngoId)
.eq('status', 'pending')
.select()
.single();
if (dbError || !data) return notFound(res, 'NGO not found or not in pending status');
// Elevate user's profile role to 'ngo' in the profiles table
const { error: profileError } = await supabaseAdmin
.from('profiles')
.update({ role: 'ngo' })
.eq('id', ngoId);
if (profileError) {
console.error('Failed to update profile role for NGO:', profileError);
// Attempt rollback of NGO approval status
await supabaseAdmin
.from('ngo_profiles')
.update({ status: 'pending', approved_by: null, approved_at: null })
.eq('id', ngoId);
return serverError(res, 'Failed to update user profile role to NGO');
}
return success(res, { ngo_id: ngoId, status: 'approved', approved_at: data.approved_at });
} catch (err) {
console.error('approveNgo error:', err);
return serverError(res);
}
}
/**
* PATCH /api/admin/ngos/:ngoId/reject
*/
async function rejectNgo(req, res) {
try {
const { ngoId } = req.params;
const { reason } = req.body;
const { data, error: dbError } = await supabaseAdmin
.from('ngo_profiles')
.update({ status: 'rejected' })
.eq('id', ngoId)
.eq('status', 'pending')
.select()
.single();
if (dbError || !data) return notFound(res, 'NGO not found or not in pending status');
return success(res, { ngo_id: ngoId, status: 'rejected', reason });
} catch (err) {
console.error('rejectNgo error:', err);
return serverError(res);
}
}
/**
* GET /api/admin/users — list all users
*/
async function listUsers(req, res) {
try {
const { page, limit, offset } = parsePagination(req.query);
const roleFilter = req.query.role;
let query = supabaseAdmin
.from('profiles')
.select('*', { count: 'exact' });
if (roleFilter) query = query.eq('role', roleFilter);
const { data, error: dbError, count } = await query
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1);
if (dbError) return error(res, dbError.message, 400);
return success(res, data, { page, limit, total: count });
} catch (err) {
console.error('listUsers error:', err);
return serverError(res);
}
}
/**
* PATCH /api/admin/users/:userId/ban
*/
async function banUser(req, res) {
try {
const { userId } = req.params;
const { reason } = req.body;
const { data, error: dbError } = await supabaseAdmin
.from('profiles')
.update({ is_banned: true, banned_reason: reason || 'Violation of terms' })
.eq('id', userId)
.neq('role', 'admin') // can't ban admins
.select()
.single();
if (dbError || !data) return notFound(res, 'User not found or is an admin');
// If NGO, also suspend their ngo_profile
if (data.role === 'ngo') {
await supabaseAdmin
.from('ngo_profiles')
.update({ status: 'suspended' })
.eq('id', userId);
}
return success(res, { user_id: userId, is_banned: true, reason });
} catch (err) {
console.error('banUser error:', err);
return serverError(res);
}
}
/**
* PATCH /api/admin/users/:userId/unban
*/
async function unbanUser(req, res) {
try {
const { userId } = req.params;
const { data, error: dbError } = await supabaseAdmin
.from('profiles')
.update({ is_banned: false, banned_reason: null })
.eq('id', userId)
.select()
.single();
if (dbError || !data) return notFound(res, 'User not found');
// If NGO, lift the suspension the ban applied (and nothing else)
if (data.role === 'ngo') {
await supabaseAdmin
.from('ngo_profiles')
.update({ status: 'approved' })
.eq('id', userId)
.eq('status', 'suspended');
}
return success(res, { user_id: userId, is_banned: false });
} catch (err) {
console.error('unbanUser error:', err);
return serverError(res);
}
}
/**
* GET /api/admin/dashboard — platform-wide stats for admin dashboard
*/
async function platformStats(req, res) {
try {
const [
adopters,
ngos,
plants,
adoptions,
posts,
reports,
users
] = await Promise.all([
supabaseAdmin.from('profiles').select('id', { count: 'exact', head: true }).eq('role', 'adopter'),
supabaseAdmin.from('ngo_profiles').select('id', { count: 'exact', head: true }).eq('status', 'approved'),
supabaseAdmin.from('plants').select('id', { count: 'exact', head: true }),
supabaseAdmin.from('adoptions').select('id', { count: 'exact', head: true }).eq('status', 'approved'),
supabaseAdmin.from('posts').select('id', { count: 'exact', head: true }),
supabaseAdmin.from('growth_reports').select('id', { count: 'exact', head: true }),
supabaseAdmin.from('profiles').select('id', { count: 'exact', head: true }),
]);
return success(res, {
total_adopters: adopters.count || 0,
total_approved_ngos: ngos.count || 0,
total_plants: plants.count || 0,
total_adoptions: adoptions.count || 0,
total_posts: posts.count || 0,
total_reports: reports.count || 0,
total_users: users.count || 0,
total_ngos: ngos.count || 0, // Legacy support for different keys
});
} catch (err) {
console.error('platformStats error:', err);
return serverError(res);
}
}
module.exports = { listNgos, approveNgo, rejectNgo, listUsers, banUser, unbanUser, platformStats };
|