Spaces:
Sleeping
Sleeping
Download src/controllers/ngo.controller.js from shard-c6/green-guard-api: direct link, hf CLI and curl.
- Browser
- Download file 7.81 kB
-
https://huggingface.co/spaces/shard-c6/green-guard-api/resolve/main/src/controllers/ngo.controller.js
- Command line
-
hf download hf://spaces/shard-c6/green-guard-api/src/controllers/ngo.controller.js
-
curl -L -o ngo.controller.js https://huggingface.co/spaces/shard-c6/green-guard-api/resolve/main/src/controllers/ngo.controller.js
7.81 kB
| const { supabaseAdmin, supabaseServiceRole } = require('../config/supabase'); | |
| const { success, error, serverError } = require('../utils/response'); | |
| /** | |
| * POST /api/ngo/onboarding — submit or update an organisation's application. | |
| * | |
| * Callable by any signed-in user. Status rules: | |
| * no application yet, pending, rejected → the application is (re)submitted as 'pending' | |
| * approved → details are updated, status is left alone | |
| * suspended → refused | |
| */ | |
| async function submitOnboarding(req, res) { | |
| try { | |
| const { org_name, registration_number, website, mission, address, onboarding_answers, darpan_id } = req.body; | |
| if (typeof org_name !== 'string' || org_name.trim().length === 0 || org_name.length > 200) { | |
| return error(res, 'Organisation name is required (max 200 characters)', 400, 'VALIDATION_ERROR'); | |
| } | |
| if (req.user.role === 'admin') { | |
| return error(res, 'Admin accounts cannot apply as an NGO', 400); | |
| } | |
| const { data: existing, error: lookupError } = await supabaseServiceRole | |
| .from('ngo_profiles') | |
| .select('status') | |
| .eq('id', req.user.id) | |
| .maybeSingle(); | |
| if (lookupError) { | |
| console.error('submitOnboarding lookup error:', lookupError); | |
| return serverError(res); | |
| } | |
| if (existing?.status === 'suspended') { | |
| return error(res, 'This organisation is suspended. Contact support.', 403, 'FORBIDDEN'); | |
| } | |
| const details = { | |
| id: req.user.id, | |
| org_name: org_name.trim(), | |
| registration_number: registration_number || null, | |
| website: website || null, | |
| mission: mission || null, | |
| address: address || null, | |
| onboarding_answers: onboarding_answers || null, | |
| darpan_id: darpan_id || null, | |
| }; | |
| // An approved organisation editing its details stays approved. | |
| if (existing?.status !== 'approved') { | |
| details.status = 'pending'; | |
| } | |
| const { data, error: dbError } = await supabaseServiceRole | |
| .from('ngo_profiles') | |
| .upsert(details, { onConflict: 'id' }) | |
| .select() | |
| .single(); | |
| if (dbError) return error(res, dbError.message, 400); | |
| // Also update display_name on profile | |
| const { error: nameError } = await supabaseServiceRole | |
| .from('profiles') | |
| .update({ display_name: details.org_name }) | |
| .eq('id', req.user.id); | |
| if (nameError) { | |
| console.error('submitOnboarding display_name error:', nameError); | |
| } | |
| return success(res, data); | |
| } catch (err) { | |
| console.error('submitOnboarding error:', err); | |
| return serverError(res); | |
| } | |
| } | |
| /** | |
| * GET /api/ngo/dashboard | |
| */ | |
| async function dashboard(req, res) { | |
| try { | |
| const ngoId = req.user.id; | |
| const [plantsResult, adoptionsResult, pendingResult] = await Promise.all([ | |
| supabaseAdmin.from('plants').select('id', { count: 'exact', head: true }).eq('ngo_id', ngoId), | |
| supabaseAdmin.from('adoptions').select('id', { count: 'exact', head: true }).eq('ngo_id', ngoId).eq('status', 'approved'), | |
| supabaseAdmin.from('adoptions').select('id', { count: 'exact', head: true }).eq('ngo_id', ngoId).eq('status', 'pending'), | |
| ]); | |
| return success(res, { | |
| total_plants: plantsResult.count || 0, | |
| total_adopted: adoptionsResult.count || 0, | |
| pending_applications: pendingResult.count || 0, | |
| }); | |
| } catch (err) { | |
| console.error('dashboard error:', err); | |
| return serverError(res); | |
| } | |
| } | |
| /** | |
| * GET /api/ngo/applications — list adoption applications for this NGO's plants | |
| */ | |
| async function listApplications(req, res) { | |
| try { | |
| const ngoId = req.user.id; | |
| const statusFilter = req.query.status; | |
| // Service role: applicants' contact details are not readable through the | |
| // public profile columns. Scoped to this NGO by the ngo_id filter. | |
| let query = supabaseServiceRole | |
| .from('adoptions') | |
| .select(` | |
| *, | |
| plants!inner(plant_name, species, image_urls), | |
| profiles!adoptions_adopter_id_fkey(username, display_name, email, phone) | |
| `) | |
| .eq('ngo_id', ngoId); | |
| if (statusFilter) query = query.eq('status', statusFilter); | |
| const { data, error: dbError } = await query.order('created_at', { ascending: false }); | |
| if (dbError) return error(res, dbError.message, 400); | |
| return success(res, data); | |
| } catch (err) { | |
| console.error('listApplications error:', err); | |
| return serverError(res); | |
| } | |
| } | |
| /** | |
| * GET /api/ngo/stats — data for planted/adopted graph | |
| */ | |
| async function ngoStats(req, res) { | |
| try { | |
| const ngoId = req.user.id; | |
| // Get all plants with their dates and adoption status | |
| const { data: plants, error: dbError } = await supabaseAdmin | |
| .from('plants') | |
| .select('planted_date, adoption_status, adopted_at') | |
| .eq('ngo_id', ngoId) | |
| .order('planted_date', { ascending: true }); | |
| if (dbError) return error(res, dbError.message, 400); | |
| // Group by month | |
| const monthly = {}; | |
| for (const plant of plants || []) { | |
| const month = plant.planted_date ? plant.planted_date.substring(0, 7) : 'unknown'; // YYYY-MM | |
| if (!monthly[month]) monthly[month] = { planted: 0, adopted: 0 }; | |
| monthly[month].planted++; | |
| if (plant.adoption_status === 'adopted') monthly[month].adopted++; | |
| } | |
| const chartData = Object.entries(monthly).map(([month, counts]) => ({ | |
| month, | |
| ...counts, | |
| })); | |
| return success(res, { | |
| chart: chartData, | |
| totals: { | |
| planted: plants?.length || 0, | |
| adopted: plants?.filter((p) => p.adoption_status === 'adopted').length || 0, | |
| available: plants?.filter((p) => p.adoption_status === 'available').length || 0, | |
| }, | |
| }); | |
| } catch (err) { | |
| console.error('ngoStats error:', err); | |
| return serverError(res); | |
| } | |
| } | |
| /** | |
| * GET /api/ngo/plants — this NGO's plants, each with its guardian and the | |
| * latest growth report. | |
| * | |
| * Three queries regardless of how many plants there are: the alternative the | |
| * frontend had was one report request per plant. | |
| */ | |
| async function listPlants(req, res) { | |
| try { | |
| const ngoId = req.user.id; | |
| const { data: plants, error: plantsError } = await supabaseAdmin | |
| .from('plants') | |
| .select('id, plant_name, species, image_urls, address, adoption_status, adopted_by, planted_date, created_at') | |
| .eq('ngo_id', ngoId) | |
| .order('created_at', { ascending: false }); | |
| if (plantsError) return error(res, plantsError.message, 400); | |
| if (!plants || plants.length === 0) return success(res, []); | |
| const plantIds = plants.map(p => p.id); | |
| const adopterIds = [...new Set(plants.map(p => p.adopted_by).filter(Boolean))]; | |
| const [reportsResult, adoptersResult] = await Promise.all([ | |
| supabaseAdmin | |
| .from('growth_reports') | |
| .select('plant_id, health_status, height_cm, created_at') | |
| .in('plant_id', plantIds) | |
| .order('created_at', { ascending: false }), | |
| adopterIds.length | |
| ? supabaseAdmin.from('profiles').select('id, display_name, username').in('id', adopterIds) | |
| : Promise.resolve({ data: [] }), | |
| ]); | |
| // Ordered newest first above, so the first one seen per plant is the latest. | |
| const latestReport = new Map(); | |
| (reportsResult.data || []).forEach(r => { | |
| if (!latestReport.has(r.plant_id)) latestReport.set(r.plant_id, r); | |
| }); | |
| const adopters = new Map((adoptersResult.data || []).map(a => [a.id, a])); | |
| return success(res, plants.map(p => ({ | |
| ...p, | |
| guardian: p.adopted_by ? adopters.get(p.adopted_by) || null : null, | |
| last_report: latestReport.get(p.id) || null, | |
| }))); | |
| } catch (err) { | |
| console.error('listPlants error:', err); | |
| return serverError(res); | |
| } | |
| } | |
| module.exports = { submitOnboarding, dashboard, listApplications, listPlants, ngoStats }; | |