PROJECT OVERVIEW:
The application, named 'Hormuz Watch', is a comprehensive SaaS platform designed to monitor and analyze real-time vessel traffic specifically within the Strait of Hormuz. It aims to provide critical insights into maritime security, geopolitical risks, and their impact on global trade and energy markets. The core value proposition is to offer an unparalleled, data-driven view of this strategically vital waterway, enabling businesses and organizations to make informed decisions, mitigate risks, and optimize logistics.
TECH STACK:
- Frontend: React (Next.js App Router)
- Styling: Tailwind CSS
- UI Components: shadcn/ui
- Backend Framework: Next.js API Routes / Server Actions
- ORM: Drizzle ORM (PostgreSQL)
- Database: PostgreSQL (or Supabase/Neon for managed service)
- Authentication: NextAuth.js (or Clerk for managed service)
- Real-time Data: Potentially WebSockets for live updates or frequent polling
- Mapping: Leaflet.js or Mapbox GL JS for vessel visualization
- State Management: Zustand or React Context API
- Data Fetching: React Query / TanStack Query for client-side data fetching and caching
- Date/Time: date-fns
- Form Handling: react-hook-form
- Validation: Zod
DATABASE SCHEMA:
1. `users` table:
- `id`: UUID (Primary Key)
- `name`: VARCHAR
- `email`: VARCHAR (Unique)
- `emailVerified`: TIMESTAMP
- `image`: VARCHAR (Optional, for profile picture)
- `createdAt`: TIMESTAMP (Default: now())
- `updatedAt`: TIMESTAMP
2. `accounts` table (for NextAuth.js):
- `id`: BIGSERIAL (Primary Key)
- `userId`: UUID (Foreign Key to `users.id`)
- `type`: VARCHAR
- `provider`: VARCHAR
- `providerAccountId`: VARCHAR
- `refresh_token`: TEXT (Optional)
- `access_token`: TEXT (Optional)
- `expires_at`: BIGINT (Optional)
- `token_type`: VARCHAR (Optional)
- `scope`: VARCHAR (Optional)
- `id_token`: TEXT (Optional)
3. `sessions` table (for NextAuth.js):
- `id`: BIGSERIAL (Primary Key)
- `sessionToken`: VARCHAR (Unique)
- `userId`: UUID (Foreign Key to `users.id`)
- `expires`: TIMESTAMP
4. `verificationTokens` table (for NextAuth.js):
- `identifier`: VARCHAR
- `token`: VARCHAR (Unique)
- `expires`: TIMESTAMP
5. `vessels` table:
- `imoNumber`: BIGINT (Primary Key)
- `mmsiNumber`: BIGINT (Unique)
- `name`: VARCHAR
- `callSign`: VARCHAR (Optional)
- `shipType`: VARCHAR (e.g., Tanker, Cargo, Passenger)
- `flag`: VARCHAR (Country code)
- `length`: DECIMAL (meters)
- `width`: DECIMAL (meters)
- `grossTonnage`: DECIMAL (Optional)
- `deadweight`: DECIMAL (Optional)
6. `vesselPositions` table:
- `id`: UUID (Primary Key, Default: uuid_generate_v4())
- `imoNumber`: BIGINT (Foreign Key to `vessels.imoNumber`)
- `timestamp`: TIMESTAMP (Unique constraint on imoNumber, timestamp for a given vessel)
- `latitude`: DECIMAL
- `longitude`: DECIMAL
- `course`: DECIMAL (Degrees)
- `speed`: DECIMAL (Knots)
- `navigationalStatus`: SMALLINT (AIS status code)
- `source`: VARCHAR (e.g., 'AIS', 'Radar')
- `receivedAt`: TIMESTAMP (When the data was processed by our system)
7. `alerts` table:
- `id`: UUID (Primary Key, Default: uuid_generate_v4())
- `userId`: UUID (Foreign Key to `users.id`)
- `alertType`: VARCHAR (e.g., 'Proximity', 'Speed Anomaly', 'Restricted Zone Entry')
- `vesselImoNumber`: BIGINT (Optional, if alert is vessel-specific)
- `locationDescription`: VARCHAR (e.g., 'Near Kharg Island', 'Approaching Hormuz Entrance')
- `thresholdValue`: DECIMAL (Optional, for quantitative alerts)
- `isActive`: BOOLEAN (Default: true)
- `createdAt`: TIMESTAMP (Default: now())
8. `reports` table:
- `id`: UUID (Primary Key, Default: uuid_generate_v4())
- `title`: VARCHAR
- `description`: TEXT
- `generatedAt`: TIMESTAMP (Default: now())
- `generatedByUserId`: UUID (Foreign Key to `users.id`)
- `reportType`: VARCHAR (e.g., 'Traffic Analysis', 'Risk Assessment')
- `data`: JSONB (Store report specific data)
CORE FEATURES & USER FLOW:
1. **User Authentication (Sign Up / Login):**
- Flow: User visits the landing page -> Clicks 'Sign Up' or 'Login' -> Redirected to auth page -> Enters credentials (email/password) or uses OAuth (Google/GitHub) -> Upon success, redirected to the dashboard.
- Auth Service: NextAuth.js integrated with PostgreSQL. Email/password sign-up requires verification.
- Edge Cases: Invalid credentials, account lockout (optional), password reset flow.
2. **Real-time Vessel Tracking Dashboard:**
- Flow: Authenticated user logs in -> Dashboard loads -> A map component displays the Strait of Hormuz area -> Live vessel positions (from `vesselPositions` table, updated frequently) are plotted as markers on the map.
- User Interaction: Users can click on a vessel marker to see a popup with basic info (Name, IMO, MMSI, Type, Flag, Last Known Speed/Course). A sidebar lists vessels currently in the monitored zone, sortable/filterable.
- Data Fetching: Initial load fetches vessels within the Hormuz geofence. Subsequent updates fetch new positions via API calls or WebSockets.
- Edge Cases: Map loading errors, no vessel data available (empty state), high density of vessels (clustering). User's current location shown if permission granted.
3. **Vessel Search & Details:**
- Flow: User uses a search bar (on dashboard or dedicated search page) -> Enters IMO, MMSI, or vessel name -> System queries `vessels` and `vesselPositions` tables -> Search results displayed -> User clicks a result -> Navigates to a detailed vessel page.
- Vessel Detail Page: Shows all vessel information from `vessels` table and a historical track of its movements (from `vesselPositions`) plotted on a map. Displays key stats (average speed, time in zone, etc.).
- Edge Cases: Vessel not found, partial matches, no historical data.
4. **Alert Configuration & Management:**
- Flow: User navigates to 'Alerts' section -> Clicks 'Create New Alert' -> Selects alert type (e.g., Proximity to specific coordinates/buoys, entering/exiting a defined zone, abnormal speed) -> Configures parameters (thresholds, zones, target vessels if applicable) -> Saves the alert.
- Notification: When an alert condition is met (checked via background job or on data ingestion), the system generates an alert entry in the `alerts` table and potentially sends an in-app notification or email (future enhancement).
- Management: Users can view, edit, disable, or delete their configured alerts.
- Edge Cases: Invalid zone definitions, overlapping alerts, alert fatigue.
5. **Basic Reporting:**
- Flow: User navigates to 'Reports' section -> Selects a report type (e.g., 'Daily Traffic Summary', 'Vessel Type Distribution') -> System generates a report based on recent data -> Report is displayed or downloadable (e.g., CSV).
- Data Aggregation: Reports will query and aggregate data from `vesselPositions` and `vessels` tables.
- Edge Cases: Insufficient data for report generation, long report generation times.
API & DATA FETCHING:
- `/api/auth/*`: Handled by NextAuth.js for authentication.
- `/api/vessels`: GET request to fetch a list of vessels within a given geofence or search criteria. Accepts query parameters like `bbox` (bounding box), `search`, `shipType`. Returns JSON array of vessel data.
- Example Request: `GET /api/vessels?bbox=-56.5,25.0,-57.0,26.0&shipType=Tanker`
- Example Response: `[{ "imoNumber": 9876543, "name": "Super Tanker", "mmsiNumber": 123456789, ... }]`
- `/api/vessels/[imoNumber]`: GET request to fetch detailed information and historical positions for a specific vessel.
- Example Request: `GET /api/vessels/9876543?startDate=2023-10-26T00:00:00Z&endDate=2023-10-27T00:00:00Z`
- Example Response: `{ "vesselInfo": { ... }, "historicalPositions": [{ "timestamp": "...", "latitude": ..., "longitude": ... }, ...] }`
- `/api/alerts`: POST to create a new alert, GET to list user's alerts, PUT/DELETE to manage them.
- `/api/reports`: POST to request report generation, GET to list generated reports.
- **Data Updates:** Initial MVP might use frequent polling (e.g., every 60 seconds) for vessel positions via an API endpoint. Future versions should implement WebSockets or server-sent events for true real-time updates. A background job/worker will be needed to ingest external AIS data and update the `vesselPositions` table.
- **Client-side Fetching:** Utilize React Query for caching, background refetching, and managing server state for all API calls.
COMPONENT BREAKDOWN (Next.js App Router Structure):
- `app/layout.tsx`: Root layout with global styles, fonts, and providers (AuthProvider, QueryClientProvider).
- `app/page.tsx`: Landing Page (publicly accessible).
- `app/login/page.tsx`: Login form component.
- `app/signup/page.tsx`: Sign up form component.
- `app/(dashboard)/layout.tsx`: Dashboard layout with sidebar navigation (protected route).
- `app/(dashboard)/dashboard/page.tsx`: Main dashboard page with the map and vessel list.
- Components: `MapComponent` (Leaflet/Mapbox integration), `VesselList` (handles vessel data and filtering), `VesselPopup` (displays info on marker click).
- `app/(dashboard)/vessels/[imoNumber]/page.tsx`: Detailed vessel information page.
- Components: `VesselDetailsCard`, `HistoricalTrackMap`, `TimeSeriesChart` (for speed/course data).
- `app/(dashboard)/alerts/page.tsx`: Page to manage alerts.
- Components: `AlertList`, `AlertForm` (for creating/editing alerts).
- `app/(dashboard)/reports/page.tsx`: Page to manage reports.
- Components: `ReportGenerator`, `ReportList`.
- `app/settings/page.tsx`: User profile and settings page.
- `components/ui/`: All shadcn/ui components and custom UI elements (Buttons, Modals, Input fields, etc.).
- `components/auth/`: Authentication-related components (LoginForm, SignupForm).
- `components/map/`: Map-specific components.
- `components/vessel/`: Components related to displaying vessel data.
- `lib/`: Utility functions, API client, Drizzle schema definition, date formatting.
- `hooks/`: Custom React hooks.
- `styles/`: Global CSS if needed (beyond Tailwind).
- State Management: Use Zustand for global state like user authentication status, theme settings. Use React Context for simpler shared states. Component-local state for UI elements.
UI/UX DESIGN & VISUAL IDENTITY:
- **Design Style:** Modern, Clean, Data-Focused with a touch of professional urgency.
- **Color Palette:**
- Primary: Deep Navy Blue (`#0A192F`)
- Secondary: Dark Grey (`#262626`)
- Accent: Teal/Cyan (`#61DAFB` or `#00F0FF` for highlights/active states)
- Text: Light Gray (`#ABB2BF`)
- Backgrounds: Slightly lighter dark gray/blue for contrast (`#1E293B`)
- Alerts: Warning Yellow (`#FFD700`), Danger Red (`#EF4444`)
- **Typography:** Sans-serif fonts. Use Inter or Roboto for body text, a slightly bolder variant for headings. Ensure good readability on dark backgrounds.
- **Layout:** Sidebar navigation on the left for main sections (Dashboard, Vessels, Alerts, Reports, Settings). Main content area occupies the rest of the screen. Map takes a significant portion of the dashboard. Use clear visual hierarchy. Responsive design principles are crucial.
- **Visual Elements:** Clean icons, subtle gradients on interactive elements, clear data visualization (charts, map markers). Focus on clarity and reducing cognitive load.
- **Responsive Rules:** Desktop-first approach, ensure usability on tablets and gracefully degrade on mobile (e.g., collapsible sidebar, stacked elements).
ANIMATIONS:
- **Page Transitions:** Subtle fade-in/out transitions between pages using Next.js's built-in router capabilities or a library like `Framer Motion`.
- **Loading States:** Skeleton loaders for data-heavy components (e.g., vessel list, report generation). Spinners for API requests.
- **Hover Effects:** Slight scale-up or background color change on interactive elements (buttons, list items).
- **Map Animations:** Smooth panning and zooming. Optional subtle pulsing animation for newly appeared vessels.
- **Notifications:** Toast notifications for alerts or confirmation messages with smooth entry/exit animations.
EDGE CASES:
- **Authentication:** Handle expired sessions, invalid tokens, social login failures gracefully. Implement password reset functionality.
- **Data Empty States:** Display informative messages and/or illustrations when no vessels are present in the area, no search results are found, or reports cannot be generated due to lack of data. E.g., "No vessel activity detected in the monitored zone currently."
- **Error Handling:** Catch API errors, database connection issues, and map rendering problems. Display user-friendly error messages. Implement global error boundaries.
- **Validation:** Implement client-side and server-side validation for all user inputs (forms, alert configurations) using Zod.
- **Geofencing:** Robust logic for defining and checking if vessels are within the Hormuz geofence. Handle edge cases like vessels exactly on the boundary.
- **Rate Limiting:** Implement rate limiting on API endpoints to prevent abuse.
- **Permissions:** Ensure users can only access their own data (alerts, reports).
SAMPLE/MOCK DATA:
1. **Vessel List Item (Dashboard):**
```json
{
"imoNumber": 9876543,
"name": "Super Tanker",
"mmsiNumber": 123456789,
"flag": "LR",
"shipType": "Tanker",
"lastPosition": {
"latitude": 26.587,
"longitude": 56.234,
"timestamp": "2023-10-27T10:30:00Z",
"speed": 10.5,
"course": 90
}
}
```
2. **Vessel Detail (Full Object):**
```json
{
"imoNumber": 9876543,
"mmsiNumber": 123456789,
"name": "Super Tanker",
"callSign": "ABCDE",
"shipType": "Crude Oil Tanker",
"flag": "Liberia",
"length": 333.0,
"width": 60.0,
"grossTonnage": 180000,
"deadweight": 320000,
"historicalPositions": [
{"timestamp": "2023-10-27T10:30:00Z", "latitude": 26.587, "longitude": 56.234, "speed": 10.5, "course": 90},
{"timestamp": "2023-10-27T10:25:00Z", "latitude": 26.575, "longitude": 56.220, "speed": 10.4, "course": 89}
]
}
```
3. **Alert Configuration:**
```json
{
"id": "uuid-alert-123",
"userId": "uuid-user-456",
"alertType": "Proximity",
"vesselImoNumber": 9876543,
"locationDescription": "Near Kharg Island Terminal",
"thresholdValue": 5,
"isActive": true,
"createdAt": "2023-10-27T09:00:00Z"
}
```
4. **Report Metadata:**
```json
{
"id": "uuid-report-789",
"title": "Daily Traffic Summary - 2023-10-26",
"generatedAt": "2023-10-27T08:00:00Z",
"reportType": "Traffic Analysis"
}
```
5. **User Profile:**
```json
{
"id": "uuid-user-456",
"name": "Ahmet Yilmaz",
"email": "ahmet.yilmaz@example.com",
"image": null
}
```
6. **Ship Types (for filters/dropdowns):**
```json
["Tanker", "Cargo", "Container Ship", "Passenger", "Tug", "Military", "Fishing", "Other"]
```
7. **Alert Types (for configuration):**
```json
["Proximity", "Zone Entry", "Zone Exit", "Speed Anomaly", "Course Deviation"]
```
8. **Mock Geofence Coordinates (Strait of Hormuz area):**
```json
// Example bounding box coordinates
{
"northEast": {"lat": 27.5, "lng": 57.0},
"southWest": {"lat": 25.0, "lng": 55.5}
}
```
TURKISH TRANSLATIONS:
- App Title: Hormuz Gözcü (Hormuz Watch)
- Dashboard: Kontrol Paneli
- Vessels: Gemiler
- Alerts: Uyarılar
- Reports: Raporlar
- Settings: Ayarlar
- Login: Giriş Yap
- Sign Up: Kayıt Ol
- Search vessels: Gemileri Ara
- Filter: Filtrele
- Vessel Name: Gemi Adı
- IMO Number: IMO Numarası
- MMSI Number: MMSI Numarası
- Ship Type: Gemi Tipi
- Flag: Bayrak
- Last Position: Son Konum
- Course: Rota
- Speed: Hız
- Timestamp: Zaman Damgası
- Create Alert: Uyarı Oluştur
- Alert Type: Uyarı Tipi
- Location: Konum
- Threshold: Eşik Değer
- Active: Aktif
- Generated At: Oluşturulma Zamanı
- Download Report: Raporu İndir
- No data available: Veri Bulunamadı
- Loading: Yükleniyor...
- An error occurred: Bir hata oluştu.
- Save: Kaydet
- Edit: Düzenle
- Delete: Sil
- All Rights Reserved: Tüm Hakları Saklıdır.
- Hormuz Watch © [Year]: Hormuz Watch © [Yıl]