PROJECT OVERVIEW:
EcoGuard AI is a sophisticated SaaS platform designed to monitor, analyze, and report on environmental regulatory exemptions, particularly those granted under national security or economic pretexts. The core problem it addresses is the lack of transparency and accessible analysis regarding how these exemptions impact endangered species and delicate ecosystems. The platform uses AI to assess the potential risks associated with these exemptions, providing data-driven insights to environmental organizations, researchers, policymakers, and the public. The primary value proposition is to offer a centralized, intelligent, and transparent system for tracking and understanding the consequences of environmental deregulation.
TECH STACK:
- Frontend: React (Next.js App Router) for a modern, server-rendered application with excellent performance and SEO.
- Styling: Tailwind CSS for rapid, utility-first styling and consistent design.
- ORM: Drizzle ORM for type-safe, efficient database interactions with PostgreSQL.
- Database: PostgreSQL, a robust relational database.
- Authentication: NextAuth.js for secure and flexible authentication (e.g., email/password, Google, GitHub OAuth).
- UI Components: shadcn/ui for a collection of accessible, reusable, and customizable UI components built with Radix UI and styled with Tailwind CSS.
- Data Fetching: React Query (or TanStack Query) for efficient server-state management, caching, and background updates.
- Charting: Chart.js or Recharts for interactive data visualizations.
- State Management: Zustand or Jotai for lightweight global state management where needed.
- Deployment: Vercel or a similar platform for seamless Next.js deployment.
- Other: Axios for HTTP requests, date-fns for date manipulation.
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. `users` table:
- `id` (UUID, primary key)
- `name` (TEXT)
- `email` (TEXT, unique)
- `emailVerified` (TIMESTAMP with time zone, optional)
- `image` (TEXT, optional)
- `createdAt` (TIMESTAMP with time zone, default: now())
- `updatedAt` (TIMESTAMP with time zone, default: now())
2. `accounts` table (for NextAuth.js):
- `id` (BIGSERIAL, primary key)
- `userId` (UUID, foreign key to `users.id`)
- `type` (TEXT)
- `provider` (TEXT)
- `providerAccountId` (TEXT)
- `refresh_token` (TEXT, optional)
- `access_token` (TEXT, optional)
- `expires_at` (BIGINT, optional)
- `token_type` (TEXT, optional)
- `scope` (TEXT, optional)
- `id_token` (TEXT, optional)
- `session_state` (TEXT, optional)
3. `sessions` table (for NextAuth.js):
- `id` (BIGSERIAL, primary key)
- `sessionToken` (TEXT, unique)
- `userId` (UUID, foreign key to `users.id`)
- `expires` (TIMESTAMP with time zone)
4. `verificationTokens` table (for NextAuth.js):
- `identifier` (TEXT)
- `token` (TEXT)
- `expires` (TIMESTAMP with time zone)
- PRIMARY KEY (`identifier`, `token`)
5. `exemptions` table:
- `id` (UUID, primary key, default: uuid_generate_v4())
- `title` (TEXT, not null)
- `source_url` (TEXT, not null)
- `source_description` (TEXT)
- `date_issued` (DATE)
- `issuing_authority` (TEXT)
- `justification_basis` (TEXT) // e.g., 'National Security', 'Economic Stability'
- `affected_region` (TEXT)
- `status` (VARCHAR(50)) // e.g., 'Active', 'Expired', 'Under Review'
- `created_by` (UUID, foreign key to `users.id`, optional)
- `createdAt` (TIMESTAMP with time zone, default: now())
- `updatedAt` (TIMESTAMP with time zone, default: now())
6. `species` table:
- `id` (UUID, primary key, default: uuid_generate_v4())
- `scientific_name` (TEXT, unique, not null)
- `common_name` (TEXT)
- `conservation_status` (VARCHAR(50)) // e.g., 'Endangered', 'Critically Endangered', 'Vulnerable'
- `description` (TEXT, optional)
- `image_url` (TEXT, optional)
7. `exemption_species_impact` table (Junction table):
- `exemption_id` (UUID, foreign key to `exemptions.id`)
- `species_id` (UUID, foreign key to `species.id`)
- `risk_level` (VARCHAR(50)) // e.g., 'High', 'Medium', 'Low', 'Unknown'
- `ai_assessment_notes` (TEXT, optional) // AI generated notes on the specific impact
- `last_assessed_at` (TIMESTAMP with time zone, optional)
- PRIMARY KEY (`exemption_id`, `species_id`)
8. `ecosystems` table:
- `id` (UUID, primary key, default: uuid_generate_v4())
- `name` (TEXT, unique, not null)
- `region` (TEXT)
- `description` (TEXT, optional)
9. `exemption_ecosystem_impact` table (Junction table):
- `exemption_id` (UUID, foreign key to `exemptions.id`)
- `ecosystem_id` (UUID, foreign key to `ecosystems.id`)
- `risk_level` (VARCHAR(50)) // e.g., 'High', 'Medium', 'Low', 'Unknown'
- `ai_assessment_notes` (TEXT, optional) // AI generated notes on the specific impact
- `last_assessed_at` (TIMESTAMP with time zone, optional)
- PRIMARY KEY (`exemption_id`, `ecosystem_id`)
10. `reports` table:
- `id` (UUID, primary key, default: uuid_generate_v4())
- `user_id` (UUID, foreign key to `users.id`)
- `title` (TEXT, not null)
- `report_type` (VARCHAR(50)) // e.g., 'Species Impact', 'Ecosystem Impact', 'Exemption Summary'
- `parameters` (JSONB) // Store filters used for report generation
- `generated_at` (TIMESTAMP with time zone, default: now())
- `file_url` (TEXT, optional) // URL to the generated report file (e.g., PDF)
CORE FEATURES & USER FLOW:
1. Authentication:
- User Registration: Users can sign up using email/password or OAuth providers (Google, GitHub).
- User Login: Secure login via chosen method.
- Password Reset: Standard password recovery flow.
- OAuth Integration: Seamless onboarding via Google/GitHub.
- User Profile: View and edit basic profile information.
- Authorization: Role-based access control (e.g., Admin, Basic User) to be implemented later, MVP focuses on authenticated users.
2. Exemption Monitoring & Display:
- Data Ingestion: Backend process (or manual upload initially) to populate the `exemptions` table from reliable sources (news APIs, government portals, academic databases).
- List View: Display all tracked exemptions in a sortable, filterable table (`/dashboard/exemptions`). Columns: Title, Source, Date Issued, Issuing Authority, Status, Affected Region.
- Detail View: Clicking an exemption shows its full details, including source URL and justification. (`/dashboard/exemptions/[id]`).
- Search Functionality: Ability to search exemptions by title, keywords, or issuing authority.
3. AI-Powered Impact Analysis:
- Species Impact Assessment: When an exemption is added or updated, an AI service (integrated via API) analyzes its potential impact on listed endangered species. It estimates a `risk_level` ('High', 'Medium', 'Low', 'Unknown') and generates `ai_assessment_notes` for the `exemption_species_impact` table.
- Ecosystem Impact Assessment: Similar AI analysis for potential impacts on defined ecosystems, populating `exemption_ecosystem_impact`.
- Triggering Analysis: Analysis can be triggered manually on demand or automatically upon new exemption entry/update.
- Displaying Analysis: Within the Exemption Detail View, show the assessed species and ecosystems, their risk levels, and AI notes.
4. Reporting & Visualization:
- Dashboard Overview: A main dashboard (`/dashboard`) showing key metrics: total exemptions, exemptions by status, top affected species/ecosystems, recent activity.
- Interactive Charts: Visualize trends, risk distributions (e.g., pie chart of risk levels for species), and geographical hotspots.
- Report Generation: Users can navigate to `/dashboard/reports` to create custom reports. Filters: Date range, Region, Species, Ecosystem, Justification Type, Risk Level. User selects parameters, clicks 'Generate Report'. A background job creates a PDF/CSV, stores it, and provides a download link. The report configuration is saved in the `reports` table.
- Data Export: Option to export filtered data from list views in CSV format.
API & DATA FETCHING:
- RESTful API design using Next.js API routes (App Router handlers).
- Data Fetching Strategy: Primarily use React Query (TanStack Query) on the client-side for fetching data from the API routes. Server components will fetch data directly where appropriate.
- Key API Endpoints:
- `GET /api/exemptions`: Fetch list of exemptions with pagination, sorting, and filtering.
- `GET /api/exemptions/[id]`: Fetch details for a single exemption.
- `POST /api/exemptions`: Create a new exemption (Admin/Internal use).
- `PUT /api/exemptions/[id]`: Update an exemption (Admin/Internal use).
- `GET /api/species`: Fetch list of species with filtering.
- `GET /api/species/[id]`: Fetch details for a single species.
- `GET /api/ecosystems`: Fetch list of ecosystems.
- `GET /api/reports`: Fetch user's generated reports.
- `POST /api/reports`: Trigger report generation with specified parameters.
- `GET /api/auth/session`: Get current user session (handled by NextAuth.js).
- Request/Response Bodies:
- Use JSON for request/response bodies.
- Standardize responses with `data` and `error` fields.
- Example (GET /api/exemptions): `{ "data": [ { "id": "...", "title": "...", ... } ], "pagination": { "total": 100, "pageSize": 10, "currentPage": 1 } }`
- Example (POST /api/reports): `{ "status": "generating", "reportId": "..." }`
COMPONENT BREAKDOWN (Next.js App Router):
- `app/layout.tsx`: Root layout, global providers, Head component.
- `app/page.tsx`: Landing Page (Marketing - not part of MVP functionality, but needed for structure).
- `app/(auth)/layout.tsx`: Layout for auth pages.
- `app/(auth)/login/page.tsx`: Login form component.
- `app/(auth)/signup/page.tsx`: Registration form component.
- `app/(auth)/reset-password/page.tsx`: Password reset form.
- `app/(protected)/layout.tsx`: Main protected layout, includes Sidebar and Header.
- `app/(protected)/dashboard/page.tsx`: Dashboard overview page. Displays summary cards, charts.
- Components: `DashboardHeader`, `SummaryCard`, `ImpactChart`, `ExemptionStatusPieChart`, `RecentActivityFeed`.
- `app/(protected)/dashboard/exemptions/page.tsx`: Exemption list page.
- Components: `ExemptionTable` (with sorting, filtering, pagination), `SearchInput`, `FilterDropdowns`.
- `app/(protected)/dashboard/exemptions/[id]/page.tsx`: Exemption detail page.
- Components: `ExemptionDetailsCard`, `SpeciesImpactTable`, `EcosystemImpactTable`, `AIAnalysisNotes`, `GenerateReportButton`.
- `app/(protected)/dashboard/species/page.tsx`: Species list page (optional for MVP, could be combined).
- `app/(protected)/dashboard/reports/page.tsx`: Report generation and history page.
- Components: `ReportGeneratorForm`, `ReportHistoryTable`.
- `app/(protected)/settings/page.tsx`: User profile and settings page.
- Components: `ProfileForm`, `AccountSettings`.
- `components/ui/`: Reusable UI components from shadcn/ui (Button, Input, Card, Table, Sheet, Dialog, etc.).
- `components/layout/`: `Sidebar`, `Header`, `Footer`.
- `components/charts/`: Wrapper components for Chart.js/Recharts.
- `components/forms/`: Custom form components (`ExemptionForm`, `ReportForm`).
- `lib/`: Utility functions, API client setup, AI service wrappers.
- `hooks/`: Custom React hooks (e.g., `useDebounce`).
- `contexts/` or `store/`: State management (if Zustand/Jotai is used).
State Management:
- Server State: Primarily managed by React Query (TanStack Query) for API data.
- Global UI State: Use Zustand/Jotai for things like sidebar open/closed state, modal visibility, UI notifications.
- Local Component State: Use `useState` for form inputs, temporary UI states.
UI/UX DESIGN & VISUAL IDENTITY:
- Design Style: Clean, Modern, Data-Focused. Emphasis on readability and clear information hierarchy.
- Color Palette:
- Primary: `#007bff` (Energetic Blue)
- Secondary: `#6c757d` (Neutral Gray)
- Accent: `#28a745` (Success Green) / `#dc3545` (Danger Red) for status indicators.
- Background: `#f8f9fa` (Light Gray)
- Text: `#212529` (Dark Gray)
- Dark Mode Accent: `#0d6efd` (Slightly Brighter Blue)
- Dark Mode Background: `#121212` (Very Dark Gray)
- Typography:
- Headings: Inter (e.g., Inter-Bold, 24px for H1)
- Body Text: Inter (e.g., Inter-Regular, 16px)
- Layout:
- Sidebar Navigation on the left.
- Main content area takes up the rest of the space.
- Use of cards for organizing information blocks.
- Consistent padding and margins.
- Responsive Design:
- Mobile-first approach.
- Use Tailwind's responsive modifiers (sm:, md:, lg:, xl:).
- Sidebar collapses into a hamburger menu on smaller screens.
- Tables should be responsive (e.g., horizontal scroll, or stacked rows).
- Visual Elements: Subtle use of gradients in headers or cards, clean icons, clear data visualization.
ANIMATIONS:
- Page Transitions: Smooth fade-in/out transitions between pages using Next.js's built-in router or a library like `Framer Motion` (if needed, keep it minimal for MVP).
- Button Hovers: Subtle background color change or slight scaling effect on buttons.
- Loading States: Skeleton loaders or spinners (`react-spinners` or shadcn/ui's `Progress` component) for data fetching, with overlays.
- Table Row Transitions: Smooth expand/collapse animations for expandable rows if implemented.
- Fade-in animations for new elements appearing on the screen.
EDGE CASES:
- Empty States: Display user-friendly messages and potentially call-to-action buttons when lists (exemptions, reports, species) are empty (e.g., 'No exemptions found. Add one to get started.').
- Authentication Flow:
- Redirect to login if accessing protected routes while unauthenticated.
- Redirect to dashboard after successful login.
- Handle OAuth callback errors gracefully.
- Error Handling:
- Global error boundary component to catch unexpected errors.
- Specific error messages for API failures (e.g., 'Failed to load exemptions. Please try again later.').
- Display inline error messages for form validation.
- Form Validation:
- Client-side validation using libraries like Zod with React Hook Form for immediate user feedback.
- Server-side validation in API routes to ensure data integrity.
- API Rate Limiting: Implement if external APIs are heavily used or if self-hosted.
- Data Consistency: Ensure data integrity between `exemptions`, `species`, and the impact junction tables.
- AI Service Failures: Gracefully handle cases where the AI analysis service is unavailable or returns an error. Display 'Analysis Pending' or 'Analysis Unavailable'.
SAMPLE/MOCK DATA:
1. Exemption Mock Data:
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"title": "Gulf of Mexico Oil Drilling Expansion",
"source_url": "https://example.com/gulf-drilling-news",
"date_issued": "2026-03-30",
"issuing_authority": "Department of Interior",
"justification_basis": "National Security",
"affected_region": "Gulf of Mexico",
"status": "Active"
}
2. Species Mock Data:
{
"id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"scientific_name": "Balaenoptera ricei",
"common_name": "Rice's Whale",
"conservation_status": "Endangered",
"image_url": "https://example.com/images/rices_whale.jpg"
}
3. Exemption Species Impact Mock Data:
{
"exemption_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"species_id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210",
"risk_level": "High",
"ai_assessment_notes": "Increased ship traffic and potential for seismic surveys pose significant threats to vocalization and feeding grounds."
}
4. Ecosystem Mock Data:
{
"id": "1a2b3c4d-5e6f-7890-abcd-ef1234567890",
"name": "Coral Reef System - Florida Keys",
"region": "South Florida"
}
5. Exemption Ecosystem Impact Mock Data:
{
"exemption_id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"ecosystem_id": "1a2b3c4d-5e6f-7890-abcd-ef1234567890",
"risk_level": "Medium",
"ai_assessment_notes": "Potential for increased pollution runoff and physical disturbance from increased activity."
}
6. User Mock Data:
{
"id": "c1d2e3f4-a5b6-7890-fedc-ba9876543210",
"name": "Dr. Aris Thorne",
"email": "aris.thorne@ecoaudits.org"
}
7. Report Mock Data:
{
"id": "98765432-10fe-dcba-9876-543210fedcba",
"user_id": "c1d2e3f4-a5b6-7890-fedc-ba9876543210",
"title": "Rice's Whale Impact Analysis - Q2 2026",
"report_type": "Species Impact",
"generated_at": "2026-04-15T10:30:00Z",
"file_url": "/reports/rice_whale_q2_2026.pdf"
}
8. Another Exemption Mock Data:
{
"id": "b2c3d4e5-f6a7-8901-2345-67890abcdef1",
"title": "Offshore Wind Farm Construction - Mid-Atlantic",
"source_url": "https://example.com/offshore-wind-permit",
"date_issued": "2026-01-15",
"issuing_authority": "Bureau of Ocean Energy Management",
"justification_basis": "Economic Development",
"affected_region": "Mid-Atlantic Bight",
"status": "Active"
}
9. Mock Species for Offshore Wind:
{
"id": "d1e2f3a4-b5c6-7890-abcd-ef1234567890",
"scientific_name": "Eubalaena glacialis",
"common_name": "North Atlantic Right Whale",
"conservation_status": "Critically Endangered",
"image_url": "https://example.com/images/narw.jpg"
}
10. Mock Exemption-Species Impact for Offshore Wind:
{
"exemption_id": "b2c3d4e5-f6a7-8901-2345-67890abcdef1",
"species_id": "d1e2f3a4-b5c6-7890-abcd-ef1234567890",
"risk_level": "High",
"ai_assessment_notes": "Construction noise, vessel traffic, and potential for entanglement pose severe risks to calving and migratory patterns."
}