# Fleet Tracker Pro Documentation

A comprehensive GPS tracking and fleet management solution

#### Welcome!

Thank you for purchasing Fleet Tracker Pro. This documentation will help you install, configure, and use all features of the system.

### View Screenshots Gallery

Explore all features through 17 comprehensive screenshots organized by category

View Screenshot Gallery

### What is Fleet Tracker Pro?

Fleet Tracker Pro is a professional GPS tracking and fleet management system designed for businesses of all sizes. It provides real-time vehicle tracking, comprehensive reporting, geofencing, driver management, and much more.

### Built for Developers

Fleet Tracker Pro is a comprehensive development framework that provides developers with a complete set of mapping and reporting libraries, designed for easy customization and rapid deployment. Whether you're building a custom fleet management solution or integrating advanced tracking features into existing systems, our architecture ensures seamless integration and scalability.

##### Advanced Mapping Infrastructure

Built on Leaflet.js, the industry-leading open-source mapping library, Fleet Tracker Pro supports multiple map providers out of the box:

- OpenStreetMap - Free, open-source maps
- Google Maps - Streets, Satellite, Hybrid, Terrain
- Yandex Maps - Map, Satellite, Hybrid, Traffic, Panorama

- 2GIS - Detailed city maps
- Stamen - Artistic map styles
- Custom Tiles - Add your own tile servers

##### Modern UI Framework

The frontend is built with Tabler, a premium open-source admin dashboard template based on Bootstrap 5. This provides:

- Clean, modern, and responsive design system
- 2,100+ Tabler Icons for consistent iconography
- Dark/Light theme support with automatic switching
- Pre-built components ready for customization
- Mobile-first approach for cross-device compatibility

##### Powerful Component Library

Fleet Tracker Pro includes battle-tested libraries and components:

- Tabulator - Feature-rich data tables with sorting, filtering, editing
- ApexCharts - Interactive, responsive charts and graphs
- Leaflet.draw - Polygon drawing and geofence creation
- Marker Clustering - Performance optimization for thousands of markers
- Custom Helpers - Ready-to-use utilities for common tasks

##### Easy Integration & Customization

Designed with developer experience in mind:

- MVC Architecture - Clean separation of concerns (Laravel)
- RESTful API - JWT-authenticated endpoints for integration
- Modular Components - Reusable JavaScript classes and functions
- Comprehensive Documentation - Every function explained with examples
- Commented Code - Well-documented codebase for easy understanding
- No Framework Lock-in - Use components independently

##### Quick Start for Development Teams

Your development team can get started immediately with our structured codebase. All components are properly namespaced, functions are documented with JSDoc style comments, and the code follows industry best practices. Simply clone, configure, and start building your custom solution!

### Key Benefits

#### Real-Time Tracking

Monitor your entire fleet on interactive maps with live location updates.

#### 12+ Reports

Comprehensive reports for parking, mileage, fuel, speed violations, and more.

#### Geofencing

Create virtual boundaries and get alerts when vehicles enter or exit.

#### Multi-Tenant

Support multiple organizations with isolated data and permissions.

## Installation

### Quick Start (Auto Installer)

1. Upload all files to your web server
2. Navigate to `http://yourdomain.com/install`
3. Follow the 5-step installation wizard
4. Login and start tracking!

Recommended: Use the auto installer for the easiest installation experience.

### Manual Installation

For advanced users who prefer manual setup:

#### 1. Install Dependencies

    composer install --optimize-autoloader --no-dev

#### 2. Configure Environment

    cp env.example.txt .env
    # Edit .env with your database credentials

#### 3. Generate Keys

    php artisan key:generate
    php artisan jwt:secret

#### 4. Import Database

    mysql -u username -p database_name < database/sql/vtc_database_table.sql

#### 5. Import Demo Data (Optional)

    php artisan db:seed --class=DemoDataSeeder

#### 6. Set Permissions

    chmod -R 775 storage bootstrap/cache
    chown -R www-data:www-data storage bootstrap/cache

See README.md for complete manual installation instructions.

## Features Overview

### Real-Time GPS Tracking

- Live vehicle location on interactive maps
- Route history replay
- Speed and direction indicators
- Multiple vehicle tracking simultaneously
- Customizable map markers and colors

