Frontend

Getting started

Getting started

Introduction

Project Overview

OnDelivery Dashboard is a comprehensive web-based logistics and delivery management system built with Angular. The application provides a complete suite of tools for managing deliveries, tracking packages, monitoring couriers, handling returns, and generating reports.

Key Features


Technology Stack

Core Framework

UI & Styling

Additional Libraries

Development Tools

Getting started

Starting the project

Prerequisites

Installation

  1. Clone the repository
git clone <repository-url>
cd ondelivery-dash
  1. Install dependencies
npm install
  1. Configure API endpoints Edit src/app/addrezz.ts to set the appropriate API endpoints:
export const OSAS_API = "https://testapi.ondelivery.id";
export const BOOKING_API = "https://demoapisat.ondelivery.id";
export const USAPI_API = "http://localhost:3621";

Running the Application

Development Server

npm start
# or
ng serve

Navigate to http://localhost:4200/. The app will automatically reload on file changes.

Production Build

npm run build

Build artifacts are stored in the dist/ directory with output hashing for cache busting.

Development Build

npm run build-dev

Builds without production optimizations.

Run Tests

npm test

Run Linter

npm run lint
Getting started

Project Architecture

Directory Structure

src/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ account-management/       # Account operations
β”‚   β”œβ”€β”€ admin-menu/                # Admin navigation
β”‚   β”œβ”€β”€ finance-management/        # Financial operations
β”‚   β”œβ”€β”€ home/                      # Dashboard/home page
β”‚   β”œβ”€β”€ incoming-scan/             # Incoming package scanning
β”‚   β”œβ”€β”€ indopaket/                 # Regional package handling
β”‚   β”œβ”€β”€ layouts/                   # Layout components (header, sidebar, breadcrumb)
β”‚   β”œβ”€β”€ login/                     # Authentication
β”‚   β”œβ”€β”€ manifest/                  # Manifest management
β”‚   β”œβ”€β”€ manual-handling/           # Manual handling operations
β”‚   β”œβ”€β”€ marketplace/               # Marketplace integration
β”‚   β”œβ”€β”€ material-component/        # Material Design wrappers
β”‚   β”œβ”€β”€ mitra-courier/             # Courier partner management
β”‚   β”œβ”€β”€ modal/                     # Modal dialogs
β”‚   β”œβ”€β”€ models/                    # Data models
β”‚   β”œβ”€β”€ monitoring-booking/        # Booking monitoring
β”‚   β”œβ”€β”€ monitoring-courier/        # Courier monitoring
β”‚   β”œβ”€β”€ notification/              # Notification system
β”‚   β”œβ”€β”€ outgoing-scan/             # Outgoing package scanning
β”‚   β”œβ”€β”€ package-return/            # Package returns
β”‚   β”œβ”€β”€ package-return-handling/   # Return processing
β”‚   β”œβ”€β”€ pod-approval/              # Proof of Delivery approval
β”‚   β”œβ”€β”€ profile/                   # User profile
β”‚   β”œβ”€β”€ reports/                   # Standard reports
β”‚   β”œβ”€β”€ reports-dc/                # Distribution center reports
β”‚   β”œβ”€β”€ saldo/                     # Account balance
β”‚   β”œβ”€β”€ services/                  # Business logic services
β”‚   β”œβ”€β”€ shared/                    # Shared utilities and components
β”‚   β”œβ”€β”€ tariff/                    # Pricing and tariff
β”‚   β”œβ”€β”€ tracking/                  # Package tracking
β”‚   β”œβ”€β”€ trucking/                  # Trucking operations
β”‚   β”œβ”€β”€ user-manage/               # User management
β”‚   β”œβ”€β”€ waybill/                   # Waybill management
β”‚   β”œβ”€β”€ api.service.ts             # Main API service
β”‚   β”œβ”€β”€ auth.guard.ts              # Authentication guard
β”‚   β”œβ”€β”€ role.guard.ts              # Role-based authorization guard
β”‚   β”œβ”€β”€ app.module.ts              # Root module
β”‚   └── app.routing.ts             # Routing configuration
β”œβ”€β”€ assets/                        # Static assets (images, icons)
β”œβ”€β”€ environments/                  # Environment configurations
└── index.html                     # Main HTML file

Architecture Pattern

The application follows Angular's module-based architecture:

  1. Root Module (app.module.ts) - Core module with essential dependencies
  2. Feature Modules - Lazy-loaded modules for each feature area
  3. Shared Module - Reusable components and utilities
  4. Services - Business logic and API communication
  5. Guards - Route protection and authorization
  6. Models - TypeScript interfaces for data structures

Module Loading Strategy

Development guidelines

Development guidelines

Authentication and security

Authentication Flow

  1. Login (/login)

    • User submits credentials
    • API returns JWT token
    • Token stored in localStorage as jwt
    • User details and roles stored in localStorage
  2. Token Management

    • JWT token sent with every API request via Authorization header
    • Token validated on each route navigation via AuthGuard
    • Invalid tokens redirect to login page
  3. Logout

    • Clear localStorage
    • Redirect to login page

