Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/lucavallini/aibar-frontend/llms.txt

Use this file to discover all available pages before exploring further.

Trips are the central entity of the Aibar SRL App. Every movement of cargo is modelled as a Viaje — capturing the assigned driver, the optional truck, origin and destination, client, freight description, fare, and kilometre count. The full lifecycle of a trip, from creation through departure and arrival to cancellation, is tracked via a state machine so that fleet managers always have an accurate real-time picture of operations.

Trip States

A trip moves through up to four states. The normal path is pendienteen_cursofinalizado. At any point before finalization the trip can also move to cancelado.
pendiente  ──iniciar()──▶  en_curso  ──finalizar()──▶  finalizado
    │                          │
    └──cancelar()──────────────┴──cancelar()──▶  cancelado
The estado field is a TypeScript union type defined in viaje.model.ts:
estado: 'pendiente' | 'en_curso' | 'finalizado' | 'cancelado'
StateMeaning
pendienteTrip created but not yet started. The driver has been assigned and is on standby.
en_cursoTrip is underway. The driver’s status becomes viajando.
finalizadoTrip completed. Kilometres travelled have been recorded.
canceladoTrip was called off. A cancellation reason is stored for audit purposes.

Data Models

Viaje Interface

The full read model returned by the API for every trip:
export interface Viaje {
  id: string;
  chofer_id: string;
  camion_id: string | null;
  cliente: string | null;
  origen: string;
  destino: string;
  carga: string | null;
  tarifa: number | null;
  kms_recorridos: number | null;
  fecha_inicio: string;
  fecha_fin: string | null;
  estado: 'pendiente' | 'en_curso' | 'finalizado' | 'cancelado';
  motivo_cancelacion: string | null;
  asignado_por: string;
  autorizado_por: string | null;
  creado_en: string;
}

ViajeCreate Interface

The payload sent when creating a new trip. Required fields are chofer_id, origen, destino, and fecha_inicio; all other fields are optional:
export interface ViajeCreate {
  chofer_id: string;
  camion_id?: string;
  cliente?: string;
  origen: string;
  destino: string;
  carga?: string;
  tarifa?: number;
  fecha_inicio: string;
}

ViajeCreate Fields

chofer_id
string
required
UUID of the driver to assign to this trip. The driver must have estado: 'disponible' at the time of creation.
origen
string
required
Free-text departure location (city, address, or waypoint name).
destino
string
required
Free-text arrival location.
fecha_inicio
string
required
ISO 8601 datetime string for the planned departure. The UI converts a datetime-local input value with new Date(...).toISOString() before sending.
camion_id
string
UUID of the truck assigned to this trip. Optional — can be omitted when the truck is not yet decided.
cliente
string
Name of the customer or company receiving the cargo.
carga
string
Free-text description of the freight being transported.
tarifa
number
Agreed fare for the trip in the local currency.

ViajesService

ViajesService is an Angular Injectable provided at the root level. It wraps all REST calls to the /viajes resource.
@Injectable({ providedIn: 'root' })
export class ViajesService {
  private apiUrl = `${environment.apiUrl}/viajes`;

  constructor(private http: HttpClient) {}
}

listar()

Fetches a paginated list of trips, with an optional state filter.
listar(estado?: string, pagina: number = 1, tamanoPagina: number = 20): Observable<RespuestaPaginada<Viaje>>
HTTP call:
GET /viajes/?pagina=1&tamano_pagina=20
GET /viajes/?pagina=1&tamano_pagina=20&estado=en_curso
When estado is omitted (or 'todos' is selected in the UI), the query string parameter is not appended and the API returns trips in all states.

crear()

Creates a new trip in pendiente state.
crear(datos: ViajeCreate): Observable<Viaje>
HTTP call:
POST /viajes/
Body: a ViajeCreate object serialised as JSON. Returns the newly created Viaje. If the driver is no longer available (race condition), the API responds with 409 Conflict.

iniciar()

