-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsupabase-integration.js
More file actions
229 lines (194 loc) · 8.16 KB
/
supabase-integration.js
File metadata and controls
229 lines (194 loc) · 8.16 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
// Supabase Integration for Donations and Leaderboard
class SupabaseIntegration {
constructor() {
this.supabase = null;
this.initializeSupabase();
}
initializeSupabase() {
try {
this.supabase = supabase.createClient(
SUPABASE_CONFIG.url,
SUPABASE_CONFIG.anonKey
);
console.log('✅ Supabase initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize Supabase:', error);
}
}
// Store donation in Supabase
async storeDonation(donationData) {
if (!this.supabase) {
throw new Error('Supabase not initialized');
}
try {
const { data, error } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.donationsTableName)
.insert([{
name: donationData.name,
email: donationData.email,
phone: donationData.phone,
amount: donationData.amount,
donation_type: donationData.donationType,
payment_method: donationData.paymentMethod,
payment_status: 'completed',
transaction_id: donationData.transactionId || `TXN_${Date.now()}`,
created_at: new Date().toISOString(),
anonymous: donationData.name === 'Anonymous',
leaderboard_eligible: this.isLeaderboardEligible(donationData)
}])
.select();
if (error) {
console.error('❌ Error storing donation in Supabase:', error);
throw new Error('Failed to store donation');
}
console.log('✅ Donation stored in Supabase:', data[0]);
return data[0];
} catch (error) {
console.error('❌ Supabase donation storage error:', error);
throw error;
}
}
// Check if donation is eligible for leaderboard
isLeaderboardEligible(donationData) {
// Must meet minimum amount and not be anonymous
return donationData.amount >= SUPABASE_CONFIG.leaderboard.minAmount &&
donationData.name !== 'Anonymous' &&
donationData.leaderboardConsent;
}
// Update leaderboard with new donation
async updateLeaderboard(donationData, supabaseDonationId) {
if (!this.isLeaderboardEligible(donationData)) {
console.log('ℹ️ Donation not eligible for leaderboard');
return null;
}
try {
// Check if donor already exists in leaderboard
const { data: existingDonor } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.tableName)
.select('*')
.eq('name', donationData.name)
.single();
if (existingDonor) {
// Update existing donor's total
const newTotal = existingDonor.total_amount + donationData.amount;
const newCount = existingDonor.donation_count + 1;
const { data: updatedDonor, error: updateError } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.tableName)
.update({
total_amount: newTotal,
donation_count: newCount,
last_donation_date: new Date().toISOString(),
last_donation_amount: donationData.amount,
updated_at: new Date().toISOString()
})
.eq('id', existingDonor.id)
.select()
.single();
if (updateError) {
console.error('❌ Error updating existing donor:', updateError);
throw new Error('Failed to update leaderboard');
}
console.log('✅ Updated existing donor in leaderboard:', updatedDonor);
return updatedDonor;
} else {
// Add new donor to leaderboard
const { data: newDonor, error: insertError } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.tableName)
.insert([{
name: donationData.name,
total_amount: donationData.amount,
donation_count: 1,
first_donation_date: new Date().toISOString(),
last_donation_date: new Date().toISOString(),
last_donation_amount: donationData.amount,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}])
.select()
.single();
if (insertError) {
console.error('❌ Error adding new donor to leaderboard:', insertError);
throw new Error('Failed to add to leaderboard');
}
console.log('✅ Added new donor to leaderboard:', newDonor);
return newDonor;
}
} catch (error) {
console.error('❌ Leaderboard update error:', error);
throw error;
}
}
// Get leaderboard data
async getLeaderboard(limit = 50) {
if (!this.supabase) {
throw new Error('Supabase not initialized');
}
try {
const { data, error } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.tableName)
.select('*')
.order('total_amount', { ascending: false })
.limit(limit);
if (error) {
console.error('❌ Error fetching leaderboard:', error);
throw new Error('Failed to fetch leaderboard');
}
return data;
} catch (error) {
console.error('❌ Leaderboard fetch error:', error);
throw error;
}
}
// Get donation statistics
async getDonationStats() {
if (!this.supabase) {
throw new Error('Supabase not initialized');
}
try {
const { data, error } = await this.supabase
.from(SUPABASE_CONFIG.leaderboard.donationsTableName)
.select('amount, payment_status');
if (error) {
console.error('❌ Error fetching donation stats:', error);
throw new Error('Failed to fetch donation stats');
}
const totalRaised = data
.filter(d => d.payment_status === 'completed')
.reduce((sum, d) => sum + d.amount, 0);
const totalDonations = data.filter(d => d.payment_status === 'completed').length;
return {
totalRaised,
totalDonations
};
} catch (error) {
console.error('❌ Donation stats error:', error);
throw error;
}
}
// Process complete donation (donation + leaderboard)
async processCompleteDonation(donationData) {
try {
console.log('Processing complete donation in Supabase...');
// 1. Store donation
const storedDonation = await this.storeDonation(donationData);
// 2. Update leaderboard if eligible
const leaderboardUpdate = await this.updateLeaderboard(donationData, storedDonation.id);
// 3. Return complete result
return {
success: true,
donation: storedDonation,
leaderboard: leaderboardUpdate,
message: leaderboardUpdate
? 'Donation processed and added to leaderboard!'
: 'Donation processed successfully!'
};
} catch (error) {
console.error('❌ Complete donation processing failed:', error);
throw error;
}
}
}
// Initialize Supabase integration when page loads
document.addEventListener('DOMContentLoaded', () => {
window.supabaseIntegration = new SupabaseIntegration();
});