Guards

AuthGuard (auth.guard.ts)

// Usage in routing
{
  path: 'home',
  loadChildren: () => import('./home/home.module').then(m => m.HomeModule),
  canActivate: [AuthGuard]
}

RoleGuard (role.guard.ts)

Security Best Practices

  1. Token Storage: JWT tokens stored in localStorage (consider httpOnly cookies for enhanced security)
  2. HTTPS: Always use HTTPS in production
  3. Token Expiration: Implement token refresh mechanism
  4. XSS Protection: Angular's built-in sanitization helps prevent XSS
  5. CSRF Protection: Use Angular's CSRF token support for POST requests
Development guidelines

Application modules

The application consists of 27+ feature modules, each handling specific business functionality:

Core Modules

1. Home Module (/home)

2. Login Module (/login)

3. Profile Module (/profile)

Waybill Management

4. Waybill Module (/waybill)

Services:

Scanning Operations

5. Incoming Scan Module (/incoming-scan)

Services:

6. Outgoing Scan Module (/outgoing-scan)

Services:

Monitoring & Tracking

7. Tracking Module (/tracking)

8. Monitoring Booking Module (/monitor-booking)

9. Monitoring Courier Module (/monitoring-courier)

Service: MonitoringCourierService

Package Returns

10. Package Return Module (/package-return)

Service: ReturnService

11. Package Return Handling Module (/return-handling)

Reports & Analytics

12. Reports Module (/reports)

Comprehensive reporting system with multiple report types:

Services:

13. Reports DC Module (/reports-dc)

Financial Management

14. Finance Management Module (/finance-management)

Service: FinanceManagementService

15. Tariff Module (/tariff)

16. Saldo Module (/saldo)

Partner & User Management

17. Mitra Courier Module (/mitra-courier)

18. User Management Module (/customer-manage)

19. Account Management Module (/account-management)

Service: AccountManagementService

Logistics Operations

20. Trucking Module (/trucking)

Services:

21. Manifest Module (/manifest)

22. Manual Handling Module (/manual-handling)

Service: ManualHandlingService

23. POD Approval Module (/pod-management)

Service: PodApprovalService

Integration & Communication

24. Marketplace Module (/marketplace)

Service: MarketplaceService

25. Indopaket Module (/indopaket)

Service: IndopaketService

26. Notification Module (/notification)

Service: NotificationService

Utility Modules

27. Models Module (/models)

Development guidelines

Services & API Integration

Main API Service (api.service.ts)

The central service for API communication with the backend.

Key Methods:

Configuration:

// API endpoints defined in addrezz.ts
OSAS_API = "https://testapi.ondelivery.id"
BOOKING_API = "https://demoapisat.ondelivery.id"
USAPI_API = "http://localhost:3621"

Service Categories

1. Scanning Services

Located in services/incoming-scans/ and services/outgoing-scans/

2. Report Services

Located in services/reports/

3. Business Services

Located in services/

HTTP Interceptor Pattern

All services use JWT tokens for authentication:

let customHeaders = new HttpHeaders({
  'Content-Type': 'application/json',
  'authorization': localStorage.getItem('jwt')!
});

PDF & Excel Export Services

PDF Service (pdf.service.ts)

Excel Export

Development guidelines

Routing & Navigation

Route Configuration

All routes are defined in app.routing.ts with lazy loading for performance.

Main Routes

Route Module Access
/ Redirect to /login Public
/login LoginComponent Public
/profile ProfileComponent Authenticated
/home HomeModule Authenticated
/waybill WaybillModule Authenticated
/incoming-scan IncomingScanModule Authenticated
/outgoing-scan OutgoingScanModule Authenticated
/tracking TrackingModule Authenticated
/reports ReportsModule Authenticated
/reports-dc ReportsDcModule Authenticated
/tariff TariffModule Authenticated
/package-return PackageReturnModule Authenticated
/return-handling PackageReturnHandlingModule Authenticated
/manifest ManifestModule Authenticated
/indopaket IndopaketModules Authenticated
/monitor-booking MonitoringBookingModule Authenticated
/monitoring-courier MonitoringCourierModule Authenticated
/mitra-courier MitraCourierModule Authenticated
/marketplace MarketplaceModule Authenticated
/account-management AccountManagementModule Authenticated
/customer-manage UserManageModule Authenticated
/manual-handling ManualHandlingModule Authenticated
/pod-management PodApprovalModule Authenticated
/trucking TruckingModule Authenticated
/finance-management FinanceManagementModule Authenticated
/saldo SaldoModule Authenticated
/notification NotificationModule Authenticated

Navigation Structure

Main Layout (layouts/full/)

Menu Configuration

Menu items are defined in shared/menu-items/ based on user roles.

Development guidelines

UI Components & Styling

Layout System

The application uses Angular Flex Layout for responsive design:

CSS Framework

Bootstrap 5.3.2 provides:

Angular Material Components

Used throughout the application:

Custom Components

Spinner Component (shared/spinner.component)

Loading indicator shown during async operations.

Modal Component (modal/modal.component)

Reusable modal dialog for various purposes.

Accordion Component (shared/accordion/)

Collapsible content panels.

Perfect Scrollbar

Custom scrollbar styling for better aesthetics:

const DEFAULT_PERFECT_SCROLLBAR_CONFIG: PerfectScrollbarConfigInterface = {
  suppressScrollX: true
};

Icons & Images

Development guidelines

State Management

LocalStorage

The application uses browser localStorage for state persistence:

Stored Data:

Observable Pattern (RxJS)

Services use RxJS Observables for reactive data flow:

// Example from ApiService
return this.http.post<any>(OSAS_API + '/auth/signin', payload, { headers });

Components subscribe to Observables:

this.apiService.getUser(username, password).subscribe(
  response => { /* handle response */ },
  error => { /* handle error */ }
);

Service State

Services maintain application state:

Development guidelines

Build & Deployment

Build Configuration

Angular build configuration in angular.json:

Project Name: project (generic name) Output Directory: dist/agent Source Root: src

Build Commands

Development Build

npm run build-dev
# Creates development build with source maps
# Output: dist/agent/

Production Build

npm run build
# Optimized production build
# Features:
#   - Minification
#   - Tree shaking
#   - AOT compilation
#   - Output hashing (cache busting)
# Output: dist/agent/

Build Optimization

Production Optimizations:

Deployment Steps

  1. Build the application
npm run build
  1. Deploy dist/agent/ directory to web server

    • Configure web server for single-page application
    • Redirect all routes to index.html
  2. Configure API endpoints

    • Update src/app/addrezz.ts before building
    • Set production API URLs
  3. Environment Configuration

    • Production: src/environments/environment.prod.ts
    • Development: src/environments/environment.ts

Web Server Configuration

Nginx Example:

server {
    listen 80;
    server_name yourdomain.com;
    root /path/to/dist/agent;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Apache Example:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

Performance Considerations

  1. Lazy Loading - Feature modules loaded on demand
  2. Code Splitting - Separate bundles for vendor and app code
  3. Output Hashing - Cache busting for updated files
  4. Compression - Enable gzip/brotli on web server
  5. CDN - Serve static assets from CDN
Development guidelines

Development guide

Code Style

TypeScript

Angular

Naming Conventions

Component Structure

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.css']
})
export class ComponentNameComponent implements OnInit {
  constructor(private service: SomeService) { }

  ngOnInit(): void {
    // Initialization logic
  }
}

Service Structure

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SomeService {
  constructor(private http: HttpClient) { }

  getData(): Observable<any> {
    const headers = new HttpHeaders({
      'Authorization': localStorage.getItem('jwt')!
    });
    return this.http.get<any>(API_URL, { headers });
  }
}

Best Practices

1. Component Communication

2. Error Handling

this.service.getData().subscribe(
  data => this.data = data,
  error => {
    console.error('Error:', error);
    // Show error message to user
  }
);

3. Memory Management

private subscription: Subscription;

ngOnInit() {
  this.subscription = this.service.getData().subscribe(/*...*/);
}

ngOnDestroy() {
  this.subscription?.unsubscribe();
}

4. Performance

5. Security

Testing

Unit Tests

npm test
# Runs Karma test runner with Jasmine

E2E Tests

npm run e2e
# Runs Protractor for end-to-end tests

Writing Tests

describe('ComponentName', () => {
  let component: ComponentName;
  let fixture: ComponentFixture<ComponentName>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ ComponentName ]
    }).compileComponents();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Linting

npm run lint
# Runs TSLint to check code quality

Fix linting issues automatically:

ng lint --fix

Git Workflow

  1. Create feature branch: git checkout -b feature/feature-name
  2. Make changes and commit: git commit -m "feat: description"
  3. Push to remote: git push origin feature/feature-name
  4. Create pull request for review

Commit Message Format:

Development guidelines

Troubleshooting

Common Issues

1. Cannot connect to API

Symptom: API calls fail with connection errors

Solution:

2. Authentication fails after page refresh

Symptom: User logged out after page refresh

Solution:

3. Lazy-loaded module not found

Symptom: Error when navigating to a route

Solution:

4. Styling issues

Symptom: Components not displaying correctly

Solution:

5. Build errors

Symptom: Build fails with TypeScript errors

Solution:

6. Performance issues

Symptom: Application is slow or unresponsive

Solution:

Debugging Tips

1. Browser DevTools

2. Angular DevTools

Install Angular DevTools Chrome extension:

3. Enable Source Maps

For production debugging, build with source maps:

ng build --source-map

4. Logging

Add console logging for debugging:

console.log('Debug:', variable);
console.error('Error:', error);

Getting Help

  1. Check Angular Documentation: https://angular.io/docs
  2. Check Angular Material Documentation: https://material.angular.io/
  3. Check Stack Overflow: Tag questions with angular and typescript
  4. Review Application Logs: Check browser console and network tab
  5. Contact Development Team: For application-specific issues
Development guidelines

Additional Resources

Official Documentation

Useful Tools

Learning Resources