Transitions a pendiente trip to en_curso.
iniciar(id: string): Observable<Viaje>
HTTP call:
POST /viajes/{id}/iniciar
Sends an empty body ({}). Returns the updated Viaje.

finalizar()

Closes an en_curso trip and records the end date and kilometres driven.
finalizar(id: string, fechaFin: string, kmsRecorridos: number): Observable<Viaje>
HTTP call:
POST /viajes/{id}/finalizar
Body:
{
  "fecha_fin": "2025-07-15T18:30:00.000Z",
  "kms_recorridos": 320
}
Returns the updated Viaje in finalizado state.

cancelar()

Cancels a pendiente or en_curso trip and stores the reason.
cancelar(id: string, motivoCancelacion: string): Observable<Viaje>
HTTP call:
POST /viajes/{id}/cancelar
Body:
{
  "motivo_cancelacion": "Cliente canceló el pedido"
}
Returns the updated Viaje in cancelado state.

Listing and Filtering Trips

The ListaViajes component exposes five filter buttons. Selecting a filter resets pagination to page 1 and re-fetches the list:
filtros: { label: string; valor: FiltroEstado }[] = [
  { label: 'Todos',      valor: 'todos'      },
  { label: 'Pendientes', valor: 'pendiente'  },
  { label: 'En curso',   valor: 'en_curso'   },
  { label: 'Finalizados',valor: 'finalizado' },
  { label: 'Cancelados', valor: 'cancelado'  },
];
The 'todos' option passes undefined to listar(), omitting the &estado= parameter entirely so the backend returns all states.

Creating a Trip

1

Open the new-trip modal

The UI calls abrirModalNuevoViaje(), which simultaneously fetches available drivers (estado === 'disponible') and active trucks to populate the form dropdowns.
2

Fill in required fields

chofer_id, origen, destino, and fecha_inicio are mandatory. The component validates these before calling the service.
3

Submit

confirmarNuevoViaje() converts the local datetime to an ISO string and calls viajesService.crear().
4

Handle the response

On success the modal closes and the list reloads. A 409 response means the chosen driver became unavailable between loading the form and submitting — the user is prompted to select another driver.
Example service call:
const datos: ViajeCreate = {
  chofer_id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
  camion_id: 'f0e1d2c3-b4a5-6789-0fed-cba987654321',
  cliente:   'Distribuidora Norte S.A.',
  origen:    'Buenos Aires',
  destino:   'Rosario',
  carga:     'Electrodomésticos',
  tarifa:    85000,
  fecha_inicio: new Date('2025-07-20T06:00').toISOString(),
};

this.viajesService.crear(datos).subscribe({
  next:  (viaje) => console.log('Viaje creado:', viaje.id),
  error: (err)   => console.error('Error al crear viaje', err),
});
A trip can only be started if the assigned driver’s estado is disponible at the moment of creation. The driver list in the new-trip modal is pre-filtered to show only drivers with estado === 'disponible'. If the driver’s state changes between loading the form and submitting, the API returns 409 Conflict.

Cancelling a Trip

Cancellation is available for both pendiente and en_curso trips. The motivoCancelacion field is required and must contain at least 5 characters — the component enforces this before calling the service:
confirmarCancelar(): void {
  const viaje = this.viajeSeleccionado();
  if (!viaje || this.motivoCancelacion.trim().length < 5) return;

  this.viajesService.cancelar(viaje.id, this.motivoCancelacion).subscribe({
    next: () => {
      this.cerrarModal();
      this.cargarViajes();
    },
    error: () => this.error.set('No se pudo cancelar el viaje')
  });
}
Cancellation is irreversible via the UI. Once a trip is in cancelado state there is no button to reopen it — a new trip must be created if needed.

Pagination

All list responses are wrapped in RespuestaPaginada<Viaje>. The component stores pagina, totalPaginas, and total as Angular signals and passes them to the shared <app-paginacion> component:
pagina       = signal(1);
totalPaginas = signal(1);
total        = signal(0);
tamanoPagina = 20;
Changing the filter resets pagina to 1 to avoid landing on a non-existent page.

Build docs developers (and LLMs) love