-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanulunar-report-api.js
More file actions
459 lines (397 loc) · 12.5 KB
/
anulunar-report-api.js
File metadata and controls
459 lines (397 loc) · 12.5 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// =============================================
// AnuLunar API - Report Download Endpoints (CORRECTED)
// Using Supabase Storage - Precision Fixes Applied
// =============================================
import { createClient } from '@supabase/supabase-js';
import { supabaseStorage } from './supabase-storage-service.js';
const supabase = createClient(
process.env.SUPABASE_URL,
process.env.SUPABASE_SERVICE_KEY
);
// Valid report types from database (table-driven validation)
async function getValidReportTypes() {
const { data, error } = await supabase
.from('report_types')
.select('slug')
.eq('active', true);
if (error) {
// Fallback to hardcoded for now
// TODO: Create report_types table
return ['inner_child_healing', 'karmic_blueprint', 'complete_spiritual_intelligence', 'numerology', 'astrology', 'celtic_moon'];
}
return data.map(row => row.slug);
}
// =============================================
// Report Download API Endpoints
// =============================================
// GET /v1/reports/download/:reportId
export async function downloadReport(req, res) {
try {
const { reportId } = req.params;
const userId = req.user?.id;
// Fix: Hardened auth check
if (!userId) {
return res.status(401).json({
error: 'Authentication required'
});
}
if (!reportId) {
return res.status(400).json({
error: 'Report ID is required'
});
}
// Fix 1: Direct ownership check, no unnecessary join
const { data: report, error } = await supabase
.from('spiritual_reports')
.select('*')
.eq('id', reportId)
.eq('profile_id', userId) // Direct ownership check
.eq('generation_status', 'completed')
.single();
if (error || !report) {
return res.status(404).json({
error: 'Report not found or access denied'
});
}
// Fix 2: Improved filename handling with full paths
let filename = null;
if (report.report_pdf_url) {
// Extract filename from Supabase signed URL
const urlParts = report.report_pdf_url.split('/');
filename = urlParts[urlParts.length - 1].split('?')[0];
}
// If no stored URL, find the file using improved path logic
if (!filename) {
const reportFiles = await supabaseStorage.listProfileReports(report.profile_id);
const matchingFile = reportFiles.find(file =>
file.name.includes(report.report_type)
);
if (matchingFile) {
// Fix 2: Use fullPath from storage service instead of reconstructing
filename = matchingFile.fullPath;
}
}
if (!filename) {
return res.status(404).json({
error: 'Report file not found'
});
}
// Generate fresh signed URL (24 hour expiry)
const signedUrl = await supabaseStorage.getReportUrl(filename, 86400);
if (!signedUrl) {
return res.status(500).json({
error: 'Failed to generate download link'
});
}
// Log download activity
await logDownloadActivity(reportId, userId, req);
// Return download information
res.json({
success: true,
report: {
id: report.id,
type: report.report_type,
tier: report.report_tier,
generated_at: report.generated_at,
download_url: signedUrl,
expires_at: new Date(Date.now() + 86400 * 1000).toISOString() // 24 hours
}
});
} catch (error) {
console.error('❌ Error in downloadReport:', error);
res.status(500).json({
error: 'Internal server error'
});
}
}
// GET /v1/reports/list
export async function listUserReports(req, res) {
try {
const userId = req.user?.id;
// Fix: Hardened auth check
if (!userId) {
return res.status(401).json({
error: 'Authentication required'
});
}
// Get all reports for the user
const { data: reports, error } = await supabase
.from('spiritual_reports')
.select('id, report_type, report_tier, sacred_price, generation_status, generated_at, created_at')
.eq('profile_id', userId)
.order('created_at', { ascending: false });
if (error) {
console.error('❌ Error fetching user reports:', error);
return res.status(500).json({
error: 'Failed to fetch reports'
});
}
res.json({
success: true,
reports: reports || []
});
} catch (error) {
console.error('❌ Error in listUserReports:', error);
res.status(500).json({
error: 'Internal server error'
});
}
}
// GET /v1/reports/status/:profileId
export async function getReportStatus(req, res) {
try {
const { profileId } = req.params;
const userId = req.user?.id;
// Fix: Hardened auth check
if (!userId) {
return res.status(401).json({
error: 'Authentication required'
});
}
// Verify user owns this profile
if (profileId !== userId) {
return res.status(403).json({
error: 'Access denied'
});
}
// Get completion status using our database function
const { data: status, error } = await supabase
.rpc('get_profile_completion_status', {
p_profile_id: profileId
});
if (error) {
console.error('❌ Error checking completion status:', error);
return res.status(500).json({
error: 'Failed to check status'
});
}
// Get available reports
const { data: reports } = await supabase
.from('spiritual_reports')
.select('id, report_type, generation_status, generated_at')
.eq('profile_id', profileId)
.order('created_at', { ascending: false });
res.json({
success: true,
profile_id: profileId,
completion_status: status,
available_reports: reports || []
});
} catch (error) {
console.error('❌ Error in getReportStatus:', error);
res.status(500).json({
error: 'Internal server error'
});
}
}
// POST /v1/reports/generate/:reportType
export async function generateReport(req, res) {
try {
const { reportType } = req.params;
const { tier = 'crystal_clarity' } = req.body;
const userId = req.user?.id;
// Fix: Hardened auth check
if (!userId) {
return res.status(401).json({
error: 'Authentication required'
});
}
// Fix 5: Table-driven validation
const validReportTypes = await getValidReportTypes();
const validTiers = ['crystal_clarity', 'full_spectrum_circle'];
if (!validReportTypes.includes(reportType)) {
return res.status(400).json({
error: 'Invalid report type'
});
}
if (!validTiers.includes(tier)) {
return res.status(400).json({
error: 'Invalid report tier'
});
}
// Check if user has all required data
const { data: status } = await supabase
.rpc('get_profile_completion_status', {
p_profile_id: userId
});
if (!status?.complete) {
return res.status(400).json({
error: 'Complete profile data required before generating reports',
missing_data: {
numerology_ready: status?.numerology_ready || false,
astrology_ready: status?.astrology_ready || false,
celtic_ready: status?.celtic_ready || false
}
});
}
// Set sacred pricing
const sacredPrices = {
crystal_clarity: 44.44,
full_spectrum_circle: 99.99
};
// Create report generation request
const { data: report, error } = await supabase
.from('spiritual_reports')
.insert([{
profile_id: userId,
report_type: reportType,
report_tier: tier,
sacred_price: sacredPrices[tier],
generation_status: 'generating',
synthesized_content: {}
}])
.select()
.single();
if (error) {
console.error('❌ Error creating report request:', error);
return res.status(500).json({
error: 'Failed to queue report generation'
});
}
// Fix 4: Mark for future improvement to proper job queue
// TODO: Replace with background worker (Supabase Edge Function, BullMQ, or Inngest)
setImmediate(async () => {
try {
await generateReportBackground(report.id, userId, reportType);
} catch (error) {
console.error('❌ Background report generation failed:', error);
}
});
res.json({
success: true,
report_id: report.id,
generation_status: 'generating',
estimated_completion: new Date(Date.now() + 10 * 60 * 1000).toISOString(), // 10 minutes
sacred_price: sacredPrices[tier]
});
} catch (error) {
console.error('❌ Error in generateReport:', error);
res.status(500).json({
error: 'Internal server error'
});
}
}
// =============================================
// Helper Functions
// =============================================
async function logDownloadActivity(reportId, userId, req) {
try {
// Log download for analytics
await supabase
.from('report_downloads')
.insert([{
report_id: reportId,
profile_id: userId,
ip_address: req.ip,
user_agent: req.get('User-Agent'),
downloaded_at: new Date().toISOString()
}]);
} catch (error) {
console.error('❌ Error logging download activity:', error);
}
}
async function generateReportBackground(reportId, profileId, reportType) {
try {
// Get all data needed for report generation
const { data: reportData, error } = await supabase
.from('profiles')
.select(`
*,
numerology_reports(*),
astrology_reports(*),
celtic_moon_reports(*)
`)
.eq('id', profileId)
.single();
if (error || !reportData) {
throw new Error('Failed to fetch complete report data');
}
// Get the report record
const { data: report } = await supabase
.from('spiritual_reports')
.select('*')
.eq('id', reportId)
.single();
if (!report) {
throw new Error('Report record not found');
}
// Generate and store the report using Supabase Storage
const result = await supabaseStorage.generateAndStoreReport(reportId, {
...report,
profile: reportData,
numerology: reportData.numerology_reports[0],
astrology: reportData.astrology_reports[0],
celticMoon: reportData.celtic_moon_reports[0]
});
if (result) {
console.log('✅ Background report generation completed');
// Send completion notification with retry logic
await sendReportReadyNotificationWithRetry(reportData.email, {
first_name: reportData.first_name,
report_type: reportType,
download_url: result.downloadUrl
});
}
} catch (error) {
console.error('❌ Background report generation failed:', error);
// Update report status to failed
await supabase
.from('spiritual_reports')
.update({
generation_status: 'failed',
generated_at: new Date().toISOString()
})
.eq('id', reportId);
}
}
// Fix: Brevo integration with retry protection
async function sendReportReadyNotificationWithRetry(email, data, retryCount = 0) {
try {
const response = await fetch('https://api.brevo.com/v3/smtp/email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': process.env.BREVO_API_KEY
},
body: JSON.stringify({
to: [{ email: email, name: data.first_name }],
templateId: parseInt(process.env.BREVO_FULL_REPORT_READY_TEMPLATE_ID),
params: data
})
});
if (response.ok) {
console.log(`📧 Report ready notification sent to ${email}`);
// Store notification status (optional but recommended)
await supabase
.from('report_notifications')
.insert([{
email: email,
report_type: data.report_type,
sent_at: new Date().toISOString(),
status: 'sent'
}]);
} else {
throw new Error(`Brevo API error: ${response.status}`);
}
} catch (error) {
console.error('❌ Error sending report ready notification:', error);
// Retry once only
if (retryCount === 0) {
console.log('🔄 Retrying notification send...');
setTimeout(() => {
sendReportReadyNotificationWithRetry(email, data, 1);
}, 5000); // 5 second delay
} else {
// Store failed notification
await supabase
.from('report_notifications')
.insert([{
email: email,
report_type: data.report_type,
sent_at: new Date().toISOString(),
status: 'failed',
error_message: error.message
}]);
}
}
}