### Comprehensive Reporting

12+ report types available:

1. Parking Analysis - Identify parking locations and durations
2. Mileage Tracking - Monitor kilometers and maintenance schedules
3. Vehicle Health - Track performance metrics
4. Working Hours - Business hours compliance
5. Visit Reports - Customer location visits
6. Zone Violations - Geofence breach alerts
7. Speed Violations - Speeding incidents
8. Fuel Consumption - Fuel usage and costs
9. Route Efficiency - Route optimization
10. After Hours Activity - Off-hours monitoring
11. Inspection Schedule - Maintenance tracking
12. Driver Scoring - Driver behavior analysis

### Geofencing

- Create circular geofences (Places)
- Create polygon geofences (Regions)
- Entry/exit detection
- Configurable alerts
- Assign vehicles to specific zones

### User & Permission Management

- Role-based access control
- Granular permissions per module
- Multi-tenant architecture
- User activity tracking

## Getting Started

### 1. First Login

After installation, login with your admin credentials:

- Navigate to `http://yourdomain.com`
- Enter your email and password
- Click "Login"

Security Tip: Change your password immediately after first login!

### 2. Add Your First Vehicle

1. Go to Vehicles → Vehicle List
2. Click + Add Vehicle
3. Fill in vehicle details:
   - Device ID (from GPS tracker)
   - Vehicle Name
   - License Plate
   - Driver Name (optional)
   - Category (optional)
4. Click Save

### 3. Create a Geofence

1. Go to Settings → Places or Regions
2. Click + Add New
3. Click on map to set location or draw polygon
4. Set radius (for places) or complete polygon (for regions)
5. Assign vehicles
6. Click Save

### 4. Generate Your First Report

1. Go to Reports menu
2. Select a report type (e.g., Parking Analysis)
3. Choose vehicle and date range
4. Click Generate Report
5. Export or print as needed

## JavaScript Libraries

Complete reference for all JavaScript libraries and helper functions used in the system.

### HTTP & API Communication

#### http Object

Central HTTP client for making API requests with automatic loading indicators and error handling.

http.post(options)

Make POST request to the server.

    http.post({
        url: '/vehicles-list',
        data: { filter: 'active' }
    }).then((response) => {
        console.log(response.data);
    }).catch((error) => {
        console.error(error);
    });

http.get(options)

Make GET request to the server.

    http.get({
        url: '/api/vehicle/details',
        params: { id: 123 }
    }).then((response) => {
        console.log(response.data);
    });

Base64Helper

Encode and decode data for secure transmission.

    // Encode data
    const postModel = Base64Helper.encode({ id: 123, name: 'Vehicle' });

    // Decode data
    const decoded = Base64Helper.decode(encodedString);

### Map Management (Leaflet)

LeafletMap Class

Main class for managing Leaflet maps, markers, and polygons.

###### Initialize Map

    const myMap = new LeafletMap();
    myMap.initMap('mapDiv', {
        zoomLevelDefault: 13,
        enablePolygonDrawing: true,
        chunkedLoading: true
    });

###### Add Markers

    const markers = [{
        id: 'vehicle-123',
        coord: [40.7128, -74.0060],
        label: 'Vehicle Name',
        popup: 'Vehicle Details',
        icon: {
            name: 'ti ti-car',
            color: 'red',
            direction: 45
        },
        draggable: false
    }];
    myMap.pinMarkers(markers);

###### Remove Markers

    // Remove specific marker
    myMap.removeMarkers('vehicle-123');

    // Remove all markers
    myMap.removeMarkers();

###### Make Marker Draggable

    myMap.makeMarkerDraggable('vehicle-123', true, function(markerId, newLatLng) {
        console.log('Marker moved to:', newLatLng);
    });

###### Add Polygon

    const polygonId = myMap.addPolygon({
        coords: [
            [40.7128, -74.0060],
            [40.7580, -73.9855],
            [40.7614, -73.9776]
        ],
        color: '#d32f2f',
        fillColor: '#ffcdd2',
        fillOpacity: 0.3,
        label: 'Geofence Area'
    });

###### Remove Polygon

    myMap.removePolygon(polygonId);

