Add flight comparator web app with full scan pipeline

Full-stack flight price scanner built on fast-flights v3 (SOCS cookie bypass):

Backend (FastAPI + SQLite):
- REST API with rate limiting, Pydantic v2 validation, paginated responses
- Scan pipeline: resolves airports, queries every day in the window, saves
  individual flights + aggregate route stats to SQLite
- Background async scan processor with real-time progress tracking
- Airport search endpoint backed by OpenFlights dataset
- Daily scan window (all dates, not monthly samples)

Frontend (React 19 + TypeScript + Tailwind CSS v4):
- Dashboard with live scan status and recent scans
- Create scan form: country mode or specific airports (searchable dropdown)
- Scan detail page with expandable route rows showing individual flights
  (date, airline, departure, arrival, price) loaded on demand
- AirportSearch component with debounced live search and multi-select

Database:
- scans → routes → flights schema with FK cascade and auto-update triggers
- Migrations for schema evolution (relaxed country constraint)

Tests:
- 74 tests: unit + integration, isolated per-test SQLite DB
- Confirmed flight fixtures in tests/confirmed_flights.json (50 real flights,
  BDS→FMM Ryanair + BDS→DUS Eurowings, scraped Feb 2026)
- Integration tests parametrized from confirmed routes

Docker:
- Multi-stage builds, Compose orchestration, Nginx reverse proxy

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-26 17:11:51 +01:00
parent aea7590874
commit 6421f83ca7
67 changed files with 37173 additions and 0 deletions

View File

