Skip to content

SIHProjectio/kmrl-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

37 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

KMRL Train Management System - Backend API

A comprehensive Django-based backend system for managing metro train operations, fleet management, depot operations, fitness certificates, and user accounts for Kochi Metro Rail Limited (KMRL).

πŸ“‹ Table of Contents

πŸ›  Tech Stack

  • Framework: Django REST Framework
  • Database: PostgreSQL/SQLite
  • Authentication: Token-based authentication
  • API Format: JSON REST API

πŸš€ Quick Start

Installation

# Clone the repository
git clone <repository-url>
cd kmrl-backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

pip install pywin32 # if using windows

# Run migrations
python manage.py migrate

# Create superuser
python manage.py createsuperuser

# Start server
python manage.py runserver

Environment Variables

Create a .env file in the root directory:

DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_URL=your-database-url
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_HOST_USER=your-email
EMAIL_HOST_PASSWORD=your-password

πŸ” Authentication

The API uses Token-based authentication. Include the token in the Authorization header:

Authorization: Token bd1a2fa1c0435f432170e0d5c75f956d50a41bc3

Getting Authentication Token

Login

POST /api/accounts/auth/login/
Content-Type: application/json

{
  "email": "user@kmrl.com",
  "password": "password123"
}

Response

{
  "token": "bd1a2fa1c0435f432170e0d5c75f956d50a41bc3",
  "user": {
    "id": "uuid",
    "email": "user@kmrl.com",
    "first_name": "John",
    "last_name": "Doe"
  }
}

πŸ“– API Documentation

Base URLs

  • Accounts App: http://localhost:8000/api/v1/accounts
  • Fleet Management App: http://localhost:8000/api/v1/fleet_management
  • Depot Management App: http://localhost:8000/api/v1/depot-management
  • Fitness Certificates App: http://localhost:8000/api/v1/fitness-certificate

πŸ‘€ Accounts App API

Authentication Endpoints

Method Endpoint Description
POST /auth/login/ User login
POST /auth/token/ Alternative login method
POST /auth/logout/ User logout
POST /auth/change-password/ Change password
POST /auth/reset-password-request/ Request password reset

Profile Management

Method Endpoint Description
GET /profile/ Get user profile
PUT /profile/ Update user profile (full)
PATCH /profile/ Update user profile (partial)
GET /preferences/ Get user preferences
PUT /preferences/ Update preferences (full)
PATCH /preferences/ Update preferences (partial)

Dashboard

Method Endpoint Description
GET /dashboard/stats/ Get dashboard statistics

Department Management

Method Endpoint Description Query Parameters
GET /departments/ List all departments has_fitness_authority, search
GET /departments/{id}/ Get department details -
POST /departments/ Create new department -
PUT /departments/{id}/ Update department (full) -
PATCH /departments/{id}/ Update department (partial) -
DELETE /departments/{id}/ Delete department (soft) -

Role Management

Method Endpoint Description Query Parameters
GET /roles/ List all roles department, role_type, search
GET /roles/{id}/ Get role details -
POST /roles/ Create new role -
PUT /roles/{id}/ Update role (full) -
PATCH /roles/{id}/ Update role (partial) -
DELETE /roles/{id}/ Delete role -

User Management

Method Endpoint Description Query Parameters
GET /users/ List all users is_active, shift_type, search, ordering
GET /users/{id}/ Get user details -
POST /users/ Create new user -
PUT /users/{id}/ Update user (full) -
PATCH /users/{id}/ Update user (partial) -
DELETE /users/{id}/ Delete user (soft) -
POST /users/{id}/assign_role/ Assign role to user -
POST /users/{id}/revoke_role/ Revoke role from user -
POST /users/{id}/reset_password/ Reset user password -
POST /users/{id}/lock_account/ Lock user account -
POST /users/{id}/unlock_account/ Unlock user account -

Activity Monitoring

Method Endpoint Description Query Parameters
GET /activities/ List user activities user, activity_type, affected_object_type, search
GET /activities/{id}/ Get activity details -