###### Focus on Marker

    myMap.focusMarker('vehicle-123');

###### Fit Bounds

    // Fit to all markers
    myMap.fitBounds();

    // Fit to specific markers
    myMap.fitBounds(['vehicle-123', 'vehicle-456']);

### Table Management (Tabulator)

createTabulator(elementId, options)

Create a fully-featured data table with sorting, filtering, and CRUD operations.

    const table = createTabulator('#myTable', {
        buttons: [
            {
                label: __('Add New'),
                icon: 'fas fa-plus',
                icon_color: 'success',
                func: addNewRow
            }
        ],
        data: myData,
        movableRows: true,
        columns: [
            {
                title: __('Name'),
                field: 'name',
                editor: 'input',
                validator: 'required'
            },
            {
                title: __('Status'),
                field: 'status_id',
                formatter: function(cell) {
                    return cell.getValue() == 1 ? 'Active' : 'Inactive';
                }
            },
            {
                title: __('Action'),
                formatter: function() {
                    return `
                        <button class="btn btn-sm edit-btn">Edit</button>
                        <button class="btn btn-sm delete-btn">Delete</button>
                    `;
                },
                cellClick: function(e, cell) {
                    if (e.target.closest('.edit-btn')) {
                        editRow(cell.getRow().getData());
                    }
                }
            }
        ]
    });

    // Add row
    table.addRow({ name: 'New Item', status_id: 1 });

    // Update data
    table.updateData([{ id: 1, name: 'Updated Name' }]);

    // Get all data
    const allData = table.getData();

tabulatorLocalize()

Get localized strings for Tabulator UI elements.

    const localizedOptions = tabulatorLocalize();
    // Returns object with pagination, headerFilters texts in current language

### UI/UX Components

showNotification(type, message)

Display toast notifications to the user.

    // Success notification
    showNotification('success', __('Data saved successfully'));

    // Error notification
    showNotification('error', __('An error occurred'));

    // Info notification
    showNotification('info', __('Please wait'));

    // Warning notification
    showNotification('warning', __('Check your input'));

showConfirmDialog(options)

Show confirmation dialog before dangerous actions.

    showConfirmDialog({
        title: __('Delete Vehicle'),
        message: __('Are you sure you want to delete this vehicle?'),
        confirmText: __('Delete'),
        cancelText: __('Cancel'),
        type: 'danger',
        onConfirm: function() {
            // Delete action here
            deleteVehicle(vehicleId);
        }
    });

popoverInit()

Initialize Bootstrap popovers for dynamically added content.

    // After adding new content to DOM
    popoverInit();

Theme Management

Get and set user's theme preference.

    // Get current theme
    const currentTheme = getTheme();

    // Set theme
    setTheme('dark');  // or 'light'

### Localization

__(key, replacements)

Translate text to current user's language.

    // Simple translation
    const text = __('Welcome');

    // Translation with placeholders
    const message = __('Hello :name', { name: 'John' });

    // Use in HTML
    document.title = __('Vehicle Tracking System');

### Helper Functions

rand_id()

Generate random unique identifier.

    const uniqueId = rand_id();
    // Example: 'x8k2n9m4p'

menuSets(menuModel)

Set active menu items and show/hide menu sections.

    menuSets({
        actives: ['vehicles', 'tracking'],
        shows: ['reports']
    });

onAppReady(callback)

Execute code when application is fully loaded.

    onAppReady(function() {
        // Initialize your code here
        initializeMap();
        loadVehicles();
    });

### Charts (ApexCharts)

Speed Chart

Create interactive speed charts.

    const speedChart = new ApexCharts(document.querySelector("#speedChart"), {
        series: [{
            name: __('Speed'),
            data: speedData
        }],
        chart: {
            type: 'line',
            height: 350
        },
        xaxis: {
            categories: timeLabels
        },
        yaxis: {
            title: {
                text: __('Speed (km/h)')
            }
        }
    });
    speedChart.render();

### Complete Example

##### Full Page Example

Here's a complete example showing how different components work together:

    // Initialize when app is ready
    onAppReady(function() {
        // Set active menu
        menuSets({
            actives: ['vehicles'],
            shows: []
        });

        // Initialize map
        const myMap = new LeafletMap();
        myMap.initMap('mapDiv', {
            zoomLevelDefault: 13,
            enablePolygonDrawing: false
        });

        // Load vehicles data
        http.post({
            url: '/vehicles-list'
        }).then((response) => {
            const data = response.data;

            // Create table
            const table = createTabulator('#vehiclesTable', {
                data: data,
                buttons: [{
                    label: __('Add Vehicle'),
                    icon: 'fas fa-plus',
                    icon_color: 'success',
                    func: function() {
                        showVehicleForm();
                    }
                }],
                columns: [
                    {
                        title: __('Name'),
                        field: 'name',
                        editor: 'input'
                    },
                    {
                        title: __('Status'),
                        field: 'status',
                        formatter: function(cell) {
                            const value = cell.getValue();
                            return value == 1
                                ? '<span class="badge bg-success">Active</span>'
                                : '<span class="badge bg-danger">Inactive</span>';
                        }
                    }
                ]
            });

            // Add markers to map
            const markers = data.map(vehicle => ({
                id: vehicle.did,
                coord: [vehicle.latitude, vehicle.longitude],
                label: vehicle.name,
                popup: `
                    <strong>${vehicle.name}</strong><br>
                    Speed: ${vehicle.speed} km/h
                `,
                icon: {
                    name: 'ti ti-car',
                    color: vehicle.status == 1 ? 'green' : 'red'
                }
            }));

            myMap.pinMarkers(markers);
            myMap.fitBounds();

            showNotification('success', __('Vehicles loaded successfully'));
        }).catch((error) => {
            showNotification('error', __('Failed to load vehicles'));
        });
    });

##### Best Practices

- Always use `__()` for user-facing text
- Handle errors in HTTP requests with .catch()
- Use `Base64Helper` for sensitive data
- Clean up event listeners when removing elements
- Initialize popovers/tooltips after DOM changes
- Use `onAppReady()` for initialization code

## API Reference

### Authentication

All API requests require JWT authentication token in the header:

    Authorization: Bearer {your_jwt_token}

### Main Endpoints

#### Vehicles

- `POST /api/vehicles/list` - Get all vehicles
- `POST /api/vehicles/add` - Add new vehicle
- `POST /api/vehicles/update` - Update vehicle
- `POST /api/vehicles/delete` - Delete vehicle

#### Reports

- `POST /api/reports/parking-analysis` - Parking analysis data
- `POST /api/reports/mileage-tracking` - Mileage data
- `POST /api/reports/vehicle-health` - Vehicle health data
- And more... (see API documentation for complete list)

#### Users

- `GET /api/users/me` - Get current user profile
- `PATCH /api/users/me` - Update profile
- `POST /api/users` - Create user

## Troubleshooting

### Installation Issues

#### Database Connection Error

- Verify database credentials in .env
- Ensure MySQL service is running
- Check database user has proper permissions
- Try connecting manually: `mysql -u username -p`

#### 500 Internal Server Error

- Check storage/ and bootstrap/cache/ are writable
- Run: `php artisan config:clear`
- Check error logs in storage/logs/laravel.log
- Enable debug mode temporarily: `APP_DEBUG=true` in .env

#### Blank Page

- Verify APP_KEY is set in .env
- Run: `php artisan key:generate`
- Clear browser cache and cookies
- Check file permissions

### Common Issues

#### Maps Not Loading

- Check internet connection (maps use external tile servers)
- Verify no JavaScript errors in browser console (F12)
- Check if map div has height set

#### No Vehicle Data Showing

- Ensure GPS device is sending data
- Check vts_device_logs table for entries
- Verify date range is correct
- Check vehicle status is "Active with Customer" (sts = 3)

## Support

Need help? We're here for you!

#### Contact Support

- Email: support@yoursite.com
- CodeCanyon Support: Via item support tab
- Response Time: Within 24-48 hours

#### Before Contacting Support

1. Check this documentation
2. Review troubleshooting section
3. Check Laravel error logs
4. Try clearing caches

#### When Reporting Issues, Include:

- PHP version: `php -v`
- Laravel version
- Browser and version
- Steps to reproduce the issue
- Error messages or screenshots
- Relevant log entries