()
| 57 | } |
| 58 | |
| 59 | export default function OrganizationAnalyticsPage() { |
| 60 | const { data: session, status } = useSession() |
| 61 | const params = useParams() ?? {} |
| 62 | const router = useRouter() |
| 63 | const orgSlug = (params.slug ?? '') as string |
| 64 | |
| 65 | const [analytics, setAnalytics] = useState<AnalyticsData | null>(null) |
| 66 | const [analyticsLoading, setAnalyticsLoading] = useState(true) |
| 67 | const [analyticsError, setAnalyticsError] = useState<string | null>(null) |
| 68 | |
| 69 | // Use the custom hook for organization data |
| 70 | const { organization, isLoading, error } = useOrganizationData(orgSlug) |
| 71 | |
| 72 | useEffect(() => { |
| 73 | if (organization) { |
| 74 | fetchAnalytics() |
| 75 | } |
| 76 | }, [organization]) |
| 77 | |
| 78 | const fetchAnalytics = async () => { |
| 79 | if (!organization) return |
| 80 | |
| 81 | try { |
| 82 | setAnalyticsLoading(true) |
| 83 | const response = await fetch(`/api/orgs/${organization.id}/analytics`) |
| 84 | |
| 85 | if (!response.ok) { |
| 86 | const error = await response.json() |
| 87 | throw new Error(error.error || 'Failed to fetch analytics') |
| 88 | } |
| 89 | |
| 90 | const data = await response.json() |
| 91 | setAnalytics(data) |
| 92 | } catch (error) { |
| 93 | console.error('Error fetching analytics:', error) |
| 94 | setAnalyticsError( |
| 95 | error instanceof Error ? error.message : 'Failed to load analytics', |
| 96 | ) |
| 97 | } finally { |
| 98 | setAnalyticsLoading(false) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | const exportData = async (format: 'csv' | 'json') => { |
| 103 | if (!organization) return |
| 104 | |
| 105 | try { |
| 106 | const response = await fetch( |
| 107 | `/api/orgs/${organization.id}/analytics/export?format=${format}`, |
| 108 | ) |
| 109 | |
| 110 | if (!response.ok) { |
| 111 | throw new Error('Failed to export data') |
| 112 | } |
| 113 | |
| 114 | const blob = await response.blob() |
| 115 | const url = window.URL.createObjectURL(blob) |
| 116 | const a = document.createElement('a') |
nothing calls this directly
no test coverage detected