@@ -0,0 +1,144 @@
import { useState } from 'react';
import { airportApi } from '../api';
import type { Airport } from '../api';
export default function Airports() {
const [query, setQuery] = useState('');
const [airports, setAirports] = useState<Airport[]>([]);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [total, setTotal] = useState(0);
const handleSearch = async (searchQuery: string, searchPage = 1) => {
if (searchQuery.length < 2) {
setAirports([]);
return;
}
try {
setLoading(true);
const response = await airportApi.search(searchQuery, searchPage, 20);
setAirports(response.data.data);
setTotalPages(response.data.pagination.pages);
setTotal(response.data.pagination.total);
setPage(searchPage);
} catch (error) {
console.error('Failed to search airports:', error);
} finally {
setLoading(false);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
handleSearch(query, 1);
};
return (
<div>
<h2 className="text-2xl font-bold text-gray-900 mb-6">Airport Search</h2>
{/* Search Form */}
<div className="bg-white rounded-lg shadow p-6 mb-6">
<form onSubmit={handleSubmit}>
<div className="flex space-x-4">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search by IATA code, city, or airport name..."
className="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
type="submit"
disabled={loading || query.length < 2}
className="px-6 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Searching...' : 'Search'}
</button>
</div>
<p className="mt-2 text-sm text-gray-500">
Enter at least 2 characters to search
</p>
</form>
</div>
{/* Results */}
{airports.length > 0 && (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
<h3 className="text-lg font-semibold text-gray-900">
Search Results
</h3>
<span className="text-sm text-gray-500">
{total} airport{total !== 1 ? 's' : ''} found
</span>
</div>
<div className="divide-y divide-gray-200">
{airports.map((airport) => (
<div key={airport.iata} className="px-6 py-4 hover:bg-gray-50">
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center space-x-3">
<span className="font-bold text-lg text-blue-600">
{airport.iata}
</span>
<span className="font-medium text-gray-900">
{airport.name}
</span>
</div>
<div className="mt-1 text-sm text-gray-500">
{airport.city}, {airport.country}
</div>
</div>
<button
onClick={() => {
navigator.clipboard.writeText(airport.iata);
}}
className="px-3 py-1 text-sm text-blue-600 hover:bg-blue-50 rounded"
>
Copy Code
</button>
</div>
</div>
))}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center">
<div className="text-sm text-gray-500">
Page {page} of {totalPages}
</div>
<div className="flex space-x-2">
<button
onClick={() => handleSearch(query, page - 1)}
disabled={page === 1 || loading}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Previous
</button>
<button
onClick={() => handleSearch(query, page + 1)}
disabled={page === totalPages || loading}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Next
</button>
</div>
</div>
)}
</div>
)}
{/* Empty State */}
{!loading && airports.length === 0 && query.length >= 2 && (
<div className="bg-white rounded-lg shadow p-12 text-center">
<p className="text-gray-500">No airports found for "{query}"</p>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,157 @@
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { scanApi } from '../api';
import type { Scan } from '../api';
export default function Dashboard() {
const [scans, setScans] = useState<Scan[]>([]);
const [loading, setLoading] = useState(true);
const [stats, setStats] = useState({
total: 0,
pending: 0,
running: 0,
completed: 0,
failed: 0,
});
useEffect(() => {
loadScans();
}, []);
const loadScans = async () => {
try {
setLoading(true);
const response = await scanApi.list(1, 10);
const scanList = response.data.data;
setScans(scanList);
// Calculate stats
setStats({
total: response.data.pagination.total,
pending: scanList.filter(s => s.status === 'pending').length,
running: scanList.filter(s => s.status === 'running').length,
completed: scanList.filter(s => s.status === 'completed').length,
failed: scanList.filter(s => s.status === 'failed').length,
});
} catch (error) {
console.error('Failed to load scans:', error);
} finally {
setLoading(false);
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed':
return 'bg-green-100 text-green-800';
case 'running':
return 'bg-blue-100 text-blue-800';
case 'pending':
return 'bg-yellow-100 text-yellow-800';
case 'failed':
return 'bg-red-100 text-red-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString();
};
if (loading) {
return (
<div className="flex justify-center items-center h-64">
<div className="text-gray-500">Loading...</div>
</div>
);
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold text-gray-900">Dashboard</h2>
<Link
to="/scans"
className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md text-sm font-medium"
>
+ New Scan
</Link>
</div>
{/* Stats Cards */}
<div className="grid grid-cols-1 md:grid-cols-5 gap-4 mb-8">
<div className="bg-white p-6 rounded-lg shadow">
<div className="text-sm font-medium text-gray-500">Total Scans</div>
<div className="text-3xl font-bold text-gray-900 mt-2">{stats.total}</div>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<div className="text-sm font-medium text-gray-500">Pending</div>
<div className="text-3xl font-bold text-yellow-600 mt-2">{stats.pending}</div>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<div className="text-sm font-medium text-gray-500">Running</div>
<div className="text-3xl font-bold text-blue-600 mt-2">{stats.running}</div>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<div className="text-sm font-medium text-gray-500">Completed</div>
<div className="text-3xl font-bold text-green-600 mt-2">{stats.completed}</div>
</div>
<div className="bg-white p-6 rounded-lg shadow">
<div className="text-sm font-medium text-gray-500">Failed</div>
<div className="text-3xl font-bold text-red-600 mt-2">{stats.failed}</div>
</div>
</div>
{/* Recent Scans */}
<div className="bg-white rounded-lg shadow">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-semibold text-gray-900">Recent Scans</h3>
</div>
<div className="divide-y divide-gray-200">
{scans.length === 0 ? (
<div className="px-6 py-12 text-center text-gray-500">
No scans yet. Create your first scan to get started!
</div>
) : (
scans.map((scan) => (
<Link
key={scan.id}
to={`/scans/${scan.id}`}
className="block px-6 py-4 hover:bg-gray-50 cursor-pointer"
>
<div className="flex items-center justify-between">
<div className="flex-1">
<div className="flex items-center space-x-3">
<span className="font-medium text-gray-900">
{scan.origin} {scan.country}
</span>
<span
className={`px-2 py-1 text-xs font-medium rounded-full ${getStatusColor(
scan.status
)}`}
>
{scan.status}
</span>
</div>
<div className="mt-1 text-sm text-gray-500">
{scan.start_date} to {scan.end_date} {scan.adults} adult(s) {scan.seat_class}
</div>
{scan.total_routes > 0 && (
<div className="mt-1 text-sm text-gray-500">
{scan.total_routes} routes {scan.total_flights} flights found
</div>
)}
</div>
<div className="text-sm text-gray-500">
{formatDate(scan.created_at)}
</div>
</div>
</Link>
))
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,194 @@
import { useEffect, useState } from 'react';
import { logApi } from '../api';
import type { LogEntry } from '../api';
export default function Logs() {
const [logs, setLogs] = useState<LogEntry[]>([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [level, setLevel] = useState<string>('');
const [search, setSearch] = useState('');
const [searchQuery, setSearchQuery] = useState('');
useEffect(() => {
loadLogs();
}, [page, level, searchQuery]);
const loadLogs = async () => {
try {
setLoading(true);
const response = await logApi.list(page, 50, level || undefined, searchQuery || undefined);
setLogs(response.data.data);
setTotalPages(response.data.pagination.pages);
} catch (error) {
console.error('Failed to load logs:', error);
} finally {
setLoading(false);
}
};
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
setSearchQuery(search);
setPage(1);
};
const getLevelColor = (logLevel: string) => {
switch (logLevel) {
case 'DEBUG': return 'bg-gray-100 text-gray-700';
case 'INFO': return 'bg-blue-100 text-blue-700';
case 'WARNING': return 'bg-yellow-100 text-yellow-700';
case 'ERROR': return 'bg-red-100 text-red-700';
case 'CRITICAL': return 'bg-red-200 text-red-900';
default: return 'bg-gray-100 text-gray-700';
}
};
const formatTimestamp = (timestamp: string) => {
return new Date(timestamp).toLocaleString();
};
return (
<div>
<h2 className="text-2xl font-bold text-gray-900 mb-6">Logs</h2>
{/* Filters */}
<div className="bg-white rounded-lg shadow p-6 mb-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Level Filter */}
<div>
<label htmlFor="level" className="block text-sm font-medium text-gray-700 mb-2">
Log Level
</label>
<select
id="level"
value={level}
onChange={(e) => {
setLevel(e.target.value);
setPage(1);
}}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All Levels</option>
<option value="DEBUG">DEBUG</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
{/* Search */}
<div>
<label htmlFor="search" className="block text-sm font-medium text-gray-700 mb-2">
Search Messages
</label>
<form onSubmit={handleSearch} className="flex space-x-2">
<input
type="text"
id="search"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search log messages..."
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
type="submit"
className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md text-sm font-medium"
>
Search
</button>
</form>
</div>
</div>
{/* Clear Filters */}
{(level || searchQuery) && (
<div className="mt-4">
<button
onClick={() => {
setLevel('');
setSearch('');
setSearchQuery('');
setPage(1);
}}
className="text-sm text-blue-600 hover:text-blue-700"
>
Clear Filters
</button>
</div>
)}
</div>
{/* Logs List */}
{loading ? (
<div className="flex justify-center items-center h-64">
<div className="text-gray-500">Loading logs...</div>
</div>
) : (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-semibold text-gray-900">Log Entries</h3>
</div>
{logs.length === 0 ? (
<div className="px-6 py-12 text-center text-gray-500">
No logs found
</div>
) : (
<>
<div className="divide-y divide-gray-200">
{logs.map((log, index) => (
<div key={index} className="px-6 py-4">
<div className="flex items-start space-x-3">
<span className={`px-2 py-1 text-xs font-medium rounded ${getLevelColor(log.level)}`}>
{log.level}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm text-gray-900 break-words">
{log.message}
</p>
<div className="mt-1 flex items-center space-x-4 text-xs text-gray-500">
<span>{formatTimestamp(log.timestamp)}</span>
{log.module && <span>Module: {log.module}</span>}
{log.function && <span>Function: {log.function}</span>}
{log.line && <span>Line: {log.line}</span>}
</div>
</div>
</div>
</div>
))}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center">
<div className="text-sm text-gray-500">
Page {page} of {totalPages}
</div>
<div className="flex space-x-2">
<button
onClick={() => setPage(page - 1)}
disabled={page === 1}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Previous
</button>
<button
onClick={() => setPage(page + 1)}
disabled={page === totalPages}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Next
</button>
</div>
</div>
)}
</>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,384 @@
import { Fragment, useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { scanApi } from '../api';
import type { Scan, Route, Flight } from '../api';
export default function ScanDetails() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [scan, setScan] = useState<Scan | null>(null);
const [routes, setRoutes] = useState<Route[]>([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const [sortField, setSortField] = useState<'min_price' | 'destination' | 'flight_count'>('min_price');
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
const [expandedRoute, setExpandedRoute] = useState<string | null>(null);
const [flightsByDest, setFlightsByDest] = useState<Record<string, Flight[]>>({});
const [loadingFlights, setLoadingFlights] = useState<string | null>(null);
useEffect(() => {
if (id) {
loadScanDetails();
}
}, [id, page]);
// Auto-refresh while scan is running
useEffect(() => {
if (!scan || (scan.status !== 'pending' && scan.status !== 'running')) {
return;
}
const interval = setInterval(() => {
loadScanDetails();
}, 3000); // Poll every 3 seconds
return () => clearInterval(interval);
}, [scan?.status, id]);
useEffect(() => {
// Sort routes when sort field or direction changes
const sorted = [...routes].sort((a, b) => {
let aVal: any = a[sortField];
let bVal: any = b[sortField];
if (sortField === 'min_price') {
aVal = aVal ?? Infinity;
bVal = bVal ?? Infinity;
}
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1;
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1;
return 0;
});
setRoutes(sorted);
}, [sortField, sortDirection]);
const loadScanDetails = async () => {
try {
setLoading(true);
const [scanResponse, routesResponse] = await Promise.all([
scanApi.get(Number(id)),
scanApi.getRoutes(Number(id), page, 20),
]);
setScan(scanResponse.data);
setRoutes(routesResponse.data.data);
setTotalPages(routesResponse.data.pagination.pages);
} catch (error) {
console.error('Failed to load scan details:', error);
} finally {
setLoading(false);
}
};
const handleSort = (field: typeof sortField) => {
if (sortField === field) {
setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc');
} else {
setSortField(field);
setSortDirection('asc');
}
};
const toggleFlights = async (destination: string) => {
if (expandedRoute === destination) {
setExpandedRoute(null);
return;
}
setExpandedRoute(destination);
if (flightsByDest[destination]) return; // already loaded
setLoadingFlights(destination);
try {
const resp = await scanApi.getFlights(Number(id), destination, 1, 200);
setFlightsByDest((prev) => ({ ...prev, [destination]: resp.data.data }));
} catch {
setFlightsByDest((prev) => ({ ...prev, [destination]: [] }));
} finally {
setLoadingFlights(null);
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'completed': return 'bg-green-100 text-green-800';
case 'running': return 'bg-blue-100 text-blue-800';
case 'pending': return 'bg-yellow-100 text-yellow-800';
case 'failed': return 'bg-red-100 text-red-800';
default: return 'bg-gray-100 text-gray-800';
}
};
const formatPrice = (price?: number) => {
return price ? `${price.toFixed(2)}` : 'N/A';
};
if (loading && !scan) {
return (
<div className="flex justify-center items-center h-64">
<div className="text-gray-500">Loading...</div>
</div>
);
}
if (!scan) {
return (
<div className="text-center py-12">
<p className="text-gray-500">Scan not found</p>
</div>
);
}
return (
<div>
{/* Header */}
<div className="mb-6">
<button
onClick={() => navigate('/')}
className="text-blue-500 hover:text-blue-700 mb-4"
>
Back to Dashboard
</button>
<div className="flex justify-between items-start">
<div>
<h2 className="text-2xl font-bold text-gray-900">
{scan.origin} {scan.country}
</h2>
<p className="text-gray-600 mt-1">
{scan.start_date} to {scan.end_date} {scan.adults} adult(s) {scan.seat_class}
</p>
</div>
<span className={`px-3 py-1 text-sm font-medium rounded-full ${getStatusColor(scan.status)}`}>
{scan.status}
</span>
</div>
</div>
{/* Progress Bar (for running scans) */}
{(scan.status === 'pending' || scan.status === 'running') && (
<div className="bg-white p-4 rounded-lg shadow mb-6">
<div className="flex justify-between items-center mb-2">
<span className="text-sm font-medium text-gray-700">
{scan.status === 'pending' ? 'Initializing...' : 'Scanning in progress...'}
</span>
<span className="text-sm text-gray-600">
{scan.routes_scanned} / {scan.total_routes > 0 ? scan.total_routes : '?'} routes
</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2.5">
<div
className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
style={{
width: scan.total_routes > 0
? `${Math.min((scan.routes_scanned / scan.total_routes) * 100, 100)}%`
: '0%'
}}
></div>
</div>
<p className="text-xs text-gray-500 mt-2">
Auto-refreshing every 3 seconds...
</p>
</div>
)}
{/* Stats */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<div className="bg-white p-4 rounded-lg shadow">
<div className="text-sm text-gray-500">Total Routes</div>
<div className="text-2xl font-bold text-gray-900 mt-1">{scan.total_routes}</div>
</div>
<div className="bg-white p-4 rounded-lg shadow">
<div className="text-sm text-gray-500">Routes Scanned</div>
<div className="text-2xl font-bold text-gray-900 mt-1">{scan.routes_scanned}</div>
</div>
<div className="bg-white p-4 rounded-lg shadow">
<div className="text-sm text-gray-500">Total Flights</div>
<div className="text-2xl font-bold text-gray-900 mt-1">{scan.total_flights}</div>
</div>
</div>
{/* Routes Table */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-semibold text-gray-900">Routes Found</h3>
</div>
{routes.length === 0 ? (
<div className="px-6 py-12 text-center">
{scan.status === 'completed' ? (
<div>
<p className="text-gray-500 text-lg">No routes found</p>
<p className="text-gray-400 text-sm mt-2">No flights available for the selected route and dates.</p>
</div>
) : scan.status === 'failed' ? (
<div>
<p className="text-red-500 text-lg">Scan failed</p>
{scan.error_message && (
<p className="text-gray-500 text-sm mt-2">{scan.error_message}</p>
)}
</div>
) : (
<div>
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-4"></div>
<p className="text-gray-500 text-lg">Scanning in progress...</p>
<p className="text-gray-400 text-sm mt-2">
Routes will appear here as they are discovered.
</p>
</div>
)}
</div>
) : (
<>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50">
<tr>
<th
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
onClick={() => handleSort('destination')}
>
Destination {sortField === 'destination' && (sortDirection === 'asc' ? '↑' : '↓')}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
City
</th>
<th
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
onClick={() => handleSort('flight_count')}
>
Flights {sortField === 'flight_count' && (sortDirection === 'asc' ? '↑' : '↓')}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Airlines
</th>
<th
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
onClick={() => handleSort('min_price')}
>
Min Price {sortField === 'min_price' && (sortDirection === 'asc' ? '↑' : '↓')}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Avg Price
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Max Price
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{routes.map((route) => (
<Fragment key={route.id}>
<tr
key={route.id}
className="hover:bg-gray-50 cursor-pointer"
onClick={() => toggleFlights(route.destination)}
>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center gap-2">
<span className="text-gray-400 text-xs">
{expandedRoute === route.destination ? '▼' : '▶'}
</span>
<div>
<div className="font-medium text-gray-900">{route.destination}</div>
<div className="text-sm text-gray-500">{route.destination_name}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{route.destination_city || 'N/A'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{route.flight_count}
</td>
<td className="px-6 py-4 text-sm text-gray-500">
<div className="max-w-xs truncate">
{route.airlines.join(', ')}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-green-600">
{formatPrice(route.min_price)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatPrice(route.avg_price)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatPrice(route.max_price)}
</td>
</tr>
{expandedRoute === route.destination && (
<tr key={`${route.id}-flights`}>
<td colSpan={7} className="px-0 py-0 bg-gray-50">
{loadingFlights === route.destination ? (
<div className="px-8 py-4 text-sm text-gray-500">Loading flights...</div>
) : (
<table className="w-full text-sm">
<thead>
<tr className="bg-gray-100 text-xs text-gray-500 uppercase">
<th className="px-8 py-2 text-left">Date</th>
<th className="px-4 py-2 text-left">Airline</th>
<th className="px-4 py-2 text-left">Departure</th>
<th className="px-4 py-2 text-left">Arrival</th>
<th className="px-4 py-2 text-left font-semibold text-green-700">Price</th>
</tr>
</thead>
<tbody>
{(flightsByDest[route.destination] || []).map((f) => (
<tr key={f.id} className="border-t border-gray-200 hover:bg-white">
<td className="px-8 py-2 text-gray-700">{f.date}</td>
<td className="px-4 py-2 text-gray-600">{f.airline || '—'}</td>
<td className="px-4 py-2 text-gray-600">{f.departure_time || '—'}</td>
<td className="px-4 py-2 text-gray-600">{f.arrival_time || '—'}</td>
<td className="px-4 py-2 font-medium text-green-600">
{f.price != null ? `${f.price.toFixed(2)}` : '—'}
</td>
</tr>
))}
{(flightsByDest[route.destination] || []).length === 0 && (
<tr>
<td colSpan={5} className="px-8 py-3 text-gray-400 text-center">
No flight details available
</td>
</tr>
)}
</tbody>
</table>
)}
</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center">
<div className="text-sm text-gray-500">
Page {page} of {totalPages}
</div>
<div className="flex space-x-2">
<button
onClick={() => setPage(page - 1)}
disabled={page === 1}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Previous
</button>
<button
onClick={() => setPage(page + 1)}
disabled={page === totalPages}
className="px-3 py-1 border border-gray-300 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
>
Next
</button>
</div>
</div>
)}
</>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,299 @@
import { useState } from 'react';
import { scanApi } from '../api';
import type { CreateScanRequest } from '../api';
import AirportSearch from '../components/AirportSearch';
export default function Scans() {
const [destinationMode, setDestinationMode] = useState<'country' | 'airports'>('country');
const [formData, setFormData] = useState<CreateScanRequest>({
origin: '',
country: '',
window_months: 3,
seat_class: 'economy',
adults: 1,
});
const [selectedAirports, setSelectedAirports] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
setLoading(true);
try {
// Validate airports mode has at least one airport selected
if (destinationMode === 'airports' && selectedAirports.length === 0) {
setError('Please add at least one destination airport');
setLoading(false);
return;
}
// Build request based on destination mode
const requestData: any = {
origin: formData.origin,
window_months: formData.window_months,
seat_class: formData.seat_class,
adults: formData.adults,
};
if (destinationMode === 'country') {
requestData.country = formData.country;
} else {
requestData.destinations = selectedAirports;
}
const response = await scanApi.create(requestData);
setSuccess(`Scan created successfully! ID: ${response.data.id}`);
// Reset form
setFormData({
origin: '',
country: '',
window_months: 3,
seat_class: 'economy',
adults: 1,
});
setSelectedAirports([]);
// Redirect to dashboard after 2 seconds
setTimeout(() => {
window.location.href = '/';
}, 2000);
} catch (err: any) {
const errorMessage = err.response?.data?.message || 'Failed to create scan';
setError(errorMessage);
} finally {
setLoading(false);
}
};
const handleChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
) => {
const { name, value } = e.target;
setFormData((prev) => ({
...prev,
[name]: name === 'adults' || name === 'window_months' ? parseInt(value) : value,
}));
};
return (
<div>
<h2 className="text-2xl font-bold text-gray-900 mb-6">Create New Scan</h2>
<div className="bg-white rounded-lg shadow p-6 max-w-2xl">
<form onSubmit={handleSubmit} className="space-y-6">
{/* Origin Airport */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Origin Airport (IATA Code)
</label>
<AirportSearch
value={formData.origin}
onChange={(value) => setFormData((prev) => ({ ...prev, origin: value }))}
placeholder="e.g., BDS, MUC, FRA"
/>
<p className="mt-1 text-sm text-gray-500">
Enter 3-letter IATA code (e.g., BDS for Brindisi)
</p>
</div>
{/* Destination Mode Toggle */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-3">
Destination Mode
</label>
<div className="flex space-x-2 mb-4">
<button
type="button"
onClick={() => setDestinationMode('country')}
className={`flex-1 px-4 py-2 text-sm font-medium rounded-md ${
destinationMode === 'country'
? 'bg-blue-500 text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Search by Country
</button>
<button
type="button"
onClick={() => setDestinationMode('airports')}
className={`flex-1 px-4 py-2 text-sm font-medium rounded-md ${
destinationMode === 'airports'
? 'bg-blue-500 text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
}`}
>
Search by Airports
</button>
</div>
{/* Country Mode */}
{destinationMode === 'country' ? (
<div>
<label htmlFor="country" className="block text-sm font-medium text-gray-700 mb-2">
Destination Country (2-letter code)
</label>
<input
type="text"
id="country"
name="country"
value={formData.country}
onChange={handleChange}
maxLength={2}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="e.g., DE, IT, ES"
/>
<p className="mt-1 text-sm text-gray-500">
ISO 2-letter country code (e.g., DE for Germany)
</p>
</div>
) : (
/* Airports Mode */
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Destination Airports
</label>
<div className="space-y-2">
<AirportSearch
value=""
onChange={(code) => {
if (code && code.length === 3 && !selectedAirports.includes(code)) {
setSelectedAirports([...selectedAirports, code]);
}
}}
clearAfterSelect
required={false}
placeholder="Search and add airports..."
/>
{/* Selected airports list */}
{selectedAirports.length > 0 && (
<div className="flex flex-wrap gap-2 mt-2">
{selectedAirports.map((code) => (
<div
key={code}
className="inline-flex items-center px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
>
<span className="font-medium">{code}</span>
<button
type="button"
onClick={() => setSelectedAirports(selectedAirports.filter((c) => c !== code))}
className="ml-2 text-blue-600 hover:text-blue-800"
>
×
</button>
</div>
))}
</div>
)}
<p className="text-sm text-gray-500">
{selectedAirports.length === 0
? 'Search and add destination airports (up to 50)'
: `${selectedAirports.length} airport(s) selected`}
</p>
</div>
</div>
)}
</div>
{/* Search Window */}
<div>
<label htmlFor="window_months" className="block text-sm font-medium text-gray-700 mb-2">
Search Window (months)
</label>
<input
type="number"
id="window_months"
name="window_months"
value={formData.window_months}
onChange={handleChange}
min={1}
max={12}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<p className="mt-1 text-sm text-gray-500">
Number of months to search (1-12)
</p>
</div>
{/* Seat Class */}
<div>
<label htmlFor="seat_class" className="block text-sm font-medium text-gray-700 mb-2">
Seat Class
</label>
<select
id="seat_class"
name="seat_class"
value={formData.seat_class}
onChange={handleChange}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="economy">Economy</option>
<option value="premium">Premium Economy</option>
<option value="business">Business</option>
<option value="first">First Class</option>
</select>
</div>
{/* Number of Adults */}
<div>
<label htmlFor="adults" className="block text-sm font-medium text-gray-700 mb-2">
Number of Adults
</label>
<input
type="number"
id="adults"
name="adults"
value={formData.adults}
onChange={handleChange}
min={1}
max={9}
required
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<p className="mt-1 text-sm text-gray-500">
Number of adult passengers (1-9)
</p>
</div>
{/* Error Message */}
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
{error}
</div>
)}
{/* Success Message */}
{success && (
<div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded">
{success}
</div>
)}
{/* Submit Button */}
<div className="flex justify-end space-x-3">
<button
type="button"
onClick={() => window.location.href = '/'}
className="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
>
Cancel
</button>
<button
type="submit"
disabled={loading}
className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-md text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? 'Creating...' : 'Create Scan'}
</button>
</div>
</form>
</div>
</div>
);
}