Session Monitoring

Method Endpoint Description Query Parameters
GET /sessions/ List user sessions user, is_active, ordering
GET /sessions/{id}/ Get session details -

πŸš‚ Fleet Management App API

Trainset Type Management

Method Endpoint Description
GET /trainset-types/ Get all trainset types
POST /trainset-types/ Create new trainset type
GET /trainset-types/{id}/ Get specific trainset type
PUT /trainset-types/{id}/ Update trainset type
DELETE /trainset-types/{id}/ Delete trainset type

Trainset Management

Method Endpoint Description Query Parameters
GET /trainsets/ List all trainsets service_status, available_only, page, page_size, search, min_mileage, max_mileage, maintenance_due, ordering
POST /trainsets/ Create new trainset -
GET /trainsets/{id}/ Get trainset details -
PATCH /trainsets/{id}/ Update trainset -
POST /trainsets/{id}/update_mileage/ Update trainset mileage -
POST /trainsets/{id}/update_service_status/ Update service status -
GET /trainsets/fleet_overview/ Get fleet statistics -
GET /trainsets/available_for_service/ Get available trainsets -
GET /trainsets/maintenance_due/ Get maintenance due trainsets days

Car Management

Method Endpoint Description Query Parameters
GET /cars/ List all cars trainset, car_type
POST /cars/ Create new car -
GET /cars/{id}/ Get car details -
PATCH /cars/{id}/ Update car -

Component Type Management

Method Endpoint Description Query Parameters
GET /component-types/ List component types category, critical_component
POST /component-types/ Create component type -
GET /component-types/{id}/ Get component type details -

Component Management

Method Endpoint Description Query Parameters
GET /components/ List all components trainset, health_status, critical_only, maintenance_due, min_health_score
POST /components/ Create new component -
GET /components/{id}/ Get component details -
POST /components/{id}/update_health/ Update component health -
GET /components/critical_components/ Get critical components with poor health -
GET /components/maintenance_due_components/ Get components due for maintenance -

Mileage Log Management

Method Endpoint Description Query Parameters
GET /mileage-logs/ List mileage logs trainset, start_date, end_date
POST /mileage-logs/ Create mileage log -
GET /mileage-logs/{id}/ Get mileage log details -
PATCH /mileage-logs/{id}/ Update mileage log -

Performance Metrics

Method Endpoint Description Query Parameters
GET /performance-metrics/ List performance metrics trainset, start_date, end_date, min_on_time_performance, min_service_availability
POST /performance-metrics/ Create performance metrics -
GET /performance-metrics/fleet_performance_summary/ Get fleet performance summary days
GET /performance-metrics/performance_trends/ Get performance trends days

🏭 Depot Management App API

Depot Management

Method Endpoint Description Query Parameters
GET /depots/ List all depots search, ordering
POST /depots/ Create new depot -
GET /depots/{id}/ Get depot details -
PUT /depots/{id}/ Update depot (full) -
PATCH /depots/{id}/ Update depot (partial) -
DELETE /depots/{id}/ Delete depot -
GET /depots/{id}/summary/ Get depot summary -
GET /depots/{id}/bay_occupancy/ Get bay occupancy status -
GET /depots/{id}/utilization_trends/ Get utilization trends -

Track Management

Method Endpoint Description Query Parameters
GET /tracks/ List all tracks depot, track_type, status
POST /tracks/ Create new track -
GET /tracks/{id}/ Get track details -
PATCH /tracks/{id}/ Update track -
DELETE /tracks/{id}/ Delete track -

Stabling Bay Management

Method Endpoint Description Query Parameters
GET /stabling-bays/ List all stabling bays depot, status, priority_level__lte, is_cleaning_bay
POST /stabling-bays/ Create new stabling bay -
GET /stabling-bays/{id}/ Get stabling bay details -
PATCH /stabling-bays/{id}/ Update stabling bay -
DELETE /stabling-bays/{id}/ Delete stabling bay -
GET /stabling-bays/available/ Get available stabling bays -
GET /stabling-bays/occupied/ Get occupied stabling bays -
POST /stabling-bays/{id}/assign_trainset/ Assign trainset to bay -
POST /stabling-bays/{id}/release_trainset/ Release trainset from bay -

