# TankStopp - Fuel Tracking Web Application

A simple and intuitive web application built with Go to track your fuel station stops and monitor fuel consumption.

## Features

- 📊 **Dashboard** - Overview of all fuel stops with statistics
- ➕ **Add Fuel Stops** - Record new fuel purchases with detailed information
- ✏️ **Edit/Delete** - Modify or remove existing fuel stop records
- 📈 **Statistics** - Track total spending, consumption, and average prices
- 🛣️ **Trip Length Tracking** - Record distance traveled for accurate consumption calculation
- 🔍 **Advanced Filtering** - Filter by date range, fuel type, and location
- 📊 **Monthly Reports** - Detailed monthly fuel consumption analytics
- 💾 **Bulk Operations** - Import/export multiple fuel stops efficiently
- 🔌 **REST API** - JSON endpoints for programmatic access
- 🗄️ **GORM Database** - Modern ORM with optimized queries and relationships
- 📱 **Responsive Design** - Works on desktop and mobile devices
- 📍 **Nearby Stations** - Find fuel stations near your location using OpenStreetMap
- ⚙️ **User Settings** - Manage profile, change password, and account preferences

## Getting Started

### Prerequisites

- Go 1.21 or higher
- SQLite3 (automatically managed by GORM)

### Installation

1. Clone or download the project:
```bash
git clone <repository-url>
cd tankstopp
```

2. Install dependencies:
```bash
go mod tidy
```

3. Run the application:
```bash
go run cmd/main.go
```

4. Open your browser and navigate to:
```
http://localhost:8080
```

### Building for Production

To build a standalone executable:

```bash
go build -o tankstopp cmd/main.go
./tankstopp
```

## Usage

### Adding a Fuel Stop

1. Click "Add New Stop" on the dashboard
2. Fill in the form with:
   - Date of the fuel stop
   - Station name and location
   - Fuel type (Super E5, E10, Diesel, etc.)
   - Amount of fuel in liters
   - Price per liter
   - Total price (calculated automatically)
   - Odometer reading (optional)
   - Notes (optional)

### Viewing Statistics

The dashboard shows:
- Total number of fuel stops
- Total liters purchased
- Total amount spent
- Average price per liter
- Average fuel consumption (if odometer readings are provided)

### Editing Fuel Stops

- Click the "Edit" button on any fuel stop card
- Modify the information and save

### Deleting Fuel Stops

- Click the "Delete" button on any fuel stop card
- Confirm the deletion

## API Endpoints

The application provides REST API endpoints for integration:

### GET /api/fuel-stops
Returns all fuel stops as JSON.

**Query Parameters:**
- `limit` - Number of results per page (default: 50)
- `offset` - Number of results to skip for pagination
- `fuel_type` - Filter by fuel type (e.g., "Diesel", "Super E5")
- `start_date` - Filter from date (YYYY-MM-DD format)
- `end_date` - Filter to date (YYYY-MM-DD format)

### POST /api/fuel-stops
Creates a new fuel stop from JSON data.

Example request body:
```json
{
    "date": "2024-01-15",
    "station_name": "Shell",
    "location": "Hamburg",
    "fuel_type": "Super E5",
    "liters": 45.5,
    "price_per_l": 1.599,
    "total_price": 72.75,
    "currency": "EUR",
    "odometer": 125000,
    "trip_length": 520.5,
    "notes": "Highway stop"
}
```

### GET /api/stats
Returns fuel consumption statistics as JSON.

### GET /api/stats/monthly/{year}
Returns monthly statistics for the specified year.

### POST /api/fuel-stops/bulk
Creates multiple fuel stops in a single transaction.

## Database

The application uses **GORM** (Go Object-Relational Mapping) with SQLite3, which creates a `fuel_stops.db` file in the project directory. The database features include:

### Schema
- `users` table with authentication and user preferences
- `fuel_stops` table with all fuel stop information
- **Foreign key constraints** with cascade delete
- **Automatic indexing** on frequently queried fields
- **Unique constraints** on usernames and emails

### Features
- **Auto-migration** - Schema updates are handled automatically
- **Connection pooling** - Optimized database connections
- **Transaction support** - ACID compliance for data integrity
- **Relationship management** - Efficient joins and preloading
- **Type safety** - Compile-time validation of database operations

### Performance Optimizations
- Prepared statements for faster query execution
- Batch operations for bulk inserts
- Optimized indexes for common query patterns
- Connection pool tuning for concurrent access

## Project Structure

```
tankstopp/
├── cmd/
│   └── main.go              # Application entry point
├── internal/
│   ├── auth/
│   │   └── session.go      # Session management
│   ├── currency/
│   │   └── currency.go     # Multi-currency support
│   ├── database/
│   │   └── db.go           # GORM database operations
│   ├── handlers/
│   │   └── handlers.go     # HTTP handlers & authentication
│   └── models/
│       └── fuelstop.go     # GORM data models
├── templates/
│   ├── base.html           # Base template
│   ├── index.html          # Dashboard
│   ├── add.html            # Add fuel stop form
│   └── edit.html           # Edit fuel stop form
├── static/                 # Static files (CSS, JS, images)
├── go.mod                  # Go module definition
└── README.md               # This file
```

