Skip to content

Latest commit

 

History

History
382 lines (283 loc) · 7.83 KB

File metadata and controls

382 lines (283 loc) · 7.83 KB

Frontend Setup Guide

Complete guide for setting up and running the Delivery Tracking App frontend.

Table of Contents

Prerequisites

  • Node.js 18.x or higher
  • npm 9.x or higher
  • Backend running on http://localhost:8080

Verify Installation

node --version  # Should be v18.x.x or higher
npm --version   # Should be 9.x.x or higher

Installation

1. Install Dependencies

npm install

This installs:

  • React 18
  • Vite (build tool)
  • Leaflet (maps)
  • STOMP.js (WebSocket)
  • ESLint (linting)

2. Verify Backend Connection

Ensure the backend is running:

curl http://localhost:8080/actuator/health

Should return: {"status":"UP"}

Development

Start Development Server

npm run dev

The application will start at http://localhost:5173

Development Features

  • Hot Module Replacement (HMR): Changes reflect instantly
  • Source Maps: Debug directly in browser
  • ESLint: Real-time code quality checks

Available Scripts

# Start development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview

# Run ESLint
npm run lint

Build for Production

1. Create Production Build

npm run build

Output is generated in dist/ folder.

2. Preview Production Build

npm run preview

3. Deploy

Copy the dist/ folder contents to your web server:

# Example: Copy to nginx
sudo cp -r dist/* /var/www/html/

# Or serve with any static file server
npx serve dist

Project Structure

Frontend/
├── src/
│   ├── App.jsx              # Main application component
│   ├── DeliveryTracker.jsx  # Core tracking component with map
│   ├── main.jsx             # Application entry point
│   └── index.css            # Global styles
├── index.html               # HTML template
├── package.json             # Dependencies and scripts
├── vite.config.js           # Vite configuration
├── eslint.config.js         # ESLint rules
└── README.md                # This file

Key Components

DeliveryTracker.jsx

The main component that handles:

  • WebSocket connection to backend
  • Real-time location updates
  • Map visualization with Leaflet
  • Order statistics display
  • ETA and speed calculations

WebSocket Connection

const socket = new WebSocket("ws://localhost:8080/ws");
stompClient = over(socket);

stompClient.connect({}, (frame) => {
  stompClient.subscribe("/topic/location", (message) => {
    const location = JSON.parse(message.body);
    // Update UI with new location
  });
});

Map Configuration

<MapContainer
  center={[18.5204, 73.8567]}  // Default: Pune center
  zoom={13}
  style={{ height: "500px", width: "100%" }}
>
  <TileLayer
    attribution='&copy; OpenStreetMap'
    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
  />
  {/* Markers and polylines */}
</MapContainer>

WebSocket Integration

Connection Flow

  1. Connect: Establish WebSocket connection to ws://localhost:8080/ws
  2. Subscribe: Listen to /topic/location topic
  3. Receive: Handle incoming DeliveryLocation messages
  4. Update: Refresh map markers and order list

Message Format

{
  "orderId": "ORD001",
  "latitude": 18.5074,
  "longitude": 73.8077,
  "status": "in-transit",
  "etaMinutes": 15.5,
  "speedKmh": 25.3,
  "distanceRemainingKm": 5.2,
  "distanceTraveledKm": 3.8,
  "timestamp": "2024-01-15T10:30:00Z",
  "driverName": "John Doe",
  "vehicleId": "VH001"
}

Connection States

State Description
Connecting Initial connection attempt
Connected Successfully connected to WebSocket
Disconnected Connection lost or failed

Customization

Change Default Map Center

Edit DeliveryTracker.jsx:

// Default center coordinates
const nalstopCoords = [18.5204, 73.8567];  // Change to your location

Add Custom Markers

function getCustomIcon(type) {
  return new L.Icon({
    iconUrl: `/icons/${type}.png`,
    iconSize: [40, 40],
    iconAnchor: [20, 40]
  });
}

Modify Color Scheme

function getColor(orderId) {
  const colors = ["blue", "red", "green", "orange", "purple"];
  // Add or modify colors
  const index = orderId.charCodeAt(orderId.length - 1) % colors.length;
  return colors[index];
}

Update Status Badges

const styles = {
  placed: { background: "#e3f2fd", color: "#1976d2" },
  "in-transit": { background: "#fff3e0", color: "#f57c00" },
  delivered: { background: "#e8f5e9", color: "#388e3c" },
  failed: { background: "#ffebee", color: "#d32f2f" },
  // Add custom status
  "custom-status": { background: "#f3e5f5", color: "#7b1fa2" }
};

Change WebSocket URL

For production deployment:

// Development
const socket = new WebSocket("ws://localhost:8080/ws");

// Production
const socket = new WebSocket("wss://your-domain.com/ws");

Environment Variables

Create .env file for environment-specific settings:

# .env.development
VITE_WEBSOCKET_URL=ws://localhost:8080/ws
VITE_API_URL=http://localhost:8080/api

# .env.production
VITE_WEBSOCKET_URL=wss://your-domain.com/ws
VITE_API_URL=https://your-domain.com/api

Use in code:

const socket = new WebSocket(import.meta.env.VITE_WEBSOCKET_URL);

Troubleshooting

WebSocket Connection Failed

Problem: "WebSocket connection failed" in browser console

Solutions:

  1. Verify backend is running: curl http://localhost:8080/actuator/health
  2. Check CORS configuration in backend
  3. Ensure port 8080 is not blocked by firewall

Map Not Loading

Problem: Blank map or tiles not loading

Solutions:

  1. Check internet connection (OpenStreetMap requires internet)
  2. Verify Leaflet CSS is imported:
    import "leaflet/dist/leaflet.css";
  3. Check browser console for 404 errors on tile requests

npm install Errors

Problem: Permission errors during install

Solutions:

# Windows: Run as Administrator
# Or use:
npm install --legacy-peer-deps

# Clear npm cache
npm cache clean --force
rm -rf node_modules
npm install

Port Already in Use

Problem: "Port 5173 is already in use"

Solutions:

# Use different port
npm run dev -- --port 3000

# Or kill process using port 5173
# Windows:
netstat -ano | findstr :5173
taskkill /PID <PID> /F

Build Errors

Problem: ESLint errors preventing build

Solutions:

# Check lint errors
npm run lint

# Auto-fix some issues
npm run lint -- --fix

# Skip lint during build (not recommended)
npm run build -- --mode=production

Browser Compatibility

Browser Version Status
Chrome 90+ Supported
Firefox 88+ Supported
Safari 14+ Supported
Edge 90+ Supported

Performance Tips

  1. Optimize Re-renders: Use React.memo for marker components
  2. Limit Path History: Keep only last 100 points per delivery
  3. Debouncing: Debounce map updates for high-frequency updates
  4. Lazy Loading: Use dynamic imports for heavy components

Next Steps

  1. Customize delivery routes in backend
  2. Add authentication (JWT)
  3. Implement push notifications
  4. Add offline support with service workers

Resources