Bay Geometry Management

Method Endpoint Description
GET /bay-geometries/ List all bay geometries
POST /bay-geometries/ Create bay geometry relationship
GET /bay-geometries/{id}/ Get bay geometry details
PATCH /bay-geometries/{id}/ Update bay geometry
DELETE /bay-geometries/{id}/ Delete bay geometry

Shunting Plan Management

Method Endpoint Description Query Parameters
GET /shunting-plans/ List all shunting plans status, depot
POST /shunting-plans/ Create new shunting plan -
GET /shunting-plans/{id}/ Get shunting plan details -
PATCH /shunting-plans/{id}/ Update shunting plan -
DELETE /shunting-plans/{id}/ Delete shunting plan -
POST /shunting-plans/{id}/approve/ Approve shunting plan -
POST /shunting-plans/{id}/start_execution/ Start plan execution -
POST /shunting-plans/{id}/complete_execution/ Complete plan execution -
GET /shunting-plans/{id}/movements_summary/ Get movements summary -

Shunting Movement Management

Method Endpoint Description Query Parameters
GET /shunting-movements/ List all movements shunting_plan
POST /shunting-movements/ Create new movement -
GET /shunting-movements/{id}/ Get movement details -
PATCH /shunting-movements/{id}/ Update movement -
DELETE /shunting-movements/{id}/ Delete movement -
POST /shunting-movements/{id}/start_movement/ Start movement execution -
POST /shunting-movements/{id}/complete_movement/ Complete movement -

Cleaning Slot Management

Method Endpoint Description Query Parameters
GET /cleaning-slots/ List all cleaning slots slot_date, status, cleaning_type
POST /cleaning-slots/ Create new cleaning slot -
GET /cleaning-slots/{id}/ Get cleaning slot details -
PATCH /cleaning-slots/{id}/ Update cleaning slot -
DELETE /cleaning-slots/{id}/ Delete cleaning slot -
GET /cleaning-slots/available_slots/ Get available cleaning slots -
GET /cleaning-slots/today_schedule/ Get today's cleaning schedule -
POST /cleaning-slots/{id}/book_slot/ Book cleaning slot -
POST /cleaning-slots/{id}/start_cleaning/ Start cleaning operation -
POST /cleaning-slots/{id}/complete_cleaning/ Complete cleaning operation -

Depot Utilization Management

Method Endpoint Description Query Parameters
GET /utilization/ List utilization records depot, date__gte, date__lte
POST /utilization/ Create utilization record -
GET /utilization/{id}/ Get utilization details -
PATCH /utilization/{id}/ Update utilization record -
DELETE /utilization/{id}/ Delete utilization record -
GET /utilization/performance_summary/ Get performance summary days

Depot Event Management

Method Endpoint Description Query Parameters
GET /events/ List all depot events depot, event_type, severity, event_datetime__date__gte, event_datetime__date__lte
POST /events/ Create new depot event -
GET /events/{id}/ Get event details -
PATCH /events/{id}/ Update depot event -
DELETE /events/{id}/ Delete depot event -
GET /events/active_incidents/ Get active incidents -
POST /events/{id}/resolve_event/ Resolve event -

Depot Equipment Management

Method Endpoint Description Query Parameters
GET /equipment/ List all depot equipment depot, equipment_type, status, search, ordering
POST /equipment/ Create new equipment -
GET /equipment/{id}/ Get equipment details -
PATCH /equipment/{id}/ Update equipment -
DELETE /equipment/{id}/ Delete equipment -
GET /equipment/maintenance_due/ Get equipment due for maintenance days
GET /equipment/equipment_status_summary/ Get equipment status summary -
GET /equipment/critical_equipment/ Get critical equipment -

