API Reference - Simulation API
Working with Simulations using Collections
Interactive Examples
Try these examples with your saved connection. If you haven't connected yet, visit the Try It Out page first.
Fetch Simulations
Fetch the first page of simulations using Collections.
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 5 });
console.log('Loaded:', simulations.length);
console.log('Has more:', simulations.hasMore);
console.log('Simulations:', simulations.models);
Get Simulation by ID
Fetch a specific simulation by its ID.
const simulations = api.collections.simulation;
// First, get any simulation to find an ID
await simulations.fetch({ limit: 1 });
const firstSim = simulations.first();
if (firstSim) {
// Now fetch that specific simulation by ID
await simulations.fetch({ id: firstSim.id } as any);
const simulation = simulations.first();
console.log('Name:', simulation.name);
console.log('State:', simulation.state);
console.log('Project:', simulation.project_id);
}
Filter by State
Group simulations by their current state.
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 50 });
// Group by state
const byState = simulations.groupBy('state');
Object.entries(byState).forEach(([state, sims]) => {
console.log(`${state}: ${sims.length} simulations`);
});
Filter by Project
Find all simulations for a specific project.
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 50 });
// Get unique project IDs
const projectIds = [...new Set(simulations.pluck('project_id'))];
const firstProjectId = projectIds[0];
// Filter by first project ID
const projectSims = simulations.filter(s =>
s.project_id === firstProjectId
);
console.log(`Project ${firstProjectId}: ${projectSims.length} simulations`);
Simulation Statistics
Get statistics about simulations including vehicle counts and algorithm types.
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 50 });
// Get statistics
const stats = {
total: simulations.length,
by_algo: simulations.countBy('algo_type'),
avg_vehicles: simulations.reduce(
(sum, s) => sum + s.number_of_vehicles, 0
) / simulations.length,
mixed_fleet: simulations.filter(s => s.mixed_fleet).length,
};
console.log('Statistics:', stats);
SimulationCollection
The SimulationCollection class provides a Backbone.js-inspired interface for managing simulation data with built-in indexing, pagination, and array operations.
Accessing the SimulationCollection
import { initializeSGERP } from 'sgerp-frontend-lib';
const api = initializeSGERP({
activeConnection: 'admin@localhost',
connections: {
'admin@localhost': {
id: 'admin@localhost',
environment: 'localhost',
user: 'admin',
password: 'admin123',
baseUrl: 'https://sgerp-stage.d.gcdev.swatrider.com',
},
},
});
// Access the SimulationCollection
const simulations = api.collections.simulation;
Common Simulation Operations
Get All Simulations
Fetch and work with simulation collections:
const simulations = api.collections.simulation;
// Fetch first page
await simulations.fetch({ limit: 10 });
console.log('Total simulations:', simulations.length);
console.log('Has more:', simulations.hasMore);
// Iterate through simulations
simulations.forEach(simulation => {
console.log(simulation.name, simulation.state);
});
// Fetch all simulations
await simulations.fetchAll();
console.log('All simulations loaded:', simulations.length);
Get Simulation by ID
Find a specific simulation by its ID:
const simulations = api.collections.simulation;
// Fetch with ID filter (replace 123 with your simulation ID)
await simulations.fetch({ id: 123 } as any);
const simulation = simulations.first();
if (simulation) {
console.log('Simulation found:', simulation.name);
console.log('Project ID:', simulation.project_id);
console.log('State:', simulation.state);
}
Filter Simulations by Project
Get all simulations for a specific project:
const simulations = api.collections.simulation;
// Fetch all simulations
await simulations.fetchAll();
// Filter by project ID (client-side)
const projectSimulations = simulations.filter(s => s.project_id === 121);
console.log(`Found ${projectSimulations.length} simulations for project 121`);
Filter by Simulation State
Find simulations by their current state:
const simulations = api.collections.simulation;
await simulations.fetchAll();
// Filter by state
const createdSimulations = simulations.where({ state: 'created' });
const completedSimulations = simulations.where({ state: 'completed' });
console.log('Created:', createdSimulations.length);
console.log('Completed:', completedSimulations.length);
// Get active (not deleted) simulations
const activeSimulations = simulations.filter(s => !s.deleted);
Group Simulations by State
Group simulations by their state:
const simulations = api.collections.simulation;
await simulations.fetchAll();
// Group by state
const byState = simulations.groupBy('state');
Object.entries(byState).forEach(([state, sims]) => {
console.log(`${state}: ${sims.length} simulations`);
});
Types
Simulation
interface Simulation {
id: number;
created_at: string;
modified_at: string;
completed_at: string | null;
name: string;
description: string;
project_id: number;
state: string;
mixed_fleet: boolean;
geofence_id: string;
bacchus_id: string;
start_time: string;
end_time: string;
booking_start_time: string | null;
booking_end_time: string | null;
dataset_id: number;
conversion_rate: number;
// Vehicle and routing settings
number_of_vehicles: number;
road_network: string;
vehicle_capacity: number;
journey_duration_source: string;
routing_profile_id: number;
routing_settings: Record<string, any>;
walking_profile_id: number;
walking_settings: Record<string, any>;
// Timing constraints
min_advance_booking_window: number;
max_advance_booking_window: number;
acceptable_waiting_time: number;
max_additional_journey_time: number;
max_additional_journey_time_percent: number;
max_walking_distance: number;
// Driver settings
driver_prep_time: number;
min_driver_rest_time: number;
percentage_driver_rest_time: number;
adjust_driver_breaks_enabled: boolean;
// Algorithm settings
algo_type: string;
algo_optimize_quantity: string;
simulation_mode: string;
// Statistics (computed)
used_vehicles_count: number | null;
in_service_mileage: number | null;
dead_mileage: number | null;
transfer_rate: number | null;
bookings_count: number;
completed_bookings_count: number;
completed_odbs_trips_count: number | null;
completed_fixed_route_trips_count: number | null;
no_offer_count: number | null;
odbs_trips_per_vehicle_per_hour: number | null;
// Performance metrics
avg_waiting_time: number | null;
min_waiting_time: number | null;
max_waiting_time: number | null;
avg_journey_time_difference: number | null;
min_journey_time_difference: number | null;
max_journey_time_difference: number | null;
// Cost and revenue
total_cost: number | null;
revenue: number | null;
utilization_rate: number | null;
// Additional data
data: {
vehicle_driving_side?: string;
messaging_webhook_url?: string;
vehicle_shift_distance?: number;
max_number_of_neighbor_stops?: number;
messaging_webhook_message_types?: string[];
offer_auto_cancellation_timeout?: number;
send_vehicle_assignment_only_on_offer_acceptance?: boolean;
[key: string]: any;
};
result: {
empty: boolean;
[key: string]: any;
};
// Flags
deleted: boolean;
allow_jump: boolean;
offer_generation_enabled: boolean;
write_events_log: boolean;
analytics_export_completed: boolean;
is_processor_based: boolean;
performance_tracker_enabled: boolean;
enable_offer_messages_generation: boolean;
enable_waypoints_cache: boolean;
order_tracking_enabled: boolean;
// Related IDs
scenario_id: number | null;
fixed_route_schedule_id: number | null;
fixed_route_filter_model_id: number | null;
pickup_transit_stops_id: number | null;
dropoff_transit_stops_id: number | null;
explicit_stops_id: number | null;
high_priority_stops_id: number | null;
pricing_id: number | null;
template_id: number | null;
// Names (denormalized)
dataset_name: string | null;
dataset_csv_filename: string | null;
project_name: string | null;
geofence_name: string | null;
// Other
recurrence: string | null;
recurrence_priority: number;
vehicle_ordering_in_one_by_one_stage: string;
deployment_label: string | null;
odbs_trip_duration: number;
absolute_max_trip_duration: number | null;
}
Complete Example
import { initializeSGERP, type Simulation } from 'sgerp-frontend-lib';
// Initialize the library
const api = initializeSGERP({
activeConnection: 'admin@staging',
connections: {
'admin@staging': {
id: 'admin@staging',
environment: 'staging',
user: 'admin',
password: 'your-password',
baseUrl: 'https://sgerp-stage.d.gcdev.swatrider.com',
},
},
});
// Get simulation by ID
async function getSimulationById(simulationId: number) {
const simulations = api.collections.simulation;
await simulations.fetch({ id: simulationId } as any);
const simulation = simulations.first();
if (simulation) {
console.log('Found simulation:', {
id: simulation.id,
name: simulation.name,
project_id: simulation.project_id,
state: simulation.state,
vehicles: simulation.number_of_vehicles,
created: new Date(simulation.created_at).toLocaleDateString(),
});
return simulation;
} else {
console.log('Simulation not found');
return null;
}
}
// List simulations for a project
async function listProjectSimulations(projectId: number) {
const simulations = api.collections.simulation;
// Fetch all simulations
await simulations.fetchAll();
// Filter by project
const projectSims = simulations.filter(s => s.project_id === projectId);
console.log(`Project ${projectId} has ${projectSims.length} simulations`);
projectSims.forEach(sim => {
console.log(` - ${sim.name} (${sim.state})`);
});
}
// Get simulation statistics
async function getSimulationStats() {
const simulations = api.collections.simulation;
await simulations.fetchAll();
// Group by state
const byState = simulations.groupBy('state');
console.log('\nSimulations by state:');
Object.entries(byState).forEach(([state, sims]) => {
console.log(` ${state}: ${sims.length}`);
});
// Group by project
const byProject = simulations.groupBy('project_id');
console.log('\nSimulations by project:');
Object.entries(byProject).forEach(([projectId, sims]) => {
console.log(` Project ${projectId}: ${sims.length}`);
});
// Active vs deleted
const active = simulations.filter(s => !s.deleted);
const deleted = simulations.filter(s => s.deleted);
console.log(`\nActive: ${active.length}, Deleted: ${deleted.length}`);
}
// Find simulations with specific settings
async function findSimulationsWithMixedFleet() {
const simulations = api.collections.simulation;
await simulations.fetchAll();
const mixedFleetSims = simulations.where({ mixed_fleet: true });
console.log(`Found ${mixedFleetSims.length} simulations with mixed fleet`);
mixedFleetSims.forEach(sim => {
console.log(` - ${sim.name} (Project ${sim.project_id})`);
});
}
// Run examples
// First, get available simulations to find IDs
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 1 });
const firstSim = simulations.first();
if (firstSim) {
await getSimulationById(firstSim.id);
await listProjectSimulations(firstSim.project_id);
}
await getSimulationStats();
await findSimulationsWithMixedFleet();
Working with Simulation Results
Simulations contain various computed statistics that are populated after the simulation runs:
const simulations = api.collections.simulation;
// Fetch simulations and find a completed one
await simulations.fetchAll();
const completedSim = simulations.find(s => s.completed_at !== null);
if (completedSim) {
console.log('Simulation completed at:', completedSim.completed_at);
// Access statistics
console.log('Vehicles used:', completedSim.used_vehicles_count);
console.log('Total bookings:', completedSim.bookings_count);
console.log('Completed bookings:', completedSim.completed_bookings_count);
console.log('Average waiting time:', completedSim.avg_waiting_time);
console.log('Utilization rate:', completedSim.utilization_rate);
console.log('Total cost:', completedSim.total_cost);
console.log('Revenue:', completedSim.revenue);
} else {
console.log('No completed simulations found');
}
Error Handling
import { APIError } from 'sgerp-frontend-lib';
try {
const simulations = api.collections.simulation;
await simulations.fetch({ limit: 10 });
if (simulations.length === 0) {
console.log('No simulations found');
} else {
console.log(`Found ${simulations.length} simulations`);
}
} catch (error) {
if (error instanceof APIError) {
if (error.status === 401) {
console.error('Authentication failed - check credentials');
} else if (error.status === 404) {
console.error('Resource not found');
} else {
console.error('API error:', error.message);
}
} else {
console.error('Unknown error:', error);
}
}