You are an expert AI full-stack developer and startup consultant tasked with creating a single-page application (SPA) for managing fuel rationing during crises. The application, codenamed 'FuelGuard', will help governments and fuel distributors control and monitor fuel distribution at the station level to prevent shortages and manage consumer demand. This prompt will guide an AI assistant (like Cursor or Gemini) to build this application from scratch.
**1. PROJECT OVERVIEW:**
FuelGuard aims to address the critical challenge of fuel scarcity and distribution control during national emergencies or periods of extreme price volatility, as exemplified by Slovenia's recent fuel rationing measures. The core problem is the difficulty in enforcing consumption limits, tracking real-time supply, and providing accurate oversight to prevent panic buying and ensure equitable distribution. FuelGuard provides a centralized SaaS platform for governments and fuel retailers to implement, manage, and monitor fuel rationing policies effectively. The value proposition lies in ensuring national energy security, maintaining public order, and enabling data-driven decision-making during critical times through real-time monitoring and automated compliance checks.
**2. TECH STACK:**
- **Frontend Framework:** React.js (using functional components and hooks)
- **UI Library/Styling:** Tailwind CSS for rapid, utility-first styling.
- **State Management:** Zustand for efficient global and local state management due to its simplicity and performance.
- **Routing:** React Router DOM for client-side navigation.
- **Data Fetching:** Axios for making HTTP requests to a hypothetical backend API.
- **Form Handling:** React Hook Form for efficient and performant form management.
- **Charting:** Recharts for data visualization on the dashboard.
- **Date/Time:** date-fns for robust date and time manipulation.
- **Build Tool:** Vite for fast development and optimized builds.
**3. CORE FEATURES:**
FuelGuard will be a responsive, multi-user, single-page application with distinct views for different user roles (e.g., Station Attendant, Station Manager, National Administrator).
* **3.1. Station Attendant View:**
* **User Flow:** Logs in, selects the station they manage. Sees a simple interface to input fuel sales. For each transaction, they enter the vehicle type (private/commercial), and the amount of fuel dispensed. The system automatically checks against the station's daily limit for that vehicle type and either approves the sale or shows a warning if the limit is reached. They can also manually input current tank levels at the start/end of shift.
* **Details:** Simple form input, real-time limit validation, transaction logging.
* **3.2. Station Manager View:**
* **User Flow:** Logs in, views the dashboard for their specific station(s). Can set/adjust daily fuel purchase limits for private and commercial vehicles based on national guidelines. Views sales reports, current stock levels, and attendant activity. Can view historical data for their station.
* **Details:** Dashboard with key metrics (sales, stock, limits), form for setting limits, historical data tables/charts.
* **3.3. National Administrator View:**
* **User Flow:** Logs in to a comprehensive dashboard displaying national fuel status. Views aggregated data from all stations: total consumption, adherence to limits, stock levels across regions, potential shortages identified by the system. Can configure national rationing policies (e.g., modify base limits, set specific dates for restrictions). Accesses detailed reports and can export data.
* **Details:** Multi-chart dashboard, policy configuration forms, user management interface, data export functionality.
**4. UI/UX DESIGN:**
* **Layout:** A clean, intuitive, and responsive dashboard layout. A persistent sidebar navigation for different sections (Dashboard, Transactions, Settings, Reports). Main content area displays relevant information based on the selected section and user role.
* **Color Palette:** Primary: A calming, trustworthy blue (#007bff). Secondary: A neutral gray (#6c757d) for text and backgrounds. Accent: A warning orange/red (#dc3545) for alerts and critical data, and a success green (#28a745) for positive indicators. White (#ffffff) for backgrounds and cards.
* **Typography:** A clean, readable sans-serif font like 'Inter' or 'Roboto'. Clear hierarchy using font sizes and weights.
* **Responsive Design:** Mobile-first approach. Sidebar collapses into a hamburger menu on smaller screens. Content reflows and resizes gracefully. Tables should be scrollable or use card-based layouts on mobile.
* **Interactivity:** Smooth transitions between pages/sections. Clear loading states (spinners, skeleton screens). Interactive charts and data tables.
**5. COMPONENT BREAKDOWN:**
* `App.jsx`: Main application component, sets up routing.
* `Layout.jsx`: Main layout component including Header, Sidebar, and Content area.
* `Sidebar.jsx`: Navigation menu component. Props: `userRole`, `navItems`.
* `Header.jsx`: Top navigation bar, includes user profile and logout button. Props: `userName`.
* `Dashboard.jsx`: Role-specific dashboard component. Contains sub-components based on `userRole`.
* `StationDashboard.jsx`: Displays station-specific metrics. Props: `stationData`.
* `NationalDashboard.jsx`: Displays aggregated national metrics. Props: `nationalData`, `charts`.
* `TransactionForm.jsx`: Form for station attendants to log fuel sales. Props: `onSubmit`, `currentLimits`.
* `LimitSettingsForm.jsx`: Form for station managers to set fuel limits. Props: `initialLimits`, `onSubmit`.
* `DataTable.jsx`: Generic reusable table component. Props: `columns`, `data`.
* `ChartComponent.jsx`: Reusable chart component using Recharts. Props: `chartData`, `config`.
* `LoginForm.jsx`: User login form.
* `LoadingSpinner.jsx`: Displays a loading indicator.
* `AlertMessage.jsx`: Displays informational, success, or error messages.
**6. DATA MODEL:**
We'll use Zustand for state management. Data will be managed in memory for the SPA, with mock APIs simulating backend interactions. In a real-world scenario, this would interact with a RESTful API.
* **`authStore`:**
```javascript
{
user: { id: string, name: string, role: 'station_attendant' | 'station_manager' | 'national_admin', stationId?: string },
isAuthenticated: boolean,
login: (credentials) => Promise<void>,
logout: () => void
}
```
* **`fuelStore`:**
```javascript
{
stations: Station[],
selectedStationId: string | null,
currentStockLevels: { [stationId: string]: { private: number, commercial: number } },
salesTransactions: Transaction[],
dailyLimits: { [stationId: string]: { private: number, commercial: number } },
fetchStations: () => Promise<void>,
updateStockLevel: (stationId, type, amount) => void,
addTransaction: (transaction) => void,
updateDailyLimits: (stationId, limits) => void,
// ... other actions for fetching reports, national data etc.
}
```
* **`Transaction` Interface:**
```typescript
interface Transaction {
id: string;
stationId: string;
timestamp: string; // ISO 8601 format
vehicleType: 'private' | 'commercial';
fuelAmountLiters: number;
pricePerLiter?: number; // Optional
totalCost?: number; // Optional
isWithinLimit: boolean;
}
```
* **`Station` Interface:**
```typescript
interface Station {
id: string;
name: string;
address: string;
region: string;
currentPrivateStock: number;
currentCommercialStock: number;
dailyPrivateLimit: number;
dailyCommercialLimit: number;
}
```
**Mock Data Service (`mockApi.js`):**
Simulates API calls using `setTimeout` to mimic network latency. Functions like `loginUser`, `fetchStationData`, `submitTransaction`, `getNationalReport`, etc.
**7. ANIMATIONS & INTERACTIONS:**
* **Page Transitions:** Subtle fade-in/fade-out transitions between routes using `Framer Motion` or CSS transitions.
* **Button Hovers:** Slight scale-up or background color change on interactive elements.
* **Form Input Focus:** Border color change or subtle glow effect on focused input fields.
* **Loading States:** Use `react-loading-skeleton` or custom CSS spinners within buttons and data areas when data is being fetched. Skeleton loaders for table rows and chart placeholders.
* **Data Updates:** Animate chart data updates (e.g., bar charts smoothly transition to new heights). Use subtle color flashes for significant data changes in tables (e.g., stock level dropping below a threshold).
* **Limit Warnings:** When a transaction approaches or exceeds a limit, provide immediate visual feedback: change the input border color to orange/red, display an `AlertMessage` component.
**8. EDGE CASES:**
* **Authentication:** Handle invalid login credentials, expired sessions (redirect to login).
* **No Data:** Display user-friendly messages when no stations are found, no transactions exist for a period, or the dashboard has no data to show (e.g., 'No transactions logged today.'). Use empty states with clear calls to action.
* **Network Errors:** Implement global error handling for API requests. Display `AlertMessage` with a 'Retry' option.
* **Input Validation:** Use `react-hook-form` for client-side validation: ensure numeric inputs are valid numbers, amounts are positive, required fields are filled. Server-side validation (simulated) should also be considered.
* **Limit Logic:** Precisely handle the accumulation of fuel sales throughout the day against the set limits. Consider edge cases like multiple attendants logging sales simultaneously (ensure atomic updates if a real backend were used).
* **Accessibility (a11y):** Use semantic HTML5 elements. Ensure sufficient color contrast. Provide `aria-labels` for interactive elements, especially icons. Ensure keyboard navigability for all components.
* **Role-Based Rendering:** Strictly enforce which components and data are visible/editable based on the logged-in user's role.
**9. SAMPLE DATA:**
* **User Roles:**
```json
{
"station_attendant": {"id": "user1", "name": "Ali Veli", "role": "station_attendant", "stationId": "stn001"},
"station_manager": {"id": "user2", "name": "Ayşe Yılmaz", "role": "station_manager", "stationId": "stn001"},
"national_admin": {"id": "admin1", "name": "Mehmet Kaya", "role": "national_admin"}
}
```
* **Stations List:**
```json
[
{
"id": "stn001",
"name": "Milli Petrol - Merkez",
"address": "Atatürk Bulvarı No: 10",
"region": "Marmara",
"currentPrivateStock": 15000,
"currentCommercialStock": 25000,
"dailyPrivateLimit": 50,
"dailyCommercialLimit": 150
},
{
"id": "stn002",
"name": "Güneş Enerji - Kıyı",
"address": "Sahil Yolu No: 5",
"region": "Ege",
"currentPrivateStock": 8000,
"currentCommercialStock": 18000,
"dailyPrivateLimit": 45,
"dailyCommercialLimit": 120
}
]
```
* **Sample Transaction:**
```json
{
"id": "txn123",
"stationId": "stn001",
"timestamp": "2023-10-27T10:30:00Z",
"vehicleType": "private",
"fuelAmountLiters": 48,
"isWithinLimit": true
}
```
* **Sample National Report Data:**
```json
{
"totalStations": 150,
"activeStations": 145,
"totalFuelDispensedToday": 750000,
"averagePrivateLimitAdherence": "95%",
"averageCommercialLimitAdherence": "92%",
"criticalStockAlerts": 5,
"regionalSummary": [
{"region": "Marmara", "consumption": 300000, "adherence": "96%"},
{"region": "Ege", "consumption": 200000, "adherence": "94%"}
]
}
```
* **Sample Limit Settings:**
```json
{
"stationId": "stn001",
"limits": {
"private": 50,
"commercial": 150
}
}
```
**10. DEPLOYMENT NOTES:**
* **Build Command:** `npm run build` (using Vite).
* **Environment Variables:** Use `.env` files for configuration (e.g., `VITE_API_BASE_URL`). Ensure sensitive keys are not committed to version control.
* **Performance Optimizations:** Vite's build process includes optimizations. Code splitting will be handled by the router. Lazy loading components where appropriate (e.g., modals, less frequently accessed sections).
* **HTTPS:** Ensure deployment on a platform that supports HTTPS (essential for a SaaS application).
* **CI/CD:** Set up a CI/CD pipeline (e.g., GitHub Actions, GitLab CI) for automated testing and deployment to a hosting provider (e.g., Vercel, Netlify, AWS Amplify).