πŸ“‹ Fitness Certificates App API

Certificate Categories Management

Method Endpoint Description Query Parameters
GET /categories/ List all certificate categories category_type, is_mandatory, search
POST /categories/ Create new certificate category -
GET /categories/{id}/ Get specific certificate category -
PUT /categories/{id}/ Update certificate category (full) -
PATCH /categories/{id}/ Update certificate category (partial) -
DELETE /categories/{id}/ Delete certificate category -
GET /categories/{id}/certificate_types/ Get certificate types for category -
GET /categories/by_department/ Get categories grouped by department -

Create Category Body:

{
    "name": "Test Rolling Stock Category",
    "code": "TRS001",
    "category_type": "ROLLING_STOCK",
    "description": "Test category for rolling stock certificates",
    "issuing_department": "uuid-here",
    "default_validity_days": 365,
    "warning_days_before_expiry": 30,
    "is_mandatory": true,
    "regulatory_reference": "RS-REG-2023-01",
    "compliance_standard": "IEC 62278",
    "priority_level": 1,
    "requires_pre_inspection": true
}

Certificate Types Management

Method Endpoint Description Query Parameters
GET /types/ List all certificate types category, inspection_level, search
POST /types/ Create new certificate type -
GET /types/{id}/ Get specific certificate type -
PUT /types/{id}/ Update certificate type (full) -
PATCH /types/{id}/ Update certificate type (partial) -
DELETE /types/{id}/ Delete certificate type -
GET /types/simple/ Get simplified certificate types for dropdowns -
GET /types/{id}/active_certificates/ Get active certificates for type -
GET /types/{id}/statistics/ Get statistics for certificate type -

Create Certificate Type Body:

{
    "category": "uuid-here",
    "name": "Brake System Certificate",
    "code": "BSC001",
    "description": "Certificate for brake system compliance",
    "inspection_level": "DETAILED",
    "inspection_checklist": [
        "Brake pad condition",
        "Hydraulic system pressure",
        "Emergency brake functionality"
    ],
    "validity_period_days": 365,
    "grace_period_days": 7,
    "renewal_period_days": 30,
    "requires_static_testing": true,
    "requires_dynamic_testing": true,
    "requires_load_testing": false,
    "requires_environmental_testing": false,
    "estimated_inspection_hours": "4.50",
    "inspection_cost": "5000.00",
    "requires_specialized_equipment": true,
    "equipment_required": ["Brake force tester", "Pressure gauge"],
    "applicable_components": ["Brake discs", "Brake pads", "Hydraulic lines"],
    "applicable_systems": ["Braking system", "Safety system"],
    "priority_level": 1
}

Fitness Certificates Management

Method Endpoint Description Query Parameters
GET /certificates/ List all fitness certificates status, compliance_status, date_from, date_to, expiry_status, search
POST /certificates/ Create new certificate -
GET /certificates/{id}/ Get specific certificate -
PUT /certificates/{id}/ Update certificate (full) -
PATCH /certificates/{id}/ Update certificate (partial) -
DELETE /certificates/{id}/ Delete certificate -
POST /certificates/{id}/issue/ Issue certificate -
POST /certificates/{id}/suspend/ Suspend certificate -
POST /certificates/{id}/revoke/ Revoke certificate -
GET /certificates/{id}/history/ Get certificate history -
GET /certificates/expiring_soon/ Get certificates expiring soon days
GET /certificates/expired/ Get expired certificates -
POST /certificates/validate_certificate/ Validate certificate -
GET /certificates/dashboard_summary/ Get dashboard summary -

Create Certificate Body:

{
    "certificate_type": "uuid-here",
    "trainset": "uuid-here",
    "expiry_date": "2026-01-15",
    "inspection_date": "2024-01-10",
    "inspection_duration_hours": "4.50",
    "inspection_location": "Depot A - Bay 1",
    "inspector": "uuid-here",
    "test_results": {
        "brake_force": "98%",
        "stopping_distance": "45m",
        "response_time": "1.2s"
    },
    "compliance_score": "95.50",
    "conditions": "Monthly brake inspection required",
    "operational_limitations": ["Max speed 80 km/h in wet conditions"],
    "inspection_cost": "5000.00",
    "certification_fee": "500.00"
}

