-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
2919 lines (2706 loc) · 167 KB
/
Copy pathApp.tsx
File metadata and controls
2919 lines (2706 loc) · 167 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
import React, { useState, useEffect, useRef } from 'react';
import { ViewMode, FormDefinition, SignerData, UserCredentials, SubscriptionPlan } from './types';
import Header from './components/Header';
import QRCodeModal from './components/QRCodeModal';
import { triggerZohoSignTemplate, testZohoConnection, fetchTemplateRoles, TemplateRole } from './services/zohoService';
import { supabase } from './services/supabaseClient';
import { getRouteContext, buildFormUrl } from './services/routingService';
import { validateContrast, validateAltText, KeyCodes, handleEnterOrSpace, getRelativeLuminance } from './utils/accessibility';
// Reserved slugs that cannot be used for forms
const RESERVED_SLUGS = ['api', 'admin', 'assets', 'static', 'public', '_next', 'favicon.ico', 'qr', 'embed'];
// Validate slug format and check against reserved words
const isValidSlug = (slug: string): boolean => {
if (!slug || slug.length === 0) return false;
// Only allow alphanumeric characters and hyphens
const slugRegex = /^[a-z0-9-]+$/;
if (!slugRegex.test(slug)) return false;
// Check against reserved words
if (RESERVED_SLUGS.includes(slug.toLowerCase())) return false;
return true;
};
// Convert slug to display title (e.g., "fbmc-short-application" -> "FBMC Short Application")
const slugToTitle = (slug: string): string => {
return slug
.split('-')
.map(word => {
// Keep common acronyms uppercase
if (word.length <= 4 && /^[a-z]+$/.test(word)) {
const upper = word.toUpperCase();
// Common acronyms that should stay uppercase
if (['FBMC', 'LLC', 'INC', 'USA', 'FAQ', 'PDF', 'API'].includes(upper)) {
return upper;
}
}
// Title case for regular words
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
})
.join(' ');
};
// Extend window for ZohoSign SDK
declare global {
interface Window {
ZohoSign: any;
}
}
const App: React.FC = () => {
const routeContext = getRouteContext();
// Destructure to primitives so useEffect dep arrays get stable scalar values
// instead of a new object reference on every render.
const { subdomain: routeSubdomain, isFormSlug: routeIsFormSlug, formSlug: routeFormSlug } = routeContext;
// Compute BEFORE any hooks so all hooks below are always called unconditionally.
// The actual redirect side-effect is moved to a useEffect further down (see UX-03).
const isRootDomain = routeSubdomain === 'root';
const getInitialView = () => {
const hash = window.location.hash || '';
const path = window.location.pathname || '/';
const hostname = window.location.hostname;
// Check for path-based form URLs (e.g., /formslug)
if (path !== '/' && !path.startsWith('/api') && !path.startsWith('/qr/')) {
return ViewMode.PUBLIC_FORM;
}
// Check for hash-based admin routes
if (hash.startsWith('#/admin/form/')) {
return ViewMode.FORM_DETAILS;
} else if (hash.startsWith('#/admin')) {
return ViewMode.ADMIN_LOGIN;
}
// If on app subdomain and no hash, redirect to admin
if (hostname.startsWith('app.') && hash === '' && path === '/') {
window.location.hash = '#/admin';
return ViewMode.ADMIN_LOGIN;
}
return ViewMode.LANDING;
};
// Determine if this is a public form page (for faster loading)
const isPublicFormPage = () => {
const path = window.location.pathname || '/';
return path !== '/' && !path.startsWith('/api') && !path.startsWith('/qr/');
};
// Determine if we should wait for auth before rendering (only for admin pages)
const shouldWaitForAuth = () => {
const hash = window.location.hash || '';
// Only admin pages need to wait for auth
return hash.startsWith('#/admin');
};
const [view, setView] = useState<ViewMode | null>(isRootDomain ? null : getInitialView());
// Landing pages and public forms render immediately; only admin pages wait for auth
const [isRouteResolved, setIsRouteResolved] = useState(isRootDomain ? false : !shouldWaitForAuth());
const [isFormLoading, setIsFormLoading] = useState(isRootDomain ? false : isPublicFormPage());
const [forms, setForms] = useState<FormDefinition[]>([]);
const [auth, setAuth] = useState<{username: string; password: string} | null>(null);
const [sessionToken, setSessionToken] = useState<string | null>(null);
const [userId, setUserId] = useState<string | null>(null);
const [currentForm, setCurrentForm] = useState<FormDefinition | null>(null);
const [usernameInput, setUsernameInput] = useState('');
const [passwordInput, setPasswordInput] = useState('');
const [authMode, setAuthMode] = useState<'login' | 'signup'>('login');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [successData, setSuccessData] = useState<{requestId: string, signingUrl?: string} | null>(null);
const [darkMode, setDarkMode] = useState(true);
// Test/Helper states
const [testingId, setTestingId] = useState<string | null>(null);
const [testResult, setTestResult] = useState<{success: boolean, message: string, hint?: string} | null>(null);
// Form editing states
const [editingId, setEditingId] = useState<string | null>(null);
const [formName, setFormName] = useState('');
const [templateId, setTemplateId] = useState('');
const [roleName, setRoleName] = useState('Signer 1');
const [apiDomain, setApiDomain] = useState('https://sign.zoho.com');
const [slug, setSlug] = useState('');
// User-level Zoho credentials (secrets are never held in state after P1-03)
const [credClientId, setCredClientId] = useState('');
// credNewClientSecret / credNewRefreshToken: only populated when user actively wants to set/replace
const [credNewClientSecret, setCredNewClientSecret] = useState('');
const [credNewRefreshToken, setCredNewRefreshToken] = useState('');
const [credApiDomain, setCredApiDomain] = useState('https://sign.zoho.com');
const [credHasClientSecret, setCredHasClientSecret] = useState(false);
const [credHasRefreshToken, setCredHasRefreshToken] = useState(false);
const [credentialsLoaded, setCredentialsLoaded] = useState(false);
const [subscription, setSubscription] = useState<SubscriptionPlan | null>(null);
const [subscriptionLoaded, setSubscriptionLoaded] = useState(false);
// QR Code Modal state
const [qrModalOpen, setQrModalOpen] = useState(false);
const [qrModalForm, setQrModalForm] = useState<FormDefinition | null>(null);
// Form Details page state
const [selectedFormId, setSelectedFormId] = useState<string | null>(null);
const [detailsTab, setDetailsTab] = useState<'settings' | 'landing' | 'signers' | 'embed' | 'qr' | 'analytics'>('settings');
// Landing page editor state
const [landingHeadline, setLandingHeadline] = useState('');
const [landingDescription, setLandingDescription] = useState('');
const [landingLogoUrl, setLandingLogoUrl] = useState('');
const [landingPrimaryColor, setLandingPrimaryColor] = useState('#3B82F6');
const [landingBackgroundColor, setLandingBackgroundColor] = useState('#F8FAFC');
const [landingCardColor, setLandingCardColor] = useState('#FFFFFF');
const [landingButtonText, setLandingButtonText] = useState('Sign Now');
const [landingCompanyName, setLandingCompanyName] = useState('');
const [landingContactEmail, setLandingContactEmail] = useState('');
const [landingContactPhone, setLandingContactPhone] = useState('');
const [landingFooterText, setLandingFooterText] = useState('');
const [landingShowPoweredBy, setLandingShowPoweredBy] = useState(true);
// Accessibility state
const [landingLogoAlt, setLandingLogoAlt] = useState('');
const [contrastWarning, setContrastWarning] = useState<string | null>(null);
const [altTextError, setAltTextError] = useState<string | null>(null);
// Signers & Delivery editor state
// templateRoles: roles fetched live from the Zoho template (with action type + isPublic flag).
// signerRoles: the admin-edited per-role config (recipient + delivery mode) for non-public roles.
// signerNotes: optional override for the Zoho request notes.
const [templateRoles, setTemplateRoles] = useState<TemplateRole[]>([]);
const [loadingRoles, setLoadingRoles] = useState(false);
const [signerRoles, setSignerRoles] = useState<Record<string, { recipientName: string; recipientEmail: string; deliveryMode: 'embedded' | 'email' }>>({});
const [signerNotes, setSignerNotes] = useState('');
// QR Code and Analytics states (legacy - keeping for compatibility)
const [qrCodes, setQrCodes] = useState<Map<string, string>>(new Map());
const [analytics, setAnalytics] = useState<Map<string, any>>(new Map());
const [loadingQR, setLoadingQR] = useState<Set<string>>(new Set());
const [loadingAnalytics, setLoadingAnalytics] = useState<Set<string>>(new Set());
const [analyticsTimeWindow, setAnalyticsTimeWindow] = useState<'day' | 'week' | 'month' | 'all'>('week');
// UX-01: Inline delete confirmation and copy-link feedback (replaces confirm() / alert())
const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [copiedLinkId, setCopiedLinkId] = useState<string | null>(null);
const [copiedEmbedId, setCopiedEmbedId] = useState<string | null>(null);
// Debounce flags to prevent infinite retry loops
const [credentialsFetchAttempted, setCredentialsFetchAttempted] = useState(false);
const [subscriptionFetchAttempted, setSubscriptionFetchAttempted] = useState(false);
const [formsFetchAttempted, setFormsFetchAttempted] = useState(false);
// Use refs for public form fetch tracking to avoid re-render loops
const fetchingFormBySlugRef = useRef(false);
const lastFetchedSlugRef = useRef<string | null>(null);
const analyticsTrackedRef = useRef<Set<string>>(new Set());
// Fetch analytics for a form
const fetchAnalytics = async (formId: string, window: string = analyticsTimeWindow) => {
if (!sessionToken) return;
// Prevent duplicate requests
if (loadingAnalytics.has(formId)) return;
setLoadingAnalytics(prev => new Set(prev).add(formId));
try {
const res = await fetch(`/api/analytics?formId=${formId}&window=${window}`, {
headers: { Authorization: `Bearer ${sessionToken}` }
});
if (res.ok) {
const data = await res.json();
setAnalytics(prev => new Map(prev).set(formId, data));
} else if (res.status === 404) {
// Form not found - set empty analytics
setAnalytics(prev => new Map(prev).set(formId, {
timeWindow: window,
summary: { totalVisits: 0, totalSubmissions: 0, conversionRate: 0 },
recentEvents: []
}));
}
} catch (e) {
console.error('Failed to fetch analytics:', e);
// Set empty analytics on error
setAnalytics(prev => new Map(prev).set(formId, {
timeWindow: window,
summary: { totalVisits: 0, totalSubmissions: 0, conversionRate: 0 },
recentEvents: []
}));
} finally {
setLoadingAnalytics(prev => {
const newSet = new Set(prev);
newSet.delete(formId);
return newSet;
});
}
};
// Fetch the roles defined in a Zoho Sign template so the admin can configure
// signers/delivery per role. Merges any saved signer_config into the editor.
const loadTemplateRoles = async (form: FormDefinition) => {
if (!sessionToken || !form.id) return;
setLoadingRoles(true);
try {
const result = await fetchTemplateRoles(form.id, sessionToken);
if (result.success && result.roles) {
setTemplateRoles(result.roles);
// Seed editor state from saved config (non-public roles only).
const saved = form.signerConfig;
const seeded: Record<string, { recipientName: string; recipientEmail: string; deliveryMode: 'embedded' | 'email' }> = {};
for (const role of result.roles) {
if (role.isPublic) continue;
const cfg = saved?.roles?.find(r => r.role.toLowerCase() === role.role.toLowerCase());
seeded[role.role] = {
recipientName: cfg?.recipientName || '',
recipientEmail: cfg?.recipientEmail || '',
deliveryMode: cfg?.deliveryMode || 'email',
};
}
setSignerRoles(seeded);
setSignerNotes(saved?.notes || '');
} else if (result.error) {
setError(result.error);
}
} finally {
setLoadingRoles(false);
}
};
const fetchForms = async (token: string) => {
if (formsFetchAttempted) {
return;
}
setFormsFetchAttempted(true);
try {
const res = await fetch('/api/forms', {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) {
if (res.status === 401) {
console.warn('Forms API unauthorized (401) - session may have expired');
// 401 is definitive — do not retry until the user re-authenticates.
} else {
// Transient error (5xx, network hiccup, etc.) — allow a future retry.
console.warn(`Forms API error (${res.status}) - will allow retry`);
setFormsFetchAttempted(false);
}
setForms([]);
return;
}
const data = await res.json();
setForms(data || []);
// Only hydrate known QR codes from existing form payload.
// Do not auto-generate or auto-fetch missing QR codes on login/dashboard load.
if (data && data.length > 0) {
setQrCodes(prev => {
const merged = new Map(prev);
for (const form of data) {
if (form?.id && form.qrCodeData) {
merged.set(form.id, form.qrCodeData);
}
}
return merged;
});
}
} catch (e) {
console.error('fetch forms error', e);
// Network failure/timeout can be transient — allow a future retry.
setFormsFetchAttempted(false);
setForms([]);
}
};
const fetchFormBySlug = async (slugVal: string) => {
// Use refs for guards to avoid stale closures and re-render loops
if (fetchingFormBySlugRef.current) {
return; // Prevent concurrent fetches
}
if (lastFetchedSlugRef.current === slugVal) {
setIsFormLoading(false);
return; // Already fetched this slug
}
fetchingFormBySlugRef.current = true;
setIsFormLoading(true);
try {
const res = await fetch(`/api/forms?slug=${encodeURIComponent(slugVal)}`);
if (res.status === 429) {
// Rate limited - show a message instead of 404
setError('Too many requests. Please try again later.');
setCurrentForm(null);
setView(ViewMode.NOT_FOUND);
return;
}
if (!res.ok) {
setCurrentForm(null);
setView(ViewMode.NOT_FOUND);
return;
}
const data = await res.json();
// Only mark as fetched after successful fetch
lastFetchedSlugRef.current = slugVal;
setCurrentForm(data);
setView(ViewMode.PUBLIC_FORM);
// Update browser history for proper back/forward navigation
if (window.location.pathname !== `/${slugVal}`) {
window.history.pushState({ slug: slugVal }, '', `/${slugVal}`);
}
} catch {
setCurrentForm(null);
setView(ViewMode.NOT_FOUND);
} finally {
fetchingFormBySlugRef.current = false;
setIsFormLoading(false);
}
};
const fetchCredentials = async (token: string) => {
if (credentialsFetchAttempted) {
return;
}
setCredentialsFetchAttempted(true);
try {
const res = await fetch('/api/credentials', { headers: { Authorization: `Bearer ${token}` } });
if (res.ok) {
const data: UserCredentials = await res.json();
setCredClientId(data.clientId || '');
setCredHasClientSecret(data.hasClientSecret || false);
setCredHasRefreshToken(data.hasRefreshToken || false);
setCredApiDomain(data.apiDomain || 'https://sign.zoho.com');
// Clear any previously entered "new value" inputs when refreshing from server
setCredNewClientSecret('');
setCredNewRefreshToken('');
} else if (res.status === 404) {
// 404 is expected - API endpoint doesn't exist yet
console.warn('Credentials API not implemented (404)');
}
} catch (e) {
// Silently handle network errors to prevent console spam
if (e instanceof TypeError && e.message === 'Failed to fetch') {
// Network error - likely API not available
console.warn('Credentials API unavailable - using defaults');
} else {
console.error('fetch credentials error', e);
}
} finally {
setCredentialsLoaded(true);
}
};
const saveCredentials = async () => {
if (!sessionToken) return;
const payload = {
clientId: credClientId.trim(),
// Only include secret/token if user explicitly entered a new value; omitting them
// tells the server to preserve the existing stored value (never overwrite with blank)
...(credNewClientSecret.trim() ? { clientSecret: credNewClientSecret.trim() } : {}),
...(credNewRefreshToken.trim() ? { refreshToken: credNewRefreshToken.trim() } : {}),
apiDomain: credApiDomain.trim() || 'https://sign.zoho.com'
};
const res = await fetch('/api/credentials', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${sessionToken}` },
body: JSON.stringify(payload)
});
if (!res.ok) {
const msg = await res.text();
setError(`Save credentials failed: ${msg}`);
return;
}
// Reset debounce flag and refetch
setCredentialsFetchAttempted(false);
await fetchCredentials(sessionToken);
};
const fetchSubscription = async (token: string) => {
if (subscriptionFetchAttempted) {
return;
}
setSubscriptionFetchAttempted(true);
try {
const res = await fetch('/api/subscription', { headers: { Authorization: `Bearer ${token}` } });
if (res.ok) {
const data: SubscriptionPlan = await res.json();
setSubscription(data);
} else if (res.status === 404) {
// 404 is expected - API endpoint doesn't exist yet
console.warn('Subscription API not implemented (404)');
}
} catch (e) {
// Silently handle network errors to prevent console spam
if (e instanceof TypeError && e.message === 'Failed to fetch') {
// Network error - likely API not available
console.warn('Subscription API unavailable - using defaults');
} else {
console.error('fetch subscription error', e);
}
} finally {
setSubscriptionLoaded(true);
}
};
const saveSubscription = async (plan: string, status: string, seats?: number) => {
if (!sessionToken) return;
const res = await fetch('/api/subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${sessionToken}` },
body: JSON.stringify({ plan, status, seats })
});
if (!res.ok) {
const msg = await res.text();
setError(`Save subscription failed: ${msg}`);
return;
}
// Reset debounce flag and refetch
setSubscriptionFetchAttempted(false);
await fetchSubscription(sessionToken);
};
useEffect(() => {
const resolveRoute = () => {
// Don't resolve routes until auth check is complete to prevent flickering
if (!isRouteResolved) {
return;
}
const hash = window.location.hash || '';
const path = window.location.pathname || '/';
// Handle path-based form URLs (e.g., /formslug)
if (path !== '/' && !path.startsWith('/api')) {
const slugVal = path.substring(1).replace(/\/$/, '');
// Validate slug format
if (!isValidSlug(slugVal)) {
setCurrentForm(null);
setView(ViewMode.NOT_FOUND);
return;
}
// For public forms, fetch by slug using ref-based guards
// The guards are in fetchFormBySlug itself, so just call it
if (slugVal && isRouteResolved) {
fetchFormBySlug(slugVal);
} else if (!isRouteResolved) {
// Wait for initial load to complete
setView(ViewMode.PUBLIC_FORM);
}
return;
} else if (hash.startsWith('#/admin/signup')) {
setAuthMode('signup');
setView(ViewMode.ADMIN_LOGIN);
window.location.hash = '#/admin/signup';
} else if (hash.startsWith('#/admin/login') || hash === '#/admin') {
setAuthMode('login');
setView(ViewMode.ADMIN_LOGIN);
window.location.hash = '#/admin/login';
} else if (hash.startsWith('#/admin/dashboard')) {
setView(ViewMode.ADMIN_DASHBOARD);
} else if (hash.startsWith('#/admin/settings')) {
setView(ViewMode.ADMIN_SETTINGS);
} else if (hash.startsWith('#/admin/form/')) {
// Extract form ID from hash (e.g., #/admin/form/123 -> 123)
const formId = hash.split('/').pop();
const form = forms.find(f => f.id === formId);
if (form && sessionToken) {
// Load form details without calling openFormDetails to avoid recursion
setSelectedFormId(formId);
setDetailsTab('settings');
// Load basic form settings into editor
setEditingId(form.id);
setFormName(form.name);
setTemplateId(form.templateId);
setRoleName(form.roleName);
setApiDomain(form.apiDomain || 'https://sign.zoho.com');
setSlug(form.slug);
// Load landing page config
const lc = form.landingConfig || {};
setLandingHeadline(lc.headline || '');
setLandingDescription(lc.description || '');
setLandingLogoUrl(lc.logoUrl || '');
setLandingLogoAlt(lc.logoAlt || '');
setLandingPrimaryColor(lc.theme?.primaryColor || '#3B82F6');
setLandingBackgroundColor(lc.theme?.backgroundColor || '#F8FAFC');
setLandingCardColor(lc.theme?.cardColor || '#FFFFFF');
setLandingButtonText(lc.buttonText || 'Sign Now');
setLandingCompanyName(lc.contact?.companyName || '');
setLandingContactEmail(lc.contact?.email || '');
setLandingContactPhone(lc.contact?.phone || '');
setLandingFooterText(lc.footerText || '');
setLandingShowPoweredBy(lc.showPoweredBy !== false);
setError(null);
setView(ViewMode.FORM_DETAILS);
} else {
// Form not found or not authenticated, go to dashboard
setView(ViewMode.ADMIN_DASHBOARD);
window.location.hash = '#/admin/dashboard';
}
} else {
if (hash !== '') {
window.location.hash = '';
}
setView(ViewMode.LANDING);
}
};
window.addEventListener('hashchange', resolveRoute);
window.addEventListener('popstate', resolveRoute);
const init = async () => {
const path = window.location.pathname || '/';
const hash = window.location.hash || '';
const isPublicForm = path !== '/' && !path.startsWith('/api') && !path.startsWith('/qr/');
const isAdminPage = hash.startsWith('#/admin');
const isLandingPage = path === '/' && !isAdminPage;
// For public form pages, fetch the form immediately without waiting for auth
if (isPublicForm) {
const slugVal = path.substring(1).replace(/\/$/, '');
if (isValidSlug(slugVal)) {
// Start fetching the form right away
fetchFormBySlug(slugVal);
} else {
setCurrentForm(null);
setView(ViewMode.NOT_FOUND);
setIsFormLoading(false);
}
// Auth check runs in background for public forms (non-blocking)
supabase.auth.getSession().then(({ data }) => {
if (data.session) {
setSessionToken(data.session.access_token);
setUserId(data.session.user.id);
setAuth({ username: data.session.user.email || '', password: '' });
}
});
return;
}
// For landing page, auth check runs in background (non-blocking)
if (isLandingPage) {
supabase.auth.getSession().then(async ({ data }) => {
if (data.session) {
setSessionToken(data.session.access_token);
setUserId(data.session.user.id);
setAuth({ username: data.session.user.email || '', password: '' });
// Fetch admin data in background for logged-in users
await Promise.all([
fetchForms(data.session.access_token),
fetchCredentials(data.session.access_token),
fetchSubscription(data.session.access_token)
]);
}
});
return;
}
// For admin pages, wait for auth check before rendering
const { data } = await supabase.auth.getSession();
if (data.session) {
setSessionToken(data.session.access_token);
setUserId(data.session.user.id);
setAuth({ username: data.session.user.email || '', password: '' });
await Promise.all([
fetchForms(data.session.access_token),
fetchCredentials(data.session.access_token),
fetchSubscription(data.session.access_token)
]);
}
setIsRouteResolved(true);
// Now that auth check is complete, resolve the route
resolveRoute();
};
init();
const { data: listener } = supabase.auth.onAuthStateChange(async (_event, session) => {
if (session?.access_token) {
setSessionToken(session.access_token);
setUserId(session.user.id);
setAuth({ username: session.user.email || '', password: '' });
await Promise.all([
fetchForms(session.access_token),
fetchCredentials(session.access_token),
fetchSubscription(session.access_token)
]);
} else {
// User logged out - clear all state
setSessionToken(null);
setUserId(null);
setAuth(null);
setForms([]);
// Reset debounce flags to allow fresh fetches on next login
setFormsFetchAttempted(false);
setCredentialsFetchAttempted(false);
setSubscriptionFetchAttempted(false);
const hash = window.location.hash;
const path = window.location.pathname || '/';
// Allow access to login/signup pages, but redirect dashboard/settings
if (hash.startsWith('#/admin/dashboard') || hash.startsWith('#/admin/settings')) {
window.location.hash = '#/admin/login';
setView(ViewMode.ADMIN_LOGIN);
} else if (hash.startsWith('#/admin/login') || hash.startsWith('#/admin/signup') || hash === '#/admin') {
// Allow login/signup pages when not authenticated - don't change view
return;
} else if (path !== '/' && !path.startsWith('/api')) {
setView(ViewMode.PUBLIC_FORM);
} else if (hash === '' || hash === '/') {
// Only set to landing if we're actually on the root
setView(ViewMode.LANDING);
}
}
});
return () => {
window.removeEventListener('hashchange', resolveRoute);
window.removeEventListener('popstate', resolveRoute);
listener?.subscription.unsubscribe();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isRouteResolved]);
const handleAuthSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError(null);
try {
if (authMode === 'signup') {
const { data, error } = await supabase.auth.signUp({
email: usernameInput,
password: passwordInput
});
if (error) {
setError(error.message || 'Sign up failed');
setLoading(false);
return;
}
if (!data.session) {
setError('Check your email to confirm your account, then log in.');
setLoading(false);
setAuthMode('login');
return;
}
setSessionToken(data.session.access_token);
setUserId(data.session.user.id);
setAuth({ username: usernameInput, password: '' });
window.location.hash = '#/admin/dashboard';
setView(ViewMode.ADMIN_DASHBOARD);
await fetchForms(data.session.access_token);
await fetchCredentials(data.session.access_token);
await fetchSubscription(data.session.access_token);
} else {
const { data, error } = await supabase.auth.signInWithPassword({
email: usernameInput,
password: passwordInput
});
if (error || !data.session) {
setError(error?.message || 'Login failed');
setLoading(false);
return;
}
setSessionToken(data.session.access_token);
setUserId(data.session.user.id);
setAuth({ username: usernameInput, password: '' });
window.location.hash = '#/admin/dashboard';
setView(ViewMode.ADMIN_DASHBOARD);
await fetchForms(data.session.access_token);
await fetchCredentials(data.session.access_token);
await fetchSubscription(data.session.access_token);
}
} catch (err: any) {
console.error('Auth error', err);
setError(err?.message || 'Network error (failed to reach Supabase)');
} finally {
setLoading(false);
}
};
const clearForm = () => {
setEditingId(null);
setFormName('');
setTemplateId('');
setRoleName('Signer 1');
setApiDomain('https://sign.zoho.com');
setSlug('');
setError(null);
// Clear landing page customization fields
setLandingHeadline('');
setLandingDescription('');
setLandingLogoUrl('');
setLandingLogoAlt('');
setLandingPrimaryColor('#3B82F6');
setLandingBackgroundColor('#F8FAFC');
setLandingCardColor('#FFFFFF');
setLandingButtonText('Sign Now');
setLandingCompanyName('');
setLandingContactEmail('');
setLandingContactPhone('');
setLandingFooterText('');
setLandingShowPoweredBy(true);
// Clear accessibility errors
setContrastWarning(null);
setAltTextError(null);
// Clear signers & delivery state
setTemplateRoles([]);
setSignerRoles({});
setSignerNotes('');
};
const startEdit = (form: FormDefinition) => {
setEditingId(form.id);
setFormName(form.name);
setTemplateId(form.templateId);
setRoleName(form.roleName);
setApiDomain(form.apiDomain || 'https://sign.zoho.com');
setSlug(form.slug);
setError(null);
};
// Open the form details page with all settings loaded
const openFormDetails = (form: FormDefinition) => {
setSelectedFormId(form.id);
setDetailsTab('settings');
// Load basic form settings into editor
setEditingId(form.id);
setFormName(form.name);
setTemplateId(form.templateId);
setRoleName(form.roleName);
setApiDomain(form.apiDomain || 'https://sign.zoho.com');
setSlug(form.slug);
// Load landing page config
const lc = form.landingConfig || {};
setLandingHeadline(lc.headline || '');
setLandingDescription(lc.description || '');
setLandingLogoUrl(lc.logoUrl || '');
setLandingLogoAlt(lc.logoAlt || '');
setLandingPrimaryColor(lc.theme?.primaryColor || '#3B82F6');
setLandingBackgroundColor(lc.theme?.backgroundColor || '#F8FAFC');
setLandingCardColor(lc.theme?.cardColor || '#FFFFFF');
setLandingButtonText(lc.buttonText || 'Sign Now');
setLandingCompanyName(lc.contact?.companyName || '');
setLandingContactEmail(lc.contact?.email || '');
setLandingContactPhone(lc.contact?.phone || '');
setLandingFooterText(lc.footerText || '');
setLandingShowPoweredBy(lc.showPoweredBy !== false);
// Reset signers & delivery state; roles are loaded on-demand when the tab is opened.
setTemplateRoles([]);
setSignerNotes(form.signerConfig?.notes || '');
const seeded: Record<string, { recipientName: string; recipientEmail: string; deliveryMode: 'embedded' | 'email' }> = {};
for (const r of form.signerConfig?.roles || []) {
if (r.isPublic) continue;
seeded[r.role] = {
recipientName: r.recipientName || '',
recipientEmail: r.recipientEmail || '',
deliveryMode: r.deliveryMode || 'email',
};
}
setSignerRoles(seeded);
setError(null);
setView(ViewMode.FORM_DETAILS);
window.location.hash = `#/admin/form/${form.id}`;
};
// Get the currently selected form object
const getSelectedForm = (): FormDefinition | undefined => {
return forms.find(f => f.id === selectedFormId);
};
const saveForm = async (e: React.FormEvent) => {
e.preventDefault();
if (!sessionToken) {
setError('Not authenticated');
return;
}
if (loading) {
return; // Prevent multiple submissions
}
// Validate accessibility requirements
if (landingLogoUrl && !landingLogoAlt) {
setError('Please provide descriptive alt text for your logo (required for accessibility)');
setDetailsTab('landing');
return;
}
if (landingLogoAlt) {
const altValidation = validateAltText(landingLogoAlt);
if (!altValidation.valid) {
setError(`Logo alt text issue: ${altValidation.errors[0]}`);
setDetailsTab('landing');
return;
}
}
// Note: Contrast warnings are shown in real-time in the UI
// We allow saving even with contrast issues, but users are warned during editing
setLoading(true);
// Validate slug before saving
const trimmedSlug = slug.trim().toLowerCase();
if (!isValidSlug(trimmedSlug)) {
setError('Invalid slug. Use only lowercase letters, numbers, and hyphens. Avoid reserved words like "api", "admin", etc.');
setLoading(false);
return;
}
// Check for duplicate slugs (excluding current form if editing)
const duplicateSlug = forms.find(f => f.slug === trimmedSlug && f.id !== editingId);
if (duplicateSlug) {
setError(`Slug "${trimmedSlug}" is already in use. Please choose a different slug.`);
setLoading(false);
return;
}
// P2-03: For new forms, omit id — server generates it via gen_random_uuid().
// For updates (editingId is set), include id so the server routes to UPDATE path.
// Build signer/delivery config from the editor when roles have been loaded;
// otherwise preserve any existing config so saving from another tab doesn't wipe it.
const signerConfig = templateRoles.length > 0
? {
notes: signerNotes.trim() || undefined,
roles: templateRoles
.filter(r => !r.isPublic)
.map(r => {
const ed = signerRoles[r.role] || { recipientName: '', recipientEmail: '', deliveryMode: 'email' as const };
return {
role: r.role,
actionType: r.actionType,
recipientName: ed.recipientName.trim() || undefined,
recipientEmail: ed.recipientEmail.trim() || undefined,
deliveryMode: ed.deliveryMode,
isPublic: false,
};
}),
}
: currentForm?.signerConfig;
const formDef: FormDefinition = {
...(editingId ? { id: editingId } : {}),
name: formName.trim(),
slug: trimmedSlug,
templateId: templateId.trim(),
roleName: roleName.trim(),
apiDomain: apiDomain.trim(),
// userId and accessToken removed — server resolves ownership from JWT (P1-02 / P3-04)
createdAt: editingId ? (forms.find(f => f.id === editingId)?.createdAt || Date.now()) : Date.now(),
signerConfig,
// Include landing config if any values are set
landingConfig: (landingHeadline || landingDescription || landingLogoUrl || landingLogoAlt || landingCompanyName || landingContactEmail || landingContactPhone || landingFooterText || landingPrimaryColor !== '#3B82F6' || landingBackgroundColor !== '#F8FAFC' || landingCardColor !== '#FFFFFF' || landingButtonText !== 'Sign Now' || !landingShowPoweredBy) ? {
headline: landingHeadline || undefined,
description: landingDescription || undefined,
logoUrl: landingLogoUrl || undefined,
logoAlt: landingLogoAlt || undefined,
theme: (landingPrimaryColor !== '#3B82F6' || landingBackgroundColor !== '#F8FAFC' || landingCardColor !== '#FFFFFF') ? {
primaryColor: landingPrimaryColor !== '#3B82F6' ? landingPrimaryColor : undefined,
backgroundColor: landingBackgroundColor, // Always save to ensure it propagates
cardColor: landingCardColor !== '#FFFFFF' ? landingCardColor : undefined
} : undefined,
buttonText: landingButtonText !== 'Sign Now' ? landingButtonText : undefined,
contact: (landingCompanyName || landingContactEmail || landingContactPhone) ? {
companyName: landingCompanyName || undefined,
email: landingContactEmail || undefined,
phone: landingContactPhone || undefined
} : undefined,
footerText: landingFooterText || undefined,
showPoweredBy: landingShowPoweredBy
} : undefined
};
const res = await fetch('/api/forms', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${sessionToken}`
},
body: JSON.stringify(formDef)
});
if (!res.ok) {
const msg = await res.text();
if (res.status === 404) {
setError('Forms API not implemented yet. Please contact administrator.');
} else {
setError(`Save failed: ${msg}`);
}
setLoading(false);
return;
}
const saved = await res.json();
// P2-03: For new forms, saved.id comes from the server (DB-generated UUID).
// Update editingId to the server-assigned id so subsequent edits go to UPDATE path.
if (!editingId && saved.id) {
setEditingId(saved.id);
}
let updated = editingId ? forms.map(f => f.id === editingId ? saved : f) : [...forms, saved];
setForms(updated);
// Determine if we're currently viewing this form's details
const isViewingSavedForm = selectedFormId === (editingId || saved.id);
// If we're viewing this form's details, update currentForm and the editor state
if (isViewingSavedForm) {
setCurrentForm(saved);
const lc = saved.landingConfig || {};
// Ensure editor stays bound to the saved form and reflect latest values
setEditingId(saved.id);
setFormName(saved.name || '');
setTemplateId(saved.templateId || '');
setRoleName(saved.roleName || 'Signer 1');
setApiDomain(saved.apiDomain || 'https://sign.zoho.com');
setSlug(saved.slug || '');
setLandingHeadline(lc.headline || '');
setLandingDescription(lc.description || '');
setLandingLogoUrl(lc.logoUrl || '');
setLandingLogoAlt(lc.logoAlt || '');
setLandingPrimaryColor(lc.theme?.primaryColor || '#3B82F6');
setLandingBackgroundColor(lc.theme?.backgroundColor || '#F8FAFC');
setLandingCardColor(lc.theme?.cardColor || '#FFFFFF');
setLandingButtonText(lc.buttonText || 'Sign Now');
setLandingCompanyName(lc.contact?.companyName || '');
setLandingContactEmail(lc.contact?.email || '');
setLandingContactPhone(lc.contact?.phone || '');
setLandingFooterText(lc.footerText || '');
setLandingShowPoweredBy(lc.showPoweredBy !== false);
// Refresh signers & delivery editor from the saved config. Roles list is
// kept as-is (already loaded); only the per-role edits are re-seeded.
setSignerNotes(saved.signerConfig?.notes || '');
const reseeded: Record<string, { recipientName: string; recipientEmail: string; deliveryMode: 'embedded' | 'email' }> = {};
for (const r of saved.signerConfig?.roles || []) {
if (r.isPublic) continue;
reseeded[r.role] = {
recipientName: r.recipientName || '',
recipientEmail: r.recipientEmail || '',