## Technologies Used

- **Backend**: Go with Gorilla Mux for routing
- **Database**: GORM ORM with SQLite3
- **Authentication**: Session-based with bcrypt password hashing
- **Currency**: Multi-currency support with 25+ currencies
- **Frontend**: HTML5, Tabler UI framework, Font Awesome
- **Templates**: Go HTML templates with custom functions

## Consumption Tracking Excellence

### Advanced Trip Analysis
TankStopp provides industry-leading fuel consumption tracking with precise trip-based calculations:

- **Trip Length Input**: Record exact distance traveled since last fillup
- **Automatic Consumption Calculation**: Real-time L/100km calculation per trip
- **Efficiency Ratings**: Categorized efficiency scoring (Excellent, Good, Average, High, Very High)
- **Driving Pattern Recognition**: Highway vs city vs mixed driving analysis
- **Fuel Type Optimization**: Compare efficiency across different fuel grades
- **Improvement Suggestions**: Identify potential efficiency gains

### Consumption Metrics
- **Individual Trip Consumption**: L/100km for each fuel stop
- **Overall Average Consumption**: Weighted average across all trips
- **Fuel Type Comparison**: Efficiency by fuel grade (E5, E10, Diesel, etc.)
- **Seasonal Analysis**: Monthly consumption trend tracking
- **Best/Worst Trip Identification**: Performance benchmarking
- **Cost Efficiency**: Cost per kilometer analysis

### Dual Calculation Methods
1. **Primary**: Trip length-based calculation (most accurate)
2. **Fallback**: Odometer difference calculation (backward compatibility)
3. **Hybrid**: Combines both methods for comprehensive analysis

## Features in Detail

### User Management
- Secure user registration and authentication
- Session-based login with automatic logout
- Multi-currency support with user preferences
- Password hashing with bcrypt

### Fuel Stop Tracking
- Record date, station, location, fuel type
- Track liters purchased and prices with precise decimal storage
- Multi-currency support with automatic formatting
- Calculate total costs automatically
- **Trip length tracking** for accurate fuel consumption calculation
- Optional odometer readings for additional tracking
- **Individual trip consumption display (L/100km)**
- **Real-time consumption analysis** with efficiency ratings
- **Per-trip fuel efficiency comparison** across different driving conditions
- **Fuel type consumption analysis** (highway vs city vs mixed driving)
- Bulk import/export capabilities

### Advanced Filtering & Search
- Filter by date range (start/end dates)
- Filter by fuel type (Diesel, Super E5, E10, etc.)
- Filter by location or station name
- Pagination support for large datasets

### Statistics Dashboard
- Visual overview of fuel consumption patterns
- Total spending and volume tracking across currencies
- Average price monitoring with trend analysis
- **Enhanced fuel consumption calculation** using trip length data
- **Per-trip consumption analysis** with efficiency ratings
- **Best/worst efficiency trip identification** with improvement suggestions
- **Fuel type consumption comparison** across different fuel grades
- **Driving pattern analysis** (highway vs city efficiency)
- **Monthly consumption trends** with seasonal analysis
- **Cost-per-kilometer tracking** for budget planning
- Monthly statistics and reports
- Last fillup information with trip details

### Data Management
- Create, read, update, delete fuel stops with ACID transactions
- Form validation and comprehensive error handling
- Responsive design optimized for mobile use
- Database relationship management
- Automatic schema migrations

### Nearby Fuel Stations
- **Location-based search** using browser geolocation
- **OpenStreetMap integration** for real-world fuel station data
- **Distance calculation** showing stations within 5km radius
- **One-click selection** to auto-fill station name and address
- **Smart sorting** by distance from your current location
- **Detailed information** including brand, operator, and full address
- **Privacy-focused** - location data is only used locally, not stored

### User Settings
- **Profile Management** - Update email address and base currency preference
- **Password Security** - Change password with current password verification
- **Account Statistics** - View total stops, liters, spending, and consumption
- **Currency Preferences** - Set default currency for new fuel stops
- **Account Information** - See member since date and account details
- **Data Management** - Permanently delete account and all associated data
- **Session Security** - Secure password updates with validation

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## Development

### Environment Variables
```bash
# Enable detailed database logging
export DB_DEBUG=true

# Set environment
export ENV=development
```

### Database Development
The application uses GORM for database operations. Key features:
- **Auto-migration**: Schema updates are automatic
- **Query logging**: Enable with `DB_DEBUG=true`
- **Connection pooling**: Optimized for performance
- **Transaction support**: Automatic rollback on errors

### Performance Monitoring
- Health check endpoint available
- Connection pool metrics
- Query performance logging in debug mode

## License

This project is open source and available under the MIT License.

## Support

For issues or questions, please create an issue in the project repository.