You are tasked with building a fully functional, multi-page Next.js MVP application for 'Resilience Hub'. This application is designed to monitor, analyze, and predict potential failures in critical systems, drawing inspiration from NASA's fault-tolerant systems used in the Artemis II mission. The goal is to provide a proactive platform for organizations managing high-risk operations to ensure maximum uptime and safety.
PROJECT OVERVIEW:
Resilience Hub is a SaaS platform that provides real-time monitoring, anomaly detection, predictive failure analysis, and automated remediation recommendations for critical infrastructure and high-stakes operations. It aims to solve the problem of unexpected system failures by identifying potential issues before they occur, thereby minimizing downtime, preventing costly accidents, and ensuring operational continuity. The core value proposition is 'proactive resilience for critical systems.'
TECH STACK:
- Framework: Next.js (App Router)
- Language: TypeScript
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- ORM: Drizzle ORM (with PostgreSQL as the database)
- Authentication: NextAuth.js (Credentials & Google Provider)
- State Management: React Context API / Zustand (for global state if needed)
- Data Fetching: Server Actions, Route Handlers, React Query (for client-side caching/fetching if necessary)
- Charting: Recharts or Chart.js
- Notification: Nodemailer (for email alerts), Twilio (for SMS alerts - optional for MVP)
- Deployment: Vercel
- Other: date-fns for date manipulation, zod for schema validation.
DATABASE SCHEMA (PostgreSQL with Drizzle ORM):
1. `users` table:
- `id` (uuid, primary key, default: uuid_generate_v4())
- `name` (text)
- `email` (text, unique, not null)
- `emailVerified` (timestamp with time zone)
- `image` (text) - for profile picture
- `hashedPassword` (text) - for credentials provider
- `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 on delete cascade)
- `type` (text)
- `provider` (text)
- `providerAccountId` (text)
- `refresh_token` (text)
- `access_token` (text)
- `expires_at` (bigint)
- `token_type` (text)
- `scope` (text)
- `id_token` (text)
- `session_state` (text)
3. `sessions` table (for NextAuth.js):
- `sessionToken` (text, primary key)
- `userId` (uuid, foreign key to users.id on delete cascade)
- `expires` (timestamp with time zone, not null)
4. `verificationTokens` table (for NextAuth.js):
- `identifier` (text)
- `token` (text, primary key)
- `expires` (timestamp with time zone, not null)
5. `organizations` table:
- `id` (uuid, primary key, default: uuid_generate_v4())
- `name` (text, not null)
- `ownerId` (uuid, foreign key to users.id on delete set null) - The user who created the organization
- `createdAt` (timestamp with time zone, default: now())
- `updatedAt` (timestamp with time zone, default: now())
6. `organizationMembers` table (Many-to-Many relationship between users and organizations):
- `userId` (uuid, foreign key to users.id on delete cascade)
- `organizationId` (uuid, foreign key to organizations.id on delete cascade)
- `role` (enum: 'admin', 'member'), default: 'member'
- `joinedAt` (timestamp with time zone, default: now())
- Primary Key: (`userId`, `organizationId`)
7. `systems` table (Represents critical systems being monitored):
- `id` (uuid, primary key, default: uuid_generate_v4())
- `organizationId` (uuid, foreign key to organizations.id on delete cascade)
- `name` (text, not null)
- `type` (text, e.g., 'Power Grid', 'Server Farm', 'Aerospace Control')
- `description` (text)
- `status` (enum: 'normal', 'warning', 'critical', 'offline'), default: 'normal'
- `lastCheckIn` (timestamp with time zone)
- `createdAt` (timestamp with time zone, default: now())
- `updatedAt` (timestamp with time zone, default: now())
8. `metrics` table (Individual data points or sensors from a system):
- `id` (uuid, primary key, default: uuid_generate_v4())
- `systemId` (uuid, foreign key to systems.id on delete cascade)
- `name` (text, e.g., 'CPU Usage', 'Temperature', 'Pressure', 'Transaction Rate')
- `unit` (text, e.g., '%', '°C', 'PSI', 'TPS')
- `currentValue` (numeric)
- `timestamp` (timestamp with time zone, not null)
- `alertThresholdHigh` (numeric)
- `alertThresholdLow` (numeric)
- `warningThresholdHigh` (numeric)
- `warningThresholdLow` (numeric)
- `createdAt` (timestamp with time zone, default: now())
9. `alerts` table (Records of triggered alerts):
- `id` (uuid, primary key, default: uuid_generate_v4())
- `systemId` (uuid, foreign key to systems.id on delete cascade)
- `metricId` (uuid, foreign key to metrics.id on delete set null)
- `level` (enum: 'warning', 'critical'), not null
- `message` (text, not null)
- `triggeredAt` (timestamp with time zone, default: now())
- `resolvedAt` (timestamp with time zone)
- `status` (enum: 'open', 'closed'), default: 'open'
10. `predictions` table (AI-generated failure predictions):
- `id` (uuid, primary key, default: uuid_generate_v4())
- `systemId` (uuid, foreign key to systems.id on delete cascade)
- `metricId` (uuid, foreign key to metrics.id on delete set null)
- `predictionTimestamp` (timestamp with time zone, not null) - When the failure is predicted to occur
- `confidence` (numeric, 0-1)
- `severity` (enum: 'low', 'medium', 'high'), not null
- `details` (text) - Explanation of the prediction
- `generatedAt` (timestamp with time zone, default: now())
CORE FEATURES & USER FLOW:
1. **Authentication (Sign Up/Sign In)**:
- Flow: User visits the landing page -> Clicks 'Sign Up' or 'Sign In' -> Redirected to Auth page -> Enters credentials (email/password) or uses Google Sign-In -> On successful login, redirected to Dashboard.
- Auth Page Components: Sign-Up Form (Name, Email, Password, Confirm Password), Sign-In Form (Email, Password), Google Sign-In Button.
- Backend: NextAuth.js handles session management, credential verification, and OAuth flow.
- Validation: Zod used for client and server-side validation of forms.
- Edge Case: Password reset flow (forgot password email link).
2. **Organization Management**:
- Flow: After login, user can create a new organization or join an existing one. If they create one, they become the 'admin'. They can invite other users (via email) who then receive an invitation.
- Components: Organization Creation Modal, Organization Settings Page (list members, invite new members, change roles, leave organization).
- Backend: Server Actions to create/update organizations and manage membership (`organizations` and `organizationMembers` tables).
- Edge Case: Handling user invitations and role assignments.
3. **System & Metric Monitoring Dashboard**:
- Flow: Logged-in user selects an organization -> Navigates to the Dashboard -> Sees a list of monitored 'Systems' -> Clicks on a system to view its 'Metrics' and current status.
- Dashboard Page: Displays a list/cards of systems with their current status indicator (green/yellow/red). Shows alerts count.
- System Detail Page: Shows real-time charts (Recharts) for key metrics (`metrics` table). Displays current metric values, thresholds, and recent alerts.
- Backend: API routes/Server Actions to fetch systems and their latest metrics for the selected organization.
- UI/UX: Clean, clear data visualization. Real-time updates via polling or WebSockets (polling for MVP).
- Edge Case: Displaying systems with no active metrics or alerts. Handling empty states.
4. **Anomaly Detection & Alerting**:
- Flow: The system continuously ingests data (simulated for MVP, actual integration later). An AI model (or rule-based system for MVP) analyzes incoming `metrics` data against defined thresholds and historical patterns.
- If an anomaly is detected (value outside thresholds or significant deviation from trend), an entry is created in the `alerts` table.
- The system's status in the `systems` table is updated accordingly.
- Alerts page: Lists all open and closed alerts, filterable by system, level, and status.
- Notification Trigger: When a new 'critical' alert is created, trigger an email notification to the organization's admins.
- Backend: Server Actions/API routes to process incoming data, detect anomalies, create alerts. Cron jobs or background tasks for periodic checks.
- Edge Case: Alert fatigue (avoiding too many alerts), alert resolution workflow.
5. **Predictive Failure Analysis**:
- Flow: A separate AI model (or simplified logic for MVP) analyzes historical `metrics` data and active `alerts` to predict potential future failures.
- Predictions are stored in the `predictions` table.
- A dedicated 'Predictions' section on the System Detail Page shows upcoming predicted failures, their confidence, and severity.
- Backend: Background job (e.g., using a task queue like BullMQ if scaling, or a simple cron script for MVP) to run prediction models.
- Edge Case: Handling low-confidence predictions, model retraining requirements.
API & DATA FETCHING:
- Server Actions: Primary method for mutations (CRUD operations on systems, metrics, alerts, organizations, users) and protected data fetching within the App Router.
- Route Handlers (API routes): Used for specific API endpoints like webhook receivers or external integrations (if any).
- Data Fetching Strategy: Fetch data directly in Server Components where possible. Use Server Actions for form submissions and mutations. For client-side data that needs frequent updates or caching, consider React Query or simply re-fetching via Server Actions on relevant events.
- Request/Response: Standard JSON. Zod schemas for request/response validation.
- Example (Server Action for adding a metric):
```typescript
// In app/systems/[systemId]/actions.ts
'use server';
import { db } from '@/lib/db';
import { metrics } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { z } from 'zod';
const addMetricSchema = z.object({
systemId: z.string().uuid(),
name: z.string().min(1),
value: z.number(),
unit: z.string().optional(),
// ... other fields
});
export async function addMetric(formData: FormData) {
const validatedData = addMetricSchema.parse({
systemId: formData.get('systemId'),
name: formData.get('name'),
value: parseFloat(formData.get('value') as string),
unit: formData.get('unit'),
});
await db.insert(metrics).values({
...validatedData,
id: crypto.randomUUID(),
timestamp: new Date(),
// Default thresholds can be set here or in a separate config
alertThresholdHigh: 100,
warningThresholdHigh: 80,
});
// Revalidate cache if using Next.js caching
// revalidatePath(`/systems/${validatedData.systemId}`);
}
```
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `/app/
- (auth)/
- page.tsx: Sign In / Sign Up form
- (protected)/
- layout.tsx: Main layout for authenticated users, includes sidebar/navbar
- dashboard/
- page.tsx: Main dashboard showing organization overview, system list, alerts summary.
- Components: OrgSelector, SystemList, AlertsSummaryCard
- systems/[systemId]/
- page.tsx: System detail page showing metrics charts, current values, recent alerts, predictions.
- Components: MetricChart (uses Recharts), MetricValueDisplay, RecentAlertsTable, PredictionsList
- components/
- AddMetricForm.tsx: Form to manually add a metric (for MVP simulation)
- settings/
- organization/
- page.tsx: Organization settings page (name, members, roles, invitations)
- Components: MemberTable, InviteMemberForm
- profile/
- page.tsx: User profile settings (name, email, password change)
- alerts/
- page.tsx: Page listing all alerts with filtering options.
- Components: AlertTable, FilterControls
- layout.tsx: Root layout for the protected section
- page.tsx: Landing Page (Public)
- layout.tsx: Root layout
- api/
- auth/[...nextauth]/route.ts: NextAuth.js route handler
- webhook/
- route.ts: Example webhook endpoint
- lib/
- db.ts: Drizzle connection setup
- db/schema.ts: Drizzle schema definitions
- auth.ts: NextAuth.js configuration
- utils.ts: Utility functions
- validation.ts: Zod validation schemas
- components/ui/
- ... shadcn/ui components (Button, Input, Card, Table, Chart, etc.)
- components/shared/
- Navbar.tsx
- Sidebar.tsx
- Footer.tsx
- LoadingSpinner.tsx
- EmptyState.tsx
- State Management: Primarily server-side state managed via Server Actions and fetched in Server Components. Client-side state for UI interactions (toggles, form states) managed locally within components. Global state (e.g., user session, organization context) managed via React Context or Zustand if complexity increases.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style**: Minimalist Clean with a touch of futuristic professionalism. Focus on clarity, data readability, and trustworthiness.
- **Color Palette**:
- Primary: Deep Blue (#0A192F)
- Secondary: Dark Gray (#1E293B)
- Accent: Bright Cyan (#64FFDA) for CTAs, highlights, active states.
- Text: Light Gray (#ADB5BD) / Off-White (#E2E8F0)
- Status Colors: Green (#34D399) for 'normal', Yellow (#FBBF24) for 'warning', Red (#F87171) for 'critical'.
- **Typography**: A modern sans-serif font like Inter or Poppins.
- Headings: Poppins (SemiBold, Bold)
- Body Text: Inter (Regular, Medium)
- **Layout**:
- Main Layout: Sidebar on the left for navigation (Dashboard, Systems, Alerts, Settings), main content area on the right.
- Dashboard: Card-based layout for key metrics summaries and system overview.
- System Detail: Tabbed interface or distinct sections for Metrics, Alerts, Predictions.
- Responsive: Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows gracefully.
- **Visual Elements**: Subtle gradients in backgrounds or cards, clean icons, clear data visualizations (line charts, gauges). Minimal use of unnecessary decoration.
ANIMATIONS:
- **Page Transitions**: Subtle fade-in/fade-out transitions between pages using Next.js's `useRouter` and a simple CSS transition.
- **Loading States**: Use shadcn/ui's `Skeleton` component or `LoadingSpinner` component with subtle opacity transitions when data is being fetched.
- **Hover Effects**: Slight scale or background color change on interactive elements (buttons, table rows, cards).
- **Chart Animations**: Recharts provides smooth animations for data loading and updates.
- **Input Fields**: Subtle focus outline animation using Tailwind CSS.
EDGE CASES:
- **Empty States**: All lists and dashboards should have informative empty state components (e.g., 'No systems added yet. Click here to add one.').
- **Authentication**: Handle expired sessions, invalid credentials, Google OAuth errors gracefully. Implement email verification and password reset.
- **Authorization**: Ensure users can only access data belonging to their organization. Role-based access control (Admin vs. Member).
- **Data Validation**: Use Zod for all incoming data (forms, API requests) to prevent invalid data entry and ensure data integrity.
- **Error Handling**: Global error boundary for unexpected UI errors. Specific error messages for API failures. Graceful degradation if a non-critical service fails.
- **Rate Limiting**: Implement basic rate limiting on API routes to prevent abuse.
- **Data Ingestion Failures**: Log errors during data processing and alert administrators if critical systems stop reporting data.
SAMPLE DATA (for frontend development & initial state testing):
1. **User:**
```json
{
"id": "uuid-user-1",
"name": "Alice Smith",
"email": "alice@example.com",
"image": "/api/auth/me/avatar.png"
}
```
2. **Organization:**
```json
{
"id": "uuid-org-1",
"name": "Quantum Dynamics Inc.",
"ownerId": "uuid-user-1"
}
```
3. **System:**
```json
[
{
"id": "uuid-sys-1",
"organizationId": "uuid-org-1",
"name": "Core Reactor Monitor",
"type": "Nuclear Power",
"status": "warning",
"lastCheckIn": "2023-10-27T10:30:00Z"
},
{
"id": "uuid-sys-2",
"organizationId": "uuid-org-1",
"name": "Turbine Efficiency Sensor",
"type": "Power Generation",
"status": "normal",
"lastCheckIn": "2023-10-27T10:32:00Z"
}
]
```
4. **Metrics (for System 1):
```json
[
{
"id": "uuid-metric-1",
"systemId": "uuid-sys-1",
"name": "Core Temperature",
"unit": "°C",
"currentValue": 85.5,
"timestamp": "2023-10-27T10:30:00Z",
"alertThresholdHigh": 90,
"warningThresholdHigh": 80
},
{
"id": "uuid-metric-2",
"systemId": "uuid-sys-1",
"name": "Neutron Flux",
"unit": "n/cm²s",
"currentValue": 1.2e15,
"timestamp": "2023-10-27T10:30:00Z",
"alertThresholdHigh": 1.5e15,
"warningThresholdHigh": 1.1e15
}
]
```
5. **Alerts (for System 1):
```json
[
{
"id": "uuid-alert-1",
"systemId": "uuid-sys-1",
"metricId": "uuid-metric-1",
"level": "warning",
"message": "Core Temperature approaching warning threshold.",
"triggeredAt": "2023-10-27T10:25:00Z",
"status": "open"
}
]
```
6. **Predictions (for System 1):
```json
[
{
"id": "uuid-pred-1",
"systemId": "uuid-sys-1",
"metricId": "uuid-metric-1",
"predictionTimestamp": "2023-10-27T12:00:00Z",
"confidence": 0.75,
"severity": "medium",
"details": "Core Temperature is predicted to exceed the high alert threshold within 2 hours based on current trend.",
"generatedAt": "2023-10-27T10:30:00Z"
}
]
```
7. **Organization Member:**
```json
{
"userId": "uuid-user-1",
"organizationId": "uuid-org-1",
"role": "admin",
"joinedAt": "2023-10-26T09:00:00Z"
}
```
This prompt provides a comprehensive blueprint for building the Resilience Hub MVP, ensuring a robust, scalable, and visually appealing application. The focus is on leveraging Next.js App Router features, Drizzle ORM for database interactions, and AI for predictive capabilities, all within a clean and professional UI.