File size: 7,813 Bytes
55ffa7e
 
83f4356
 
55ffa7e
 
 
 
 
 
83f4356
 
 
 
 
55ffa7e
 
 
 
 
 
 
 
83f4356
55ffa7e
83f4356
55ffa7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83f4356
 
 
 
 
 
55ffa7e
 
 
 
 
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55ffa7e
 
 
83f4356
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04189d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 };