Issue Certificate Body:

{
    "inspection_data": {
        "test_results": {
            "brake_force": "98%",
            "stopping_distance": "45m",
            "response_time": "1.2s"
        },
        "compliance_score": 95.5,
        "defects_found": [],
        "corrective_actions": [],
        "conditions": "Monthly brake inspection required",
        "limitations": ["Max speed 80 km/h in wet conditions"]
    }
}

Inspection Schedules Management

Method Endpoint Description Query Parameters
GET /inspections/ List all inspection schedules status, inspection_type, search
POST /inspections/ Create new inspection schedule -
GET /inspections/{id}/ Get specific inspection schedule -
PUT /inspections/{id}/ Update inspection schedule (full) -
PATCH /inspections/{id}/ Update inspection schedule (partial) -
DELETE /inspections/{id}/ Delete inspection schedule -
POST /inspections/{id}/start/ Start inspection -
POST /inspections/{id}/complete/ Complete inspection -
POST /inspections/{id}/cancel/ Cancel inspection -
GET /inspections/calendar/ Get calendar view of inspections start_date, end_date
GET /inspections/capacity/ Get inspection capacity for date date

Create Inspection Schedule Body:

{
    "trainset": 1,
    "certificate_types": [1, 2],
    "inspection_type": "NEW",
    "scheduled_date": "2024-02-15",
    "scheduled_time": "09:00:00",
    "estimated_duration_hours": "6.00",
    "inspection_location": "Depot A - Inspection Bay 1",
    "depot": 1,
    "inspection_bay": 1,
    "lead_inspector": 2,
    "prerequisite_certificates": [],
    "prerequisite_maintenance": ["Brake pad replacement", "Hydraulic fluid check"],
    "estimated_cost": "8000.00"
}

Certificate Renewals Management

Method Endpoint Description Query Parameters
GET /renewals/ List all renewals renewal_status, search
POST /renewals/ Create new renewal -
GET /renewals/{id}/ Get specific renewal -
PUT /renewals/{id}/ Update renewal (full) -
PATCH /renewals/{id}/ Update renewal (partial) -
DELETE /renewals/{id}/ Delete renewal -
POST /renewals/{id}/approve/ Approve renewal -
POST /renewals/{id}/reject/ Reject renewal -
GET /renewals/pending/ Get pending renewals -

Create Renewal Body:

{
    "original_certificate": 1,
    "requires_full_inspection": true,
    "requires_documentation_review": true,
    "requires_performance_testing": false,
    "renewal_fee": "1000.00",
    "inspection_cost": "5000.00",
    "notes": "Standard renewal process",
    "conditions_for_renewal": "Complete brake system inspection required"
}

Certificate Compliance Management

Method Endpoint Description Query Parameters
GET /compliance/ List all compliance records overall_compliance, eligible_for_revenue_service
GET /compliance/{id}/ Get specific compliance record -
POST /compliance/{id}/update_status/ Update compliance status -
GET /compliance/summary/ Get compliance summary -
GET /compliance/high_risk/ Get high-risk compliance cases -

Notifications Management

Method Endpoint Description Query Parameters
GET /notifications/ List all notifications notification_type, delivery_status
POST /notifications/ Create notification -
GET /notifications/{id}/ Get specific notification -
PUT /notifications/{id}/ Update notification (full) -
PATCH /notifications/{id}/ Update notification (partial) -
DELETE /notifications/{id}/ Delete notification -
POST /notifications/{id}/mark_delivered/ Mark notification as delivered -
POST /notifications/{id}/mark_read/ Mark notification as read -
GET /notifications/unread/ Get unread notifications -

Create Notification Body:

{
    "notification_type": "EXPIRY_WARNING",
    "title": "Certificate Expiring Soon",
    "message": "Certificate BSC001-2024-0001 will expire in 30 days",
    "certificate": 1,
    "trainset": 1,
    "recipient_users": [2, 3],
    "recipient_departments": [1],
    "channel": "EMAIL",
    "priority": "HIGH",
    "requires_response": false
}

Certificate Templates Management

Method Endpoint Description Query Parameters
GET /templates/ List all templates certificate_type, is_active, search
POST /templates/ Create new template -
GET /templates/{id}/ Get specific template -
PUT /templates/{id}/ Update template (full) -
PATCH /templates/{id}/ Update template (partial) -
DELETE /templates/{id}/ Delete template -
POST /templates/{id}/generate_certificate/ Generate certificate from template -

Create Template Body:

{
    "certificate_type": 1,
    "template_name": "Standard Brake Certificate Template",
    "version": "1.0",
    "header_content": "KMRL FITNESS CERTIFICATE",
    "body_template": "This is to certify that trainset {{trainset_number}} has been inspected for {{certificate_type}} compliance...",
    "footer_content": "This certificate is valid until {{expiry_date}}",
    "page_size": "A4",
    "orientation": "PORTRAIT",
    "font_family": "Arial",
    "font_size": 12,
    "logo_url": "https://example.com/logo.png",
    "watermark_text": "KMRL OFFICIAL",
    "color_scheme": {
        "primary": "#003366",
        "secondary": "#666666",
        "accent": "#0066CC"
    },
    "includes_qr_code": true,
    "qr_code_position": "bottom-right",
    "digital_signature_required": true
}

Custom API Endpoints

Method Endpoint Description Query Parameters
GET /trainset-status/ Get trainset certificate status trainset_id
GET /expiry-alerts/ Get certificate expiry alerts type, days
GET /analytics/ Get certificate analytics start_date, end_date
POST /bulk-operations/ Perform bulk operations -
GET /reports/ Generate reports type, start_date, end_date, format

Bulk Operations Body (Suspend):

{
    "operation": "bulk_suspend",
    "certificate_ids": [1, 2, 3],
    "reason": "Safety audit findings require immediate suspension"
}

Bulk Operations Body (Renew):

{
    "operation": "bulk_renew",
    "certificate_ids": [4, 5, 6]
}

Bulk Operations Body (Export):

{
    "operation": "bulk_export",
    "certificate_ids": [1, 2, 3, 4, 5]
}

Validate Certificate Body:

{
    "certificate_number": "BSC001-2024-0001",
    "trainset_number": "T001",
    "validation_date": "2024-01-15"
}

πŸ— Apps Overview

Accounts App

Handles user management, authentication, roles, departments, and activity monitoring.

Key Features:

  • Token-based authentication
  • Role-based access control
  • User profile management
  • Activity logging
  • Session monitoring
  • Department and role management

Main Models:

  • User (Custom user model)
  • Department
  • Role
  • UserRoleAssignment
  • UserActivity
  • UserSession
  • UserPreferences

Fleet Management App

Manages train fleet operations, maintenance, and performance tracking.

Key Features:

  • Trainset lifecycle management
  • Component health monitoring
  • Maintenance scheduling
  • Performance analytics
  • Mileage tracking
  • Fleet overview and statistics

Main Models:

  • TrainsetType
  • Trainset
  • Car
  • ComponentType
  • Component
  • MileageLog
  • PerformanceMetrics

Depot Management App

Manages depot operations, stabling, shunting, cleaning, and equipment.

Key Features:

  • Depot and track management
  • Stabling bay allocation and tracking
  • Shunting plan creation and execution
  • Cleaning slot scheduling and management
  • Equipment tracking and maintenance
  • Utilization monitoring and reporting
  • Event logging and incident management

Main Models:

  • Depot
  • Track
  • StablingBay
  • BayGeometry
  • ShuntingPlan
  • ShuntingMovement
  • CleaningSlot
  • DepotUtilization
  • DepotEvent
  • DepotEquipment

Fitness Certificates App

Manages train fitness certificates, inspections, compliance, and regulatory requirements.

Key Features:

  • Certificate category and type management
  • Certificate lifecycle management (create, issue, suspend, revoke, renew)
  • Inspection scheduling and execution
  • Compliance monitoring and reporting
  • Certificate template management
  • Notification system for expiry alerts
  • Bulk operations support
  • Analytics and reporting dashboard
  • Certificate validation system

Main Models:

  • CertificateCategory
  • CertificateType
  • FitnessCertificate
  • InspectionSchedule
  • CertificateRenewal
  • CertificateCompliance
  • CertificateNotification
  • CertificateTemplate

❌ Error Handling

Standard Error Response Format

{
  "error": "Error message",
  "details": {
    "field_name": ["Specific error details"]
  },
  "status_code": 400
}

Common HTTP Status Codes

  • 200 - Success
  • 201 - Created
  • 400 - Bad Request
  • 401 - Unauthorized
  • 403 - Forbidden
  • 404 - Not Found
  • 500 - Internal Server Error

πŸ§ͺ Testing

Using the REST Files

The repository includes comprehensive test files:

  • fleet_management_test.rest - Fleet management API tests
  • accounts_test.rest - Accounts API tests
  • depot_management_test.rest - Depot management API tests
  • fitness_certificate_test.rest - Fitness certificates API tests

Test Categories

  1. Authentication Tests - Login, logout, token validation
  2. CRUD Operations - Create, read, update, delete operations
  3. Filtering & Search - Query parameter testing
  4. Error Scenarios - Invalid data, unauthorized access
  5. Bulk Operations - Multiple record operations
  6. Performance Tests - Analytics and reporting endpoints
  7. Operational Workflows - Certificate lifecycle, inspection workflows
  8. Complex Filtering - Multi-parameter filtering and search
  9. Status Management - Testing status transitions and validations
  10. Special Actions - Issue, suspend, revoke, renew operations
  11. Template & Notification Testing - Template generation and notification delivery
  12. Compliance & Analytics - Compliance monitoring and analytics endpoints

πŸ“Š Data Models Overview

User Management

  • User: Core user model with profile information
  • Department: Organizational departments with fitness certificate authority
  • Role: User roles with permissions
  • UserRoleAssignment: Links users to roles with validity periods

Fleet Management

  • Trainset: Individual train units with operational data
  • Car: Individual cars within trainsets
  • Component: Trackable components with health monitoring
  • PerformanceMetrics: Daily performance tracking data

Depot Management

Core Infrastructure

  • Depot: Main depot facilities with operational details
  • Track: Individual tracks within depots
  • StablingBay: Specific bays for trainset parking
  • BayGeometry: Spatial relationships between bays

Operations Management

  • ShuntingPlan: Planned trainset movements
  • ShuntingMovement: Individual movement operations
  • CleaningSlot: Scheduled cleaning operations
  • DepotUtilization: Daily operational metrics

Equipment & Events

  • DepotEquipment: Equipment inventory and status
  • DepotEvent: Operational events and incidents

Fitness Certificates Management

Certificate Structure

  • CertificateCategory: Categories of certificates (Rolling Stock, Infrastructure, etc.)
  • CertificateType: Specific types within categories with inspection requirements
  • FitnessCertificate: Individual certificates with full lifecycle tracking

Operations & Workflow

  • InspectionSchedule: Scheduled inspections for certificate issuance/renewal
  • CertificateRenewal: Renewal processes and approvals
  • CertificateCompliance: Compliance status tracking per trainset

Supporting Systems

  • CertificateTemplate: Template management for certificate generation
  • CertificateNotification: Automated notification system
  • Analytics & Reporting: Comprehensive analytics and reporting capabilities

πŸ”„ Common Query Parameters

Filtering

  • search - Full-text search across relevant fields
  • ordering - Sort results (prefix with - for descending)
  • page & page_size - Pagination controls

Date Filtering

  • start_date & end_date - Date range filtering
  • date__gte & date__lte - Greater/less than equal date filtering
  • date_from & date_to - Alternative date range filtering
  • Format: YYYY-MM-DD

Boolean Filters

  • is_active, available_only, maintenance_due - Boolean filters
  • is_mandatory, requires_pre_inspection - Certificate-specific boolean filters
  • Values: true or false

Certificate-Specific Filters

  • status - Certificate status (DRAFT, ISSUED, SUSPENDED, REVOKED, EXPIRED)
  • compliance_status - Compliance status (COMPLIANT, NON_COMPLIANT, PARTIAL)
  • expiry_status - Expiry status (expiring_soon, expired, renewal_due)
  • category_type - Certificate category type (ROLLING_STOCK, INFRASTRUCTURE, etc.)
  • inspection_level - Inspection level (BASIC, DETAILED, COMPREHENSIVE)
  • notification_type - Notification type (EXPIRY_WARNING, INSPECTION_DUE, etc.)

Depot-Specific Filters

  • depot - Filter by depot ID
  • track_type - Filter tracks by type (STABLING, MAINTENANCE, etc.)
  • cleaning_type - Filter cleaning slots by type
  • event_type - Filter events by type
  • severity - Filter events by severity level

πŸ“ Notes for Frontend Developers

  1. Authentication Required: Most endpoints require authentication token
  2. UUID Primary Keys: Most models use UUID as primary keys
  3. Pagination: Large datasets are paginated (default: 20 items per page)
  4. Soft Deletes: Most delete operations are soft deletes (records marked inactive)
  5. Timestamps: All models include created_at and updated_at fields
  6. Validation: Comprehensive input validation with detailed error messages
  7. Permissions: Role-based permissions control access to different endpoints
  8. Complex Filtering: All apps support advanced filtering with multiple parameters
  9. Status Management: Certificates have comprehensive status workflow management
  10. Operational Actions: Special endpoints for operational actions (issue, suspend, revoke, etc.)
  11. Bulk Operations: Support for bulk certificate operations (suspend, renew, export)
  12. Template System: Dynamic certificate template generation with customizable layouts
  13. Notification System: Automated notifications for expiry, inspection due, etc.
  14. Analytics & Reporting: Comprehensive analytics with multiple report formats (JSON, CSV, PDF)
  15. Compliance Tracking: Real-time compliance status monitoring per trainset

πŸš€ Getting Started

  1. Base URL: Use http://localhost:8000 for local development
  2. Authentication: Obtain token via /api/v1/accounts/auth/login/
  3. Headers: Always include Authorization: Token <your-token>
  4. Content-Type: Use application/json for POST/PUT/PATCH requests
  5. Error Handling: Check HTTP status codes and parse error messages
  6. Testing: Use the provided .rest files as API usage examples
  7. Certificate Management: Start with categories, then types, then certificates
  8. Workflow Management: Follow status transitions for certificate lifecycle
  9. Template Usage: Create templates before generating certificates
  10. Bulk Operations: Use bulk endpoints for multiple certificate operations
  11. Analytics: Leverage analytics endpoints for dashboard and reporting needs

For detailed implementation examples, refer to the test files included in the repository.

Certificate Workflow Example

  1. Setup Categories & Types:

    • Create certificate categories via /categories/
    • Define certificate types via /types/
  2. Schedule Inspections:

    • Create inspection schedules via /inspections/
    • Start and complete inspections
  3. Issue Certificates:

    • Create certificate drafts via /certificates/
    • Issue certificates via /certificates/{id}/issue/
  4. Monitor Compliance:

    • Check compliance status via /compliance/
    • Monitor expiry alerts via /expiry-alerts/
  5. Handle Renewals:

    • Create renewals via /renewals/
    • Approve/reject renewals
  6. Generate Reports:

    • Use analytics endpoints for insights
    • Generate various report formats

About

This repo will contain the entire backend for our KMRL web app

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages