## AI Master Prompt for Aviation Safety Sentinel MVP
### 1. PROJECT OVERVIEW:
**Project Name:** Aviation Safety Sentinel
**Problem:** The aviation industry faces critical safety risks due to communication gaps, overlooked pilot/crew concerns, and the failure to proactively address potential hazards before they lead to accidents. The recent LaGuardia incident, where pilot safety alarms were reportedly raised months prior to a fatal crash, highlights a systemic issue of warnings being ignored or not acted upon effectively.
**Solution:** Aviation Safety Sentinel is an AI-powered SaaS platform designed to ingest, analyze, and escalate safety concerns within the aviation sector. It provides a secure channel for reporting potential risks, leverages AI to identify patterns and predict high-risk situations, and offers a centralized dashboard for authorities to monitor and manage safety issues proactively. The core value proposition is to transform potential risks into actionable intelligence, thereby preventing accidents and enhancing overall aviation safety.
**Value Proposition:** "Proactively identify and mitigate aviation safety risks before they escalate into incidents. Aviation Safety Sentinel empowers airlines, airports, and regulatory bodies with AI-driven insights and streamlined workflows to ensure the highest standards of safety."
### 2. TECH STACK:
* **Frontend:** React (Next.js App Router)
* **Styling:** Tailwind CSS
* **ORM:** Drizzle ORM (PostgreSQL or SQLite for MVP)
* **UI Library:** shadcn/ui (for accessible, reusable components)
* **Authentication:** NextAuth.js (for secure user management, including email/password, Google OAuth)
* **State Management:** Zustand or React Context API (for global state)
* **Data Fetching:** React Server Components (RSC), Server Actions, custom API routes (Next.js)
* **Database:** PostgreSQL (recommended for production), SQLite (for local development/simplicity in MVP)
* **Charting:** Chart.js or Recharts (for dashboard visualizations)
* **Form Handling:** React Hook Form with Zod for validation
* **Deployment:** Vercel (recommended for Next.js)
### 3. DATABASE SCHEMA (PostgreSQL-like syntax):
```sql
-- Users table for authentication and authorization
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(50) DEFAULT 'user', -- e.g., 'admin', 'analyst', 'reporter'
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
);
-- Table to store reported safety concerns
CREATE TABLE safety_reports (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
reporter_id UUID REFERENCES users(id) ON DELETE SET NULL,
is_anonymous BOOLEAN DEFAULT FALSE,
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
category VARCHAR(100), -- e.g., 'Communication', 'Maintenance', 'Procedure', 'Infrastructure'
priority VARCHAR(50) DEFAULT 'medium', -- e.g., 'low', 'medium', 'high', 'critical'
status VARCHAR(50) DEFAULT 'new', -- e.g., 'new', 'investigating', 'action_required', 'resolved', 'closed'
location VARCHAR(255), -- e.g., Airport Name, Runway Number, Aircraft Type
reported_at TIMESTAMPTZ DEFAULT now()
);
-- Table to store AI analysis results and alerts
CREATE TABLE ai_analyses (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
report_id UUID REFERENCES safety_reports(id) ON DELETE CASCADE,
analysis_text TEXT NOT NULL,
risk_score REAL, -- e.g., 0.0 to 1.0
generated_at TIMESTAMPTZ DEFAULT now(),
suggested_actions TEXT
);
-- Table to track actions taken on reports/analyses
CREATE TABLE actions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
report_id UUID REFERENCES safety_reports(id) ON DELETE CASCADE,
assigned_to UUID REFERENCES users(id) ON DELETE SET NULL,
action_description TEXT NOT NULL,
due_date DATE,
completion_date DATE,
status VARCHAR(50) DEFAULT 'pending', -- e.g., 'pending', 'in_progress', 'completed', 'overdue'
created_at TIMESTAMPTZ DEFAULT now()
);
-- Optional: Table for external data sources (e.g., aviation bulletins)
CREATE TABLE external_data (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
source_name VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
processed_at TIMESTAMPTZ DEFAULT now(),
related_report_id UUID REFERENCES safety_reports(id) ON DELETE SET NULL
);
```
### 4. CORE FEATURES & USER FLOW:
**A. User Authentication (NextAuth.js):**
* **Flow:** User lands on the login/signup page. Options: Email/Password or Google OAuth.
* **Signup:** User provides name, email, password. Password is hashed. Record created in `users` table. Redirect to dashboard.
* **Login:** User provides credentials. Validate against `users` table. If valid, create a session. Redirect to dashboard.
* **OAuth:** User clicks Google button. Redirected to Google for auth. Redirect back to app. If new user, create record; if existing, log in. Redirect to dashboard.
* **Edge Cases:** Invalid credentials, duplicate email, OAuth errors, session expiry.
**B. Report Submission (New Page `/reports/new`):**
* **Flow:** Authenticated user navigates to the new report page. User fills out a form:
1. **Anonymous Option:** Toggle to submit anonymously.
2. **Title:** Short, descriptive title (e.g., 'Unusual engine noise during descent').
3. **Description:** Detailed explanation of the concern.
4. **Category:** Select from predefined list (e.g., 'Engine', 'Navigation', 'Crew Communication').
5. **Priority:** Select level ('Low', 'Medium', 'High', 'Critical').
6. **Location:** Text input for airport, runway, aircraft type etc.
7. User clicks 'Submit'.
8. **Server Action:** Data is validated (using Zod). If valid, a new record is created in the `safety_reports` table. If `is_anonymous` is false, `reporter_id` is set to the logged-in user's ID. A background job/server action triggers AI analysis.
* **Edge Cases:** Form validation errors, network issues during submission, required fields missing.
**C. Dashboard (Protected Page `/dashboard`):**
* **Flow:** Authenticated user (with appropriate role, e.g., 'analyst' or 'admin') accesses the dashboard.
1. **Overview Stats:** Cards displaying total reports, new reports, high-priority alerts, resolved issues.
2. **Recent Reports:** A table/list showing the latest submitted reports with key details (title, status, priority, date).
3. **Alerts Feed:** A section highlighting critical AI-generated alerts based on `ai_analyses` table.
4. **Visualizations:** Charts showing report trends by category, status over time, risk score distribution (using Chart.js/Recharts).
5. **Interactivity:** Clicking a report row navigates to the detailed report view. Filtering/sorting options for tables.
* **Data Fetching:** Uses React Server Components (RSC) to fetch aggregated data directly from the database for initial load. More specific data fetched via client-side requests or Server Actions if needed.
* **Edge Cases:** Empty states (no reports, no alerts), user without permissions, slow data loading.
**D. Report Detail View (Dynamic Page `/reports/[reportId]`):**
* **Flow:** User clicks on a specific report from the dashboard or a list.
1. **Report Details:** Displays all information from the `safety_reports` table.
2. **AI Analysis:** Shows associated `ai_analyses` records (analysis text, risk score, suggested actions).
3. **Action Tracking:** Displays associated `actions` records (description, assigned user, status, due date, completion date).
4. **Status Update:** If user has permissions, allows changing the `status` of the report.
5. **Add Action:** Form to create a new `action` item, assigning it to a user and setting a due date.
* **Edge Cases:** Report not found, no AI analysis available yet, no actions logged.
**E. AI Analysis Trigger:**
* **Flow:** This is a background process, triggered after a new report is submitted (via Server Action or a queue system).
1. Fetches the latest report content.
2. (Placeholder for actual AI integration) Simulates AI analysis: Generates a plausible `analysis_text`, calculates a `risk_score` (e.g., based on keywords, priority), and suggests `suggested_actions`.
3. Stores the result in the `ai_analyses` table, linked to the `report_id`.
4. (Future) Integrate with a real LLM API (e.g., OpenAI, Gemini) for actual natural language analysis and risk assessment.
* **Edge Cases:** AI service unavailable, analysis takes too long, poor quality analysis output.
### 5. API & DATA FETCHING:
* **App Router Structure:** Utilize Server Components (RSC) for initial page loads and data fetching where possible (e.g., `/dashboard`, `/reports/[reportId]`). This simplifies data fetching and improves performance.
* **Server Actions:** Use for mutations (creating, updating, deleting data) triggered by forms (e.g., submitting a report, adding an action). Example:
```javascript
// app/reports/new/actions.ts
'use server';
import { db } from '@/lib/db'; // Your Drizzle DB instance
import { safety_reports } from '@/lib/schema'; // Your Drizzle schema
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
const reportSchema = z.object({
title: z.string().min(3),
description: z.string().min(10),
// ... other fields
});
export async function createReport(formData: FormData) {
const data = Object.fromEntries(formData.entries());
const validatedData = reportSchema.parse(data);
await db.insert(safety_reports).values({
title: validatedData.title,
description: validatedData.description,
// ... map other fields
reporter_id: 'some-user-id' // Get from session in real app
});
revalidatePath('/dashboard'); // Clear cache for dashboard
return { success: true };
}
```
* **API Routes (app/api/...):** Use for specific backend tasks not covered by Server Actions, or for integrating with third-party services that require a stable endpoint.
* **Client-Side Fetching:** Use `useEffect` or libraries like SWR/React Query for dynamic data updates or client-initiated actions where Server Components are not suitable.
* **Data Flow:** Server Components fetch data directly. Server Actions receive form data, perform DB operations, and can revalidate cache. Client components interact with Server Actions or API routes.
### 6. COMPONENT BREAKDOWN (Next.js App Router):
* **`app/layout.tsx`:** Root layout (html, body, providers like ThemeProvider, possibly auth provider).
* **`app/page.tsx`:** Landing Page (Public).
* **`app/login/page.tsx`:** Login page (using NextAuth.js components).
* **`app/signup/page.tsx`:** Signup page.
* **`app/dashboard/page.tsx`:** (Protected) Main dashboard page. Fetches overview stats and recent reports via RSC.
* `components/Dashboard/OverviewStats.tsx`: Displays key metrics (cards).
* `components/Dashboard/RecentReportsTable.tsx`: Table component for recent reports.
* `components/Dashboard/AlertsFeed.tsx`: List of critical AI alerts.
* `components/Charts/ReportTrendChart.tsx`: Chart component.
* **`app/reports/new/page.tsx`:** (Protected) Form page for submitting new safety reports.
* `components/Forms/ReportForm.tsx`: Contains the report submission form logic, uses React Hook Form & Zod, calls Server Action `createReport`.
* **`app/reports/[reportId]/page.tsx`:** (Protected) Dynamic page for viewing report details.
* `components/Reports/ReportDetailView.tsx`: Displays report data.
* `components/AiAnalysis/AnalysisDisplay.tsx`: Shows AI analysis results.
* `components/Actions/ActionTracking.tsx`: Manages and displays action items.
* `components/Actions/AddActionForm.tsx`: Form to add new actions.
* **`app/settings/page.tsx`:** (Protected) User settings page (profile, password change).
* **`components/Layout/Navbar.tsx`:** Navigation bar (conditionally renders based on auth state).
* **`components/Layout/Sidebar.tsx`:** Sidebar navigation for authenticated users.
* **`components/Common/DataTable.tsx`:** Reusable data table component (used in dashboard, potentially elsewhere).
* **`components/Common/Button.tsx`:** Custom button component (likely from shadcn/ui).
* **`components/Common/Card.tsx`:** Reusable card component (likely from shadcn/ui).
* **`components/Auth/OAuthButtons.tsx`:** Buttons for Google OAuth login.
**State Management:** Primarily Server Components for data fetching. Zustand or Context API for global UI state (e.g., theme, sidebar open/closed). Local component state for form inputs, UI toggles.
### 7. UI/UX DESIGN & VISUAL IDENTITY:
* **Design Style:** Minimalist Clean with Professional Accents.
* Focus on clarity, readability, and efficient information display. Avoid clutter.
* **Color Palette:**
* **Primary:** `#2563EB` (a strong, trustworthy blue)
* **Secondary:** `#10B981` (a calming, positive green for resolved/success states)
* **Accent/Alert:** `#EF4444` (a clear red for critical alerts/errors)
* **Warning:** `#F59E0B` (a distinct orange/yellow for warnings)
* **Neutral Background:** `#F3F4F6` (light gray for main background)
* **Card/Element Background:** `#FFFFFF` (white for cards and primary content areas)
* **Text (Dark):** `#1F2937` (dark gray for primary text)
* **Text (Light/Muted):** `#6B7280` (lighter gray for secondary text)
* **Typography:**
* **Headings:** Inter, Semi-bold (e.g., `font-semibold`)
* **Body Text:** Inter, Regular (e.g., `font-normal`)
* Ensure good contrast and readability.
* **Layout:**
* **Main Structure:** Sidebar navigation on the left, main content area on the right.
* **Dashboard:** Grid layout for cards (stats), tables, and charts. Clear separation between sections.
* **Forms:** Well-spaced form elements with clear labels and validation feedback.
* **Responsiveness:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows into single column layouts.
* **Interactivity:** Subtle hover effects on buttons and table rows. Smooth transitions for UI elements (e.g., sidebar collapse, modal opening). Loading spinners/skeletons for data fetching.
### 8. SAMPLE/MOCK DATA:
**`safety_reports` Table:**
1. `{ id: '...', title: 'Unusual vibration during takeoff', description: 'Pilot noticed a strong, abnormal vibration from the left engine during the takeoff roll at JFK.', category: 'Engine', priority: 'high', status: 'new', location: 'JFK Runway 4L', reported_at: '2024-07-26T10:00:00Z' }`
2. `{ id: '...', title: 'Navigation system glitch', description: 'During cruise, the primary navigation display flickered and showed incorrect position for approx. 2 minutes. Backup system engaged.', category: 'Navigation', priority: 'medium', status: 'investigating', location: 'Flight 123, FL350', reported_at: '2024-07-25T15:30:00Z' }`
3. `{ id: '...', title: 'Ground vehicle proximity warning', description: 'Ground vehicle entered active taxiway C without proper clearance. Close call averted by ATC intervention.', category: 'Infrastructure', priority: 'critical', status: 'new', location: 'LAX Taxiway C', reported_at: '2024-07-26T08:15:00Z' }`
4. `{ id: '...', title: 'Routine check anomaly', description: 'A scheduled maintenance check revealed a minor wear on a hydraulic component. Replaced as precaution.', category: 'Maintenance', priority: 'low', status: 'resolved', location: 'Hangar 5', reported_at: '2024-07-20T11:00:00Z' }`
**`ai_analyses` Table (linked to above reports):
**5. `{ id: '...', report_id: 'report_id_1', analysis_text: 'High vibration reported during critical flight phase (takeoff). Potential risk of engine malfunction. Correlates with recent component advisories.', risk_score: 0.85, suggested_actions: 'Recommend immediate non-routine engine inspection. Review maintenance logs for similar issues.' }`
6. `{ id: '...', report_id: 'report_id_3', analysis_text: 'Critical safety breach involving ground vehicle and active taxiway. Indicates potential breakdown in ATC communication or vehicle operator training.', risk_score: 0.92, suggested_actions: 'Review ATC logs for the period. Conduct immediate retraining for ground vehicle operators. Evaluate current taxiway safety protocols.' }`
**`actions` Table (linked to above reports):
**7. `{ id: '...', report_id: 'report_id_1', assigned_to: 'user_id_analyst', action_description: 'Schedule and perform non-routine inspection of left engine.', status: 'in_progress', due_date: '2024-07-29', created_at: '2024-07-26T11:00:00Z' }`
8. `{ id: '...', report_id: 'report_id_3', assigned_to: 'user_id_admin', action_description: 'Initiate investigation into ground vehicle incident and ATC communication logs.', status: 'pending', due_date: '2024-07-28', created_at: '2024-07-26T09:00:00Z' }`
9. `{ id: '...', report_id: 'report_id_4', assigned_to: 'user_id_technician', action_description: 'Inspection completed. Component replaced successfully.', status: 'completed', completion_date: '2024-07-25', created_at: '2024-07-20T11:05:00Z' }`
**`users` Table:**
10. `{ id: 'user_id_pilot', name: 'Alex Smith', email: 'alex.smith@airline.com', role: 'reporter' }`
11. `{ id: 'user_id_analyst', name: 'Maria Garcia', email: 'maria.garcia@safety.com', role: 'analyst' }`
12. `{ id: 'user_id_admin', name: 'John Doe', email: 'john.doe@aviation.gov', role: 'admin' }`
### 9. TURKISH TRANSLATIONS:
* **App Title:** Güvenlik Gözcüsü
* **Project Overview:** Aviation Safety Sentinel, havacılık sektöründeki iletişim kopuklukları, göz ardı edilen mürettebat endişeleri ve kazalara yol açabilecek potansiyel tehlikelerin proaktif olarak ele alınamaması gibi kritik güvenlik risklerini ele alan yapay zeka destekli bir SaaS platformudur. Potansiyel riskleri toplamak, analiz etmek ve yetkililere iletmek için güvenli bir kanal sağlar, tehlikeli durumları oluşmadan önce tespit ederek önleyici tedbirlerin alınmasını amaçlar.
* **Value Proposition:** "Havacılık güvenliği risklerini olaylara dönüşmeden proaktif olarak belirleyin ve azaltın. Aviation Safety Sentinel, havayolu şirketlerini, havalimanlarını ve düzenleyici kurumları, yapay zeka destekli içgörüler ve kolaylaştırılmış iş akışlarıyla en üst düzeyde güvenlik sağlamaları için güçlendirir."
* **Report Submission:** Yeni Rapor Oluştur
* **Title:** Rapor Başlığı
* **Description:** Açıklama
* **Category:** Kategori
* **Priority:** Öncelik
* **Status:** Durum
* **Location:** Konum
* **Submit:** Gönder
* **Dashboard:** Kontrol Paneli
* **Overview Stats:** Genel Bakış İstatistikleri
* **Recent Reports:** Son Raporlar
* **Alerts Feed:** Uyarılar
* **New Report:** Yeni Rapor
* **Actions:** Eylemler
* **Assign To:** Atanan Kişi
* **Due Date:** Son Teslim Tarihi
* **Save Action:** Eylem Kaydet
* **Login:** Giriş Yap
* **Sign Up:** Kayıt Ol
* **Logout:** Çıkış Yap
* **Settings:** Ayarlar
### 10. ANIMATIONS:
* **Page Transitions:** Use `Framer Motion` or Next.js's built-in features for smooth fading or sliding transitions between pages.
* **Button Hovers:** Subtle background color change or slight scale-up effect on button hover.
* **Loading States:** Implement skeleton loaders for tables and cards while data is being fetched. Use spinners within buttons during submission processes.
* **Dropdowns/Modals:** Smooth slide-down/fade-in animations for dropdown menus and modal dialogs.
* **Chart Interactions:** Tooltip animations and subtle transitions when chart data updates.
### 11. EDGE CASES:
* **Authentication:** Handle expired sessions, unauthorized access attempts gracefully. Implement password reset functionality.
* **Data Validation:** Robust client-side (Zod) and server-side (Server Actions) validation for all user inputs. Provide clear error messages.
* **Empty States:** Design user-friendly empty states for tables, charts, and lists (e.g., "No reports submitted yet. Submit your first report to get started.").
* **Error Handling:** Implement global error handling for API routes and Server Actions. Display user-friendly error messages (e.g., using a toast notification system).
* **Network Failures:** Provide visual feedback (e.g., loading indicators) and retry mechanisms or clear error messages when network requests fail.
* **AI Service Downtime:** If integrating with external AI services, implement fallback mechanisms or clear messaging indicating that AI features are temporarily unavailable.
* **Permissions:** Ensure role-based access control is strictly enforced for sensitive features (e.g., viewing all reports, assigning actions).