-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsupabase-backend.js
More file actions
1800 lines (1508 loc) · 66.3 KB
/
Copy pathsupabase-backend.js
File metadata and controls
1800 lines (1508 loc) · 66.3 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Supabase Backend Integration for Creative Asset Validator
* Version: 1.0.0
*
* This module provides real-time sync and persistent storage using Supabase.
*
* SETUP INSTRUCTIONS:
* 1. Create a free account at https://supabase.com
* 2. Create a new project
* 3. Go to Settings > API and copy your URL and anon key
* 4. Update SUPABASE_URL and SUPABASE_ANON_KEY below
* 5. Run the SQL schema in your Supabase SQL Editor (see bottom of this file)
*/
(function() {
'use strict';
// ============================================
// CONFIGURATION - UPDATE THESE VALUES
// ============================================
const SUPABASE_URL = window.__CAV_CONFIG__?.SUPABASE_URL || localStorage.getItem('cav_supabase_url') || '';
const SUPABASE_ANON_KEY = window.__CAV_CONFIG__?.SUPABASE_ANON_KEY || localStorage.getItem('cav_supabase_key') || '';
// Check if Supabase is configured
const isConfigured = () => {
return SUPABASE_URL !== 'YOUR_SUPABASE_URL' &&
SUPABASE_ANON_KEY !== 'YOUR_SUPABASE_ANON_KEY';
};
// ============================================
// SUPABASE CLIENT
// ============================================
let supabase = null;
async function initSupabase() {
if (!isConfigured()) {
console.warn('[Supabase] Not configured. Using local storage only.');
return null;
}
// Load Supabase client library if not already loaded
if (!window.supabase) {
await loadSupabaseLibrary();
}
supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
console.log('[Supabase] ✅ Client initialized');
// Set up auth state listener
supabase.auth.onAuthStateChange((event, session) => {
console.log('[Supabase] Auth state changed:', event);
if (session) {
window.supabaseSession = session;
// Sync local data to cloud on login
syncLocalToCloud();
}
});
return supabase;
}
async function loadSupabaseLibrary() {
return new Promise((resolve, reject) => {
if (window.supabase) {
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2';
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// ============================================
// AUTHENTICATION
// ============================================
// Sign in with Google (integrates with existing Google OAuth)
async function signInWithGoogle(googleCredential) {
if (!supabase) return { error: 'Supabase not initialized' };
try {
const { data, error } = await supabase.auth.signInWithIdToken({
provider: 'google',
token: googleCredential
});
if (error) throw error;
console.log('[Supabase] ✅ Signed in with Google');
return { data };
} catch (error) {
console.error('[Supabase] Google sign-in error:', error);
return { error };
}
}
// Get current user - works with both Supabase Auth and Google Sign-In
async function getCurrentUser() {
if (!supabase) {
console.warn('[Supabase] Client not initialized');
return null;
}
try {
// First try Supabase Auth
const { data, error } = await supabase.auth.getUser();
if (!error && data?.user) {
// Return Supabase auth user
return { data: { user: data.user } };
}
// Fallback to Google Sign-In session (cavUserSession)
const googleSession = window.cavUserSession ||
window.CAVSecurity?.SecureSessionManager?.getSession();
if (googleSession?.email) {
// Return a user-like object from Google Sign-In
return {
data: {
user: {
id: null, // No Supabase auth.uid() for Google Sign-In
email: googleSession.email,
user_metadata: {
name: googleSession.name,
full_name: googleSession.name,
avatar_url: googleSession.picture
}
}
},
source: 'google_signin'
};
}
if (error) {
// Only log if we have no fallback
console.log('[Supabase] No auth session, using user_email for queries');
}
return null;
} catch (e) {
console.warn('[Supabase] Exception getting user:', e.message);
return null;
}
}
// Get current user email - works with both auth methods
// ROBUST: Checks multiple sources to ensure we always get the current user
function getCurrentUserEmail() {
try {
// 1. Check window.cavUserSession (set after Google Sign-In)
if (window.cavUserSession?.email) {
return window.cavUserSession.email;
}
// 2. Check CAVSecurity SecureSessionManager
const secureSession = window.CAVSecurity?.SecureSessionManager?.getSession?.();
if (secureSession?.email) {
return secureSession.email;
}
// 3. Check localStorage cav_session (encrypted session)
try {
const cavSession = JSON.parse(localStorage.getItem('cav_session') || 'null');
if (cavSession?.email) {
return cavSession.email;
}
} catch (e) {}
// 4. Check localStorage cav_user_session (plain session)
try {
const userSession = JSON.parse(localStorage.getItem('cav_user_session') || 'null');
if (userSession?.email) {
return userSession.email;
}
} catch (e) {}
// 5. Check localStorage cav_auth_session (auth session)
try {
const authSession = JSON.parse(localStorage.getItem('cav_auth_session') || 'null');
if (authSession?.email) {
return authSession.email;
}
} catch (e) {}
// 6. Check localStorage cav_secure_session_v3 (secure session)
try {
const secureSession = JSON.parse(localStorage.getItem('cav_secure_session_v3') || 'null');
if (secureSession?.email) {
return secureSession.email;
}
} catch (e) {}
// 7. Check localStorage cav_last_user_email (fallback)
const lastEmail = localStorage.getItem('cav_last_user_email');
if (lastEmail && lastEmail !== 'anonymous') {
return lastEmail;
}
return null;
} catch (e) {
console.warn('[Supabase] Error getting user email:', e);
return null;
}
}
// ============================================
// SHARED API KEYS (Encrypted)
// ============================================
// Simple encryption for API keys (use a proper encryption library in production)
function encryptKey(key, salt) {
// Basic XOR encryption - replace with AES in production
const encoded = btoa(key);
return encoded.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ salt.charCodeAt(i % salt.length))
).join('');
}
function decryptKey(encrypted, salt) {
const decrypted = encrypted.split('').map((c, i) =>
String.fromCharCode(c.charCodeAt(0) ^ salt.charCodeAt(i % salt.length))
).join('');
return atob(decrypted);
}
// Save shared API keys (admin only)
async function saveSharedKeys(keys, organizationId) {
if (!supabase) {
// Fallback to localStorage
localStorage.setItem('cav_platform_credentials', JSON.stringify({
sharedKeys: keys,
sharing: { enabled: true }
}));
return { success: true, source: 'local' };
}
try {
const user = await getCurrentUser();
if (!user?.data?.user) throw new Error('Not authenticated');
// Encrypt keys before storing
const salt = user.data.user.id;
const encryptedKeys = {};
for (const [provider, key] of Object.entries(keys)) {
if (key) {
encryptedKeys[provider] = encryptKey(key, salt);
}
}
const { error } = await supabase
.from('shared_api_keys')
.upsert({
organization_id: organizationId || 'default',
admin_user_id: user.data.user.id,
encrypted_keys: encryptedKeys,
updated_at: new Date().toISOString()
}, {
onConflict: 'organization_id'
});
if (error) throw error;
console.log('[Supabase] ✅ Shared keys saved');
return { success: true, source: 'cloud' };
} catch (error) {
console.error('[Supabase] Error saving shared keys:', error);
// Fallback to localStorage
localStorage.setItem('cav_platform_credentials', JSON.stringify({
sharedKeys: keys,
sharing: { enabled: true }
}));
return { success: true, source: 'local', error };
}
}
// Load shared API keys (for team members)
async function loadSharedKeys(organizationId) {
if (!supabase) {
// Fallback to localStorage
const local = JSON.parse(localStorage.getItem('cav_platform_credentials') || '{}');
return local.sharedKeys || {};
}
try {
const user = await getCurrentUser();
if (!user?.data?.user) return {};
const { data, error } = await supabase
.from('shared_api_keys')
.select('*')
.eq('organization_id', organizationId || 'default')
.single();
if (error) throw error;
if (!data) return {};
// Decrypt keys
const salt = data.admin_user_id;
const decryptedKeys = {};
for (const [provider, encrypted] of Object.entries(data.encrypted_keys || {})) {
try {
decryptedKeys[provider] = decryptKey(encrypted, salt);
} catch (e) {
console.warn(`[Supabase] Could not decrypt ${provider} key`);
}
}
console.log('[Supabase] ✅ Shared keys loaded');
return decryptedKeys;
} catch (error) {
console.error('[Supabase] Error loading shared keys:', error);
// Fallback to localStorage
const local = JSON.parse(localStorage.getItem('cav_platform_credentials') || '{}');
return local.sharedKeys || {};
}
}
// Subscribe to real-time key updates
function subscribeToSharedKeys(organizationId, callback) {
if (!supabase) return null;
const subscription = supabase
.channel('shared_keys_changes')
.on('postgres_changes', {
event: '*',
schema: 'public',
table: 'shared_api_keys',
filter: `organization_id=eq.${organizationId || 'default'}`
}, (payload) => {
console.log('[Supabase] Shared keys updated in real-time');
loadSharedKeys(organizationId).then(callback);
})
.subscribe();
return subscription;
}
// ============================================
// CRM DATA SYNC
// ============================================
// Save company
async function saveCompany(company) {
// Always save to local sync engine first for reliability
if (window.syncEngine?.saveCompany) {
await window.syncEngine.saveCompany(company).catch(e =>
console.warn('[Supabase] Local save failed:', e)
);
}
if (!supabase) {
console.log('[Supabase] Not initialized, saved locally only');
return { success: true, source: 'local' };
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
// Must have at least user_email to save to cloud
if (!userId && !userEmail) {
console.warn('[Supabase] No user credentials, saved locally only');
return { success: true, source: 'local' };
}
// Build upsert data with snake_case column names
const upsertData = {
uuid: company.uuid || company.id,
name: company.name,
industry: company.industry || null,
website: company.website || null,
logo_url: company.logoUrl || company.logo_url || null,
description: company.description || null,
type: company.type || 'client',
tags: company.tags || [],
is_shared: company.isShared || company.is_shared || false,
// JSONB fields - Supabase handles objects automatically
metadata: company.metadata || {},
enriched_data: company.enrichedData || company.enriched_data || {},
strategy_insights: company.strategyInsights || company.strategy_insights || {},
chat_history: company.chatHistory || company.chat_history || [],
benchmarks: company.benchmarks || [],
best_practices: company.bestPractices || company.best_practices || [],
competitors: company.competitors || [],
ai_analyses: company.aiAnalyses || company.ai_analyses || [],
notes_list: company.notesList || company.notes_list || [],
linked_assets: company.linkedAssets || company.linked_assets || [],
sharing: company.sharing || {},
// User info
user_email: userEmail,
owner_email: userEmail,
updated_at: new Date().toISOString()
};
// Only include user_id if we have it (from Supabase Auth)
if (userId) {
upsertData.user_id = userId;
}
console.log('[Supabase] Saving company:', upsertData.name, 'uuid:', upsertData.uuid);
const { error } = await supabase
.from('companies')
.upsert(upsertData, {
onConflict: 'uuid'
});
if (error) throw error;
console.log('[Supabase] ✅ Company saved to cloud:', company.name);
return { success: true, source: 'cloud' };
} catch (error) {
console.error('[Supabase] Cloud save error (data saved locally):', error.message);
return { success: true, source: 'local', error: error.message };
}
}
// Get all companies
async function getCompanies() {
// First try local for speed
const localCompanies = await window.syncEngine?.getAllCompanies() || [];
if (!supabase) {
return localCompanies;
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
// Must have at least user_email to query
if (!userId && !userEmail) {
console.log('[Supabase] No user credentials, using local data');
return localCompanies;
}
// Build query based on available credentials
let query = supabase
.from('companies')
.select('*')
.is('deleted_at', null)
.order('created_at', { ascending: false });
// Filter by user - use user_id if available, otherwise user_email
if (userId) {
query = query.or(`user_id.eq.${userId},is_shared.eq.true`);
} else if (userEmail) {
query = query.or(`user_email.eq.${userEmail},is_shared.eq.true`);
}
const { data, error } = await query;
if (error) throw error;
// Parse JSON fields back to objects
const parsed = (data || []).map(company => {
const jsonFields = ['enrichedData', 'strategyInsights', 'aiAnalyses', 'chatHistory',
'benchmarks', 'bestPractices', 'competitors', 'sharing', 'metadata'];
jsonFields.forEach(field => {
if (company[field] && typeof company[field] === 'string') {
try {
company[field] = JSON.parse(company[field]);
} catch (e) {}
}
});
return company;
});
// Merge with local - cloud takes precedence
const mergedMap = new Map();
localCompanies.forEach(c => mergedMap.set(c.uuid || c.id, c));
parsed.forEach(c => mergedMap.set(c.uuid || c.id, c));
console.log(`[Supabase] Loaded ${parsed.length} companies from cloud`);
return Array.from(mergedMap.values());
} catch (error) {
console.error('[Supabase] Error getting companies:', error.message);
return localCompanies;
}
}
// Save contact
async function saveContact(contact) {
if (!supabase) {
return window.syncEngine?.saveContact(contact);
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
const upsertData = {
...contact,
user_email: userEmail,
updated_at: new Date().toISOString()
};
if (userId) upsertData.user_id = userId;
const { error } = await supabase
.from('contacts')
.upsert(upsertData, { onConflict: 'uuid' });
if (error) throw error;
console.log('[Supabase] ✅ Contact saved to cloud');
return { success: true };
} catch (error) {
console.warn('[Supabase] Contact save error:', error.message);
return window.syncEngine?.saveContact(contact);
}
}
// Get all contacts
async function getContacts() {
const localContacts = window.syncEngine?.getAllContacts() || [];
if (!supabase) {
return localContacts;
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
if (!userId && !userEmail) {
return localContacts;
}
let query = supabase
.from('contacts')
.select('*')
.is('deleted_at', null);
if (userId) {
query = query.or(`user_id.eq.${userId},is_shared.eq.true`);
} else if (userEmail) {
query = query.eq('user_email', userEmail);
}
const { data, error } = await query;
if (error) throw error;
// Merge with local
const mergedMap = new Map();
localContacts.forEach(c => mergedMap.set(c.uuid || c.id, c));
(data || []).forEach(c => mergedMap.set(c.uuid || c.id, c));
return Array.from(mergedMap.values());
} catch (error) {
return localContacts;
}
}
// Save project
async function saveProject(project) {
if (!supabase) {
return window.syncEngine?.saveProject(project);
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
const upsertData = {
...project,
user_email: userEmail,
updated_at: new Date().toISOString()
};
if (userId) upsertData.user_id = userId;
const { error } = await supabase
.from('projects')
.upsert(upsertData, { onConflict: 'uuid' });
if (error) throw error;
console.log('[Supabase] ✅ Project saved to cloud');
return { success: true };
} catch (error) {
console.warn('[Supabase] Project save error:', error.message);
return window.syncEngine?.saveProject(project);
}
}
// Get all projects
async function getProjects() {
const localProjects = window.syncEngine?.getAllProjects() || [];
if (!supabase) {
return localProjects;
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
if (!userId && !userEmail) {
return localProjects;
}
let query = supabase
.from('projects')
.select('*')
.is('deleted_at', null);
if (userId) {
query = query.or(`user_id.eq.${userId},is_shared.eq.true`);
} else if (userEmail) {
query = query.eq('user_email', userEmail);
}
const { data, error } = await query;
if (error) throw error;
return data || [];
} catch (error) {
return window.syncEngine?.getAllProjects() || [];
}
}
// ============================================
// USER ACTIVITY LOGGING
// ============================================
async function logUserActivity(activity) {
if (!supabase) {
// Store in localStorage
const logs = JSON.parse(localStorage.getItem('cav_user_activity') || '[]');
logs.push({ ...activity, timestamp: new Date().toISOString() });
localStorage.setItem('cav_user_activity', JSON.stringify(logs.slice(-1000))); // Keep last 1000
return;
}
try {
const user = await getCurrentUser();
const userEmail = user?.data?.user?.email || getCurrentUserEmail() || 'anonymous';
await supabase.from('user_activity').insert({
user_id: user?.data?.user?.id,
user_email: userEmail,
owner_email: userEmail,
action: activity.action,
details: activity.details,
ip_address: activity.ip,
user_agent: navigator.userAgent,
created_at: new Date().toISOString()
});
} catch (error) {
console.warn('[Supabase] Error logging activity:', error);
}
}
async function getUserActivityLogs(limit = 100) {
if (!supabase) {
return JSON.parse(localStorage.getItem('cav_user_activity') || '[]').slice(-limit);
}
try {
const { data, error } = await supabase
.from('user_activity')
.select('*')
.order('created_at', { ascending: false })
.limit(limit);
if (error) throw error;
return data || [];
} catch (error) {
return JSON.parse(localStorage.getItem('cav_user_activity') || '[]').slice(-limit);
}
}
// ============================================
// SETTINGS SYNC
// ============================================
async function saveSettings(settings) {
if (!supabase) {
localStorage.setItem('cav_v3_settings', JSON.stringify(settings));
return { success: true, source: 'local' };
}
try {
const user = await getCurrentUser();
if (!user?.data?.user) {
localStorage.setItem('cav_v3_settings', JSON.stringify(settings));
return { success: true, source: 'local' };
}
const { error } = await supabase
.from('user_settings')
.upsert({
user_id: user.data.user.id,
settings: settings,
updated_at: new Date().toISOString()
}, {
onConflict: 'user_id'
});
if (error) throw error;
// Also save locally for offline access
localStorage.setItem('cav_v3_settings', JSON.stringify(settings));
return { success: true, source: 'cloud' };
} catch (error) {
localStorage.setItem('cav_v3_settings', JSON.stringify(settings));
return { success: true, source: 'local', error };
}
}
async function loadSettings() {
const localSettings = JSON.parse(localStorage.getItem('cav_v3_settings') || '{}');
if (!supabase) {
return localSettings;
}
try {
const user = await getCurrentUser();
const userId = user?.data?.user?.id;
const userEmail = user?.data?.user?.email || getCurrentUserEmail();
if (!userId && !userEmail) return localSettings;
// Query by user_id if available, otherwise by user_email
let query = supabase.from('user_settings').select('settings, data');
if (userId) {
query = query.eq('user_id', userId);
} else {
query = query.eq('user_email', userEmail);
}
const { data, error } = await query.maybeSingle();
if (error || !data) return localSettings;
// Merge cloud settings with local (cloud takes precedence)
const cloudSettings = data.settings || data.data || {};
const merged = { ...localSettings, ...cloudSettings };
localStorage.setItem('cav_v3_settings', JSON.stringify(merged));
return merged;
} catch (error) {
return localSettings;
}
}
// ============================================
// DATA MIGRATION (localStorage → Supabase)
// ============================================
async function syncLocalToCloud() {
if (!supabase) return;
console.log('[Supabase] Starting local → cloud sync...');
try {
// Sync companies
const localCompanies = await window.syncEngine?.getAllCompanies() || [];
for (const company of localCompanies) {
await saveCompany(company);
}
// Sync contacts
const localContacts = await window.syncEngine?.getAllContacts() || [];
for (const contact of localContacts) {
await saveContact(contact);
}
// Sync projects
const localProjects = await window.syncEngine?.getAllProjects() || [];
for (const project of localProjects) {
await saveProject(project);
}
// Sync settings
const localSettings = JSON.parse(localStorage.getItem('cav_v3_settings') || '{}');
if (Object.keys(localSettings).length > 0) {
await saveSettings(localSettings);
}
console.log('[Supabase] ✅ Local → cloud sync complete');
} catch (error) {
console.error('[Supabase] Sync error:', error);
}
}
// ============================================
// EXPORT API
// ============================================
// ============================================
// DIAGNOSTIC TOOL
// ============================================
async function runDiagnostics() {
console.log('═══════════════════════════════════════════');
console.log(' CAV SUPABASE DIAGNOSTICS');
console.log('═══════════════════════════════════════════');
const results = {
configured: isConfigured(),
connected: false,
authenticated: false,
canReadKeys: false,
canWriteKeys: false,
tablesExist: false,
errors: []
};
// 1. Check configuration
console.log('\n📋 Configuration:');
console.log(` URL: ${SUPABASE_URL.substring(0, 30)}...`);
console.log(` Key: ${SUPABASE_ANON_KEY.substring(0, 20)}...`);
console.log(` Configured: ${results.configured ? '✅ Yes' : '❌ No'}`);
if (!results.configured) {
results.errors.push('Supabase not configured');
return results;
}
// 2. Check connection
console.log('\n🔌 Connection:');
try {
if (!supabase) await initSupabase();
const { data, error } = await supabase.from('shared_api_keys').select('count').limit(1);
if (error && error.code === '42P01') {
console.log(' ❌ Tables not created - run the SQL schema');
results.errors.push('Tables not created');
} else if (error) {
console.log(` ❌ Connection error: ${error.message}`);
results.errors.push(error.message);
} else {
console.log(' ✅ Connected to Supabase');
results.connected = true;
results.tablesExist = true;
}
} catch (e) {
console.log(` ❌ Connection failed: ${e.message}`);
results.errors.push(e.message);
}
// 3. Check authentication
console.log('\n🔐 Authentication:');
try {
const { data: { user } } = await supabase.auth.getUser();
if (user) {
console.log(` ✅ Authenticated as: ${user.email}`);
results.authenticated = true;
} else {
console.log(' ⚠️ Not authenticated (anonymous access)');
console.log(' → Users can still read shared keys');
console.log(' → To enable full sync, set up Google Auth in Supabase');
}
} catch (e) {
console.log(` ⚠️ Auth check: ${e.message}`);
}
// 4. Check shared keys
console.log('\n🔑 Shared Keys:');
try {
const { data, error } = await supabase
.from('shared_api_keys')
.select('*')
.eq('organization_id', 'default');
if (error) {
console.log(` ❌ Cannot read: ${error.message}`);
} else if (data && data.length > 0) {
console.log(` ✅ Found shared keys for organization`);
console.log(` Providers configured: ${Object.keys(data[0].encrypted_keys || {}).join(', ') || 'none'}`);
results.canReadKeys = true;
} else {
console.log(' ⚠️ No shared keys saved yet');
console.log(' → Go to Settings > API Sharing to configure');
}
} catch (e) {
console.log(` ❌ Error: ${e.message}`);
}
// 5. Check localStorage fallback
console.log('\n💾 Local Storage:');
const localCreds = JSON.parse(localStorage.getItem('cav_platform_credentials') || '{}');
const localKeys = localCreds.sharedKeys || {};
console.log(` Local shared keys: ${Object.keys(localKeys).filter(k => localKeys[k]).join(', ') || 'none'}`);
console.log(` Sharing enabled: ${localCreds.sharing?.enabled ? 'Yes' : 'No'}`);
// 6. Summary
console.log('\n═══════════════════════════════════════════');
console.log(' SUMMARY');
console.log('═══════════════════════════════════════════');
if (results.connected && results.tablesExist) {
console.log('✅ Supabase is ready for cloud sync!');
if (!results.canReadKeys) {
console.log('→ Save your API keys in Settings > API Sharing');
}
} else if (results.configured) {
console.log('⚠️ Supabase configured but not fully connected');
console.log('→ Check if tables are created');
console.log('→ Check Supabase dashboard for errors');
} else {
console.log('❌ Using local storage only (no cloud sync)');
}
console.log('\n═══════════════════════════════════════════\n');
return results;
}
// ============================================
// DIRECT SAVE (NO AUTH REQUIRED)
// ============================================
// Save shared keys directly (for admin use without full auth)
async function saveSharedKeysDirect(keys, organizationId = 'default') {
if (!supabase) {
await initSupabase();
}
if (!supabase) {
console.error('[Supabase] Cannot initialize client');
return { success: false, error: 'Supabase not initialized' };
}
try {
// Get admin email from session
const adminEmail = window.cavUserSession?.email || 'unknown';
const { data, error } = await supabase
.from('shared_api_keys')
.upsert({
organization_id: organizationId,
admin_user_id: null, // Anonymous save
encrypted_keys: keys, // Store keys (consider encryption for production)
allowed_domains: [],
allowed_emails: [],
is_global_share: true,
updated_at: new Date().toISOString()
}, {
onConflict: 'organization_id'
})
.select();
if (error) {
console.error('[Supabase] Save error:', error);
return { success: false, error: error.message };
}
console.log('[Supabase] ✅ Shared keys saved directly');
return { success: true, data };
} catch (e) {
console.error('[Supabase] Exception:', e);
return { success: false, error: e.message };
}
}
// Load shared keys directly (no auth required)
async function loadSharedKeysDirect(organizationId = 'default') {
if (!supabase) {
await initSupabase();
}
if (!supabase) {
return { success: false, keys: {} };
}
try {
// Use maybeSingle() instead of single() to avoid 406 errors when no rows exist
const { data, error } = await supabase
.from('shared_api_keys')
.select('encrypted_keys')
.eq('organization_id', organizationId)
.maybeSingle();
if (error) {
// Handle common errors gracefully
if (error.code === 'PGRST116' || error.code === '406' || error.message?.includes('406')) {
// No rows found - not an error
return { success: true, keys: {} };
}
// Table doesn't exist yet
if (error.code === '42P01' || error.message?.includes('does not exist')) {
console.warn('[Supabase] shared_api_keys table not created yet');
return { success: true, keys: {} };
}
console.error('[Supabase] Load error:', error);
return { success: false, keys: {}, error: error.message };
}
// data can be null if no rows match
if (!data) {