NAV Navbar
logo SimpliRoute
  • Introducción
  • Autenticación
  • Visitas
  • Gestión de planes
  • Rutas (Routes)
  • Route Properties
  • Vehículos
  • Clientes
  • Usuarios
  • Habilidades
  • Zonas
  • Flotas
  • Webhooks
  • Optimización
  • Optimización: Metadatos
  • Validar Incompatibilidades
  • Facturas
  • El proceso de Checkout
  • TMS: Proveedor de transporte
  • Integración GPS
  • Errors
  • Datamart
  • Documentation Logo

    Introducción

    API Endpoint:

    URL: https://api.simpliroute.com/v1/
    
    URL: https://api.simpliroute.com/v1/
    
    URL: https://api.simpliroute.com/v1/
    

    La API de SimpliRoute es un conjunto de endpoints REST. Nuestra API tiene URLs predecibles y orientadas a recursos, y utiliza códigos de respuesta HTTP para indicar errores de la API. Usamos características integradas de HTTP, como autenticación HTTP y verbos HTTP, que son entendidos por clientes HTTP estándar. Admitimos el intercambio de recursos de origen cruzado, lo que te permite interactuar de forma segura con nuestra API desde una aplicación web del lado del cliente (aunque nunca debes exponer tu clave API secreta en el código del cliente de un sitio web público). Las respuestas de la API son JSON, incluidas las de errores.

    El objetivo principal de esta documentación es permitir que cualquier desarrollador comience a trabajar con nuestra API gracias a diferentes ejemplos y casos de uso expuestos en esta documentación. Hay 2 casos básicos para trabajar con nuestra API:

    • Tú (o tu empresa) son una plataforma web de SimpliRoute y deseas enviar información desde tu sistema a SimpliRoute o viceversa. En ese caso, te interesarán principalmente nuestros endpoints de visitas.

    • Eres un desarrollador interesado en mejorar nuestro sistema agregando inteligencia de rutas. En ese caso, nuestra API de Optimización de Rutas es el camino correcto a seguir.

    Si tienes comentarios, errores o información desactualizada, no dudes en contactarnos en [email protected].

    Autenticación

    Endpoint básico para mostrar cómo realizar una llamada con el Token de Autorización

    Endpoint básico para mostrar cómo realizar una llamada con el Token de Autorización

    var settings = {
        async: true,
        crossDomain: true,
        url: "https://api.simpliroute.com/v1/accounts/me/",
        method: "GET",
        headers: {
            "content-type": "application/json",
            authorization: "Token 12345678900987sr",
        },
    };
    $.ajax(settings).done(function (response) {
        console.log(response);
    });
    
    OkHttpClient client = new OkHttpClient();
    
    Request request = new Request.Builder()
      .url("https://api.simpliroute.com/v1/accounts/me/")
      .get()
      .addHeader("content-type", "application/json")
      .addHeader("authorization", "Token 12345678900987sr")
      .build();
    
    Response response = client.newCall(request).execute();
    
    curl curl -X GET \
      https://api.simpliroute.com/v1/accounts/me/ \
      -H 'authorization: Token 12345678900987sr' \
      -H 'content-type: application/json' \
    

    Asegúrate de reemplazar 12345678900987sr con tu API key.

    Para usar la API de SimpliRoute, debes proporcionar un Token válido a través del encabezado "Authorization". Si no tienes un Token, puedes obtenerlo desde tu cuenta en la URL: https://app2.simpliroute.com/#/uprofile/info.

    Si no tienes una cuenta, puedes crear una prueba gratuita de 14 días en esta URL: https://app2.simpliroute.com/#/signup.

    Visitas

    Si deseas integrar tu sistema con SimpliRoute, el endpoint más relevante de nuestra API es Visit. Un objeto de visita es cualquier tarea que un conductor deba realizar en la calle: una orden de servicio, una entrega, un retiro. Por lo tanto, si deseas optimizar esas órdenes y rastrearlas en SimpliRoute, debes crear un objeto de visita. En este objeto en particular, debes especificar algunas cosas simples. Estos son los únicos campos obligatorios para crear una visita en SimpliRoute:

    • Título
    • Dirección
    • Fecha Planificada

    Esa es la información básica que debe contener una visita para ser aceptada en la API. Al igual que todos los endpoints de la API de SimpliRoute, implementa los métodos HTTP GET, POST, PUT y DELETE.

    El objeto Visita

    Ejemplo del objeto visita

    {
        "id": 200189436,
        "order": null,
        "tracking_id": "SR98278668985242",
        "status": "pending",
        "title": "SimpliRoute3",
        "address": "vespucio norte 22, las condes",
        "latitude": "-33.413433",
        "longitude": "-70.585503",
        "load": 39.0,
        "load_2": 100.0,
        "load_3": 0.0,
        "window_start": null,
        "window_end": null,
        "window_start_2": null,
        "window_end_2": null,
        "duration": "00:00:10",
        "contact_name": "",
        "contact_phone": "",
        "contact_email": null,
        "reference": "",
        "notes": "",
        "skills_required": [],
        "skills_optional": [],
        "tags": [],
        "planned_date": "2016-06-30",
        "programmed_date": null,
        "route": null,
        "estimated_time_arrival": null,
        "estimated_time_departure": null,
        "checkin_time": null,
        "checkout_time": null,
        "checkout_latitude": null,
        "checkout_longitude": null,
        "checkout_comment": "",
        "checkout_observation": null,
        "signature": null,
        "pictures": [],
        "created": "2022-09-03T01:19:42.786633Z",
        "modified": "2022-09-03T01:19:42.786633Z",
        "eta_predicted": "2016-06-30T00:00:00-04:00",
        "eta_current": "2016-06-30T00:00:00-04:00",
        "priority": false,
        "has_alert": false,
        "priority_level": null,
        "extra_field_values": null,
        "geocode_alert": null,
        "visit_type": null,
        "current_eta": null,
        "fleet": null,
        "properties": {
          "city": "Santiago"
        },
        "items": [
            {
                "id": 221544,
                "title": "bar",
                "status": "pending",
                "load": 2.0,
                "load_2": 1.5,
                "load_3": 0.0,
                "reference": "bar",
                "visit": 200189436,
                "notes": "",
                "quantity_planned": 2.0,
                "quantity_delivered": 0.0
            },
            {
                "id": 221543,
                "title": "foo",
                "status": "pending",
                "load": 15.0,
                "load_2": 0.0,
                "load_3": 0.5,
                "reference": "foo",
                "visit": 200189436,
                "notes": "",
                "quantity_planned": 1.0,
                "quantity_delivered": 0.0
            }
        ],
        "on_its_way": null
    }
    
    Attributes Data Type Description
    id uuid Unique identifier for the object.
    order Integer Visit order when the visit already belongs to a delivery route.
    tracking_id String Autogenerated tracking code to follow the delivery.
    status String Visit's status (pending, partial, completed, failed or canceled).
    title String String to identify the delivery. Usually company or person's name.
    address String Address text. Best practice is to use Googlemaps format.
    planned_date Date Date when the visit will be delivered.
    latitude Float Visit's latitude location.
    longitude Float Visit's longitude location.
    load Double Space of the truck that visit uses.
    load_2 Double Space of the truck that visit uses.
    load_3 Double Space of the truck that visit uses.
    window_start Time Initial Hour when the visit can be visit.
    window_end Time Final Hour when the visit can be visit.
    window_start_2 Time Initial Hour when the visit can be visit.
    window_end_2 Time Final Hour when the visit can be visit.
    duration Timestamp Time spent in the delivery (HH:mm:ss).
    contact_name String Name of who will receive the delivery.
    contact_phone String Phone of who will receive the delivery.
    contact_email String E-mail of who will receive the delivery.
    reference String Reference or internal identifier of the company. Example: Invoice or order number.
    notes String Information to help the driver.
    skills_required Integer array Array of required skills id that this visit needs.
    skills_optional Integer array Array of optional skills id that this visit needs.
    Tags Integer array Array of tag IDs that characterize the visit.
    route UUID Unique identifier of the route.
    route_estimated_time_start Time Estimated time that the vehicle will start the route in "HH:mm:ss".
    estimated_time_arrival Time SimpliRoute estimation of arrival to the visit.
    estimated_time_departure Time SimpliRoute estimation of departure from visit.
    checkin_time Timestamp Timestamp when the driver started the delivery.
    checkout_time Timestamp Timestamp when the driver completed the delivery.
    checkout_latitude Float Latitude of the driver when he completed the delivery.
    checkout_longitude Float Longitude of the driver when he completed the delivery.
    checkout_comment String Information provided by the driver upon completing the delivery.
    checkout_observation UUID Unique identifier of the observation.
    signature String Contains the URL with the image of the client's signature.
    pictures URL array Array with URLs of pictures added with the delivery.
    created Timestamp Timestamp of the creation of the visit.
    modified Timestamp Timestamp of the last edition of the visit.
    driver Integer Driver ID.
    vehicle Integer Vehicle ID.
    has alert Boolean Contains a boolean value to identify an alert.
    priority_level Integer If the visit is more important than others. It goes from 1 to 5. 1: First of the day, 2: Last of the day. 3: High priority, 4: Medium priority, 5: Low priority.
    extra_field_values String json object containing attributes and values ​​pre-configured by SimpliRoute.
    geocode_alert String Geocoding alert.
    visit_type String Visit type associated with the visit.
    fleet Integer Fleet ID.
    items Array Object Arrangement containing the elements to deliver on the visit.
    on its way Timestamp Timestamp when the driver notifies that they are going to the next delivery.
    properties Object Extra properties of a visit.

    El Objeto de Propiedad

    Attributes Data Type Description
    city String The city of the visit address
    delivery_type String Specifies the delivery type: DELIVERY or PICK
    source String The source of the data to be saved: CLIENT
    source_ident String An identifier used to reference the source, e.g., client ID
    merchant String The merchant associated with the data

    El Objeto de Campo Extra

    URL Definition

    GET https://api.simpliroute.com/v1/accounts/extra-fields/
    
    

    Ejemplo de respuesta

    [
     {
        "id": 23531,
        "label": "order number",
        "key": "order_number",
        "order": 1,
        "enable": true,
        "type": "STX",
        "checkout_type": "S&F",
        "options": [],
        "is_alert": false,
        "is_read": true,
        "is_write": false,
        "is_mandatory": false,
        "visit_types": []
      }
    ]
    

    Los campos extra son una excelente manera de personalizar el formulario de cierre en la aplicación móvil y se pueden incluir en los detalles de la visita. Si no están habilitados en tu cuenta, comunícate con tu representante de Customer Success.

    Parameter Type Description
    id Integer Unique identifier for the extrafield.
    label String The name that will be displayed to the user in the Mobile App (e.g., "order number").
    key String The key associated with the extrafield is used to register it in the database and to identify the extrafield when creating visits (e.g., "order_number").
    order Integer Position of the extrafield in the successful and/or failed checkout form.
    enable Boolean Boolean value indicating whether the extrafield is enabled (true) or disabled (false).
    type String Specifies the type of extrafield (e.g., "STX" means short text).
    checkout_type String Indicates if the extrafield is used in successful and/or failed checkouts (e.g., "S&F").
    options Array An array of options for the extrafield (only for dropdown type).
    is_alert Boolean Boolean value indicating whether the extrafield triggers an alert in tracking.
    is_read Boolean Boolean value indicating whether the extrafield is readable and can only be populated via integration.
    is_write Boolean Boolean value indicating whether the extrafield is writable and can be filled by the Mobile App user.
    is_mandatory Boolean Boolean value indicating whether the extrafield is mandatory to complete in the form.
    visit_types Array An array of visit types associated with the extrafield.

    Observaciones

    URL Definition

    GET https://api.simpliroute.com/v1/routes/observations/
    
    

    Ejemplo de respuesta

    [
        {
            "id": "0b776cb0-zed7-4376-8c6e-fa3db58fde6a",
            "type": "failed",
            "label": "Cliente ausente",
            "created": "2023-10-04T17:02:37.040148Z",
            "modified": "2023-10-04T17:02:37.040148Z"
        },
        {
            "id": "0b776cb0-aed7-7376-8c6e-fa3db58fde6a",
            "type": "completed",
            "label": "Recibido conforme",
            "created": "2023-10-04T17:02:37.040148Z",
            "modified": "2023-10-04T17:02:37.040148Z"
        }
    ]
    

    Las observaciones en SimpliRoute permiten registrar en detalle las razones específicas de visitas completadas o fallidas. Estas observaciones son completamente personalizables, lo que permite una adaptación perfecta a las necesidades únicas del negocio o de las operaciones de entrega.

    Parameter Type Description
    id UUID Unique identifier for the observation (UUID).
    type string The status of the delivery: failed or completed.
    label string A customizable reason or note explaining the outcome of the delivery.
    created string The timestamp when the observation was created.
    modified string The timestamp when the observation was last modified.

    Tags

    URL Definition

    GET https://api.simpliroute.com/v1/routes/tags
    
    

    Ejemplo de respuesta

    [
        {
            "id": 4185,
            "label": "pickup",
            "color": "#472929"
        }
    ]
    

    Una visita puede ser etiquetada con etiquetas predefinidas específicas para cada cliente. Para configurar esto, comunícate con tu representante de Customer Success para que las creen en nuestra base de datos. Estas etiquetas serán visibles para el conductor en la aplicación móvil.

    Parameter Type Description
    id int Unique identifier for the tag.
    label string The name or description of the tag.
    color string The color associated with the tag, represented as a hexadecimal value.

    El Objeto Items

    El objeto Items se presenta como una herramienta para gestionar las cantidades de artículos en cada visita, así como sus entregas parciales. Para ello, puedes crear visitas con arreglos de artículos estableciendo hasta 3 cargas del artículo, referencia, notas, cantidad planificada y entregada.

    Ejemplo del Objeto Items

    {
      {
          "id": 64,
          "title": "prueba2",
          "status": "pending",
          "load": null,
          "load_2": null,
          "load_3": 5.0,
          "reference": "",
          "notes": "",
          "quantity_planned": 4.0,
          "quantity_delivered": 1.0
      }
    }
    
    Attributes Data Type Description
    id uuid Unique identifier for the object.
    title String Title of the item to deliver.route
    status String Element status: pending, failed, or completed
    load Double Space or load that the element occupies in the vehicle
    load_2 Double Second load unit complementary to the first
    load_3 Double Third load unit complementary to the first and the second
    reference Date Internal element identifier
    notes String Additional item notes
    quantity_planned Float Planned quantity of the item
    quantity_delivered Float Delivered quantity of the item

    Crear una visita con items

    Puedes crear una visita agregando cantidades de artículos para cada visita; estos campos son opcionales.

    URL Definition

    
    POST https://api.simpliroute.com/v1/routes/visits/
    
    

    Ejemplo de solicitud

    curl --location --request POST 'https://api.simpliroute.com/v1/routes/visits' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "title": "SimpliRoute3",
        "address": "vespucio norte 22, las condes",
        "load": 39,
        "load_2": 100,
        "window_start": null,
        "window_end": null,
        "duration": "00:10:00",
        "contact_name": "",
        "contact_phone": "",
        "reference": "",
        "notes": "",
        "planned_date": "2016-06-30",
        "items": [
          {
              "title": "foo",
              "load": 15,
              "load_3": 0.5     ,
              "reference": "foo",
              "quantity_planned": 1
          },
          {
              "title": "bar",
              "load": 2,
              "load_2": 1.5,
              "reference": "bar",
              "quantity_planned": 2
          }
      ]
    }'
    
    
    
    OkHttpClient client = new OkHttpClient();
    
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n  \"title\": \"Kwik e mart\",\n  \"address\": \"742 Evergreen Terrace, Springfield, USA\",\n  \"latitude\": 44.052698,\n  \"longitude\": -123.020718,\n  \"contact_name\": \"Apu Nahasapeemapetilon\",\n  \"contact_phone\": \"+123413123212\",\n  \"contact_email\": \"[email protected]\",\n  \"reference\": \"invoice_id\",\n  \"notes\": \"Leave at front door\",\n  \"planned_date\": \"2020-01-01\"\n}");
    Request request = new Request.Builder()
      .url("https://api.simpliroute.com/v1/routes/visits/")
      .post(body)
      .addHeader("content-type", "application/json")
      .addHeader("authorization", "Token 12345678900987sr")
      .build();
    
    Response response = client.newCall(request).execute();
    
    var settings = {
        async: true,
        crossDomain: true,
        url: "https://api.simpliroute.com/v1/routes/visits/",
        method: "POST",
        headers: {
            "content-type": "application/json",
            authorization: "Token 12345678900987sr",
        },
        processData: false,
        data: '{\n  "title": "Kwik e mart",\n  "address": "742 Evergreen Terrace, Springfield, USA",\n  "latitude": 44.052698,\n  "longitude": -123.020718,\n  "contact_name": "Apu Nahasapeemapetilon",\n  "contact_phone": "+123413123212",\n  "contact_email": "[email protected]",\n  "reference": "invoice_id",\n  "notes": "Leave at front door",\n  "planned_date": "2020-01-01"\n}',
    };
    
    $.ajax(settings).done(function (response) {
        console.log(response);
    });
    

    Para crear una visita, la información mínima necesaria es un título, una dirección y una fecha planificada (planned_date). Los demás parámetros en el objeto de visita son opcionales y los necesitarás dependiendo de tu implementación.

    Puedes crear visitas una por una o como un arreglo. Los ejemplos en el lado derecho solo muestran la creación de una visita por solicitud, pero si necesitas crear un lote de visitas, la entrada será algo como esto:

    Ejemplo de Solicitud

    
    [ 
        {
        "title": "SimpliRoute3",
        "address": "vespucio norte 22, las condes",
        "load": 39,
        "load_2": 100,
        "window_start": null,
        "window_end": null,
        "duration": "00:10:00",
        "contact_name": "",
        "contact_phone": "",
        "reference": "",
        "notes": "",
        "planned_date": "2016-06-30",
        "items":
        [
            {
                "title": "foo",
                "load": 15,
                "load_3": 0.5     ,
                "reference": "foo",
                "quantity_planned": 1
            },
            {
                "title": "bar",
                "load": 2,
                "load_2": 1.5,
                "reference": "bar",
                "quantity_planned": 2
            }
        ]
      }
    ]
    
    

    Respuesta

    Devuelve el objeto de visita si la creación fue exitosa. Esta llamada devolverá un error si alguno de los parámetros es inválido.

    Recuperar una visita

    URL Definition

    
    GET https://api.simpliroute.com/v1/routes/visits/{{visit_id}}
    
    

    Ejemplo de solicitud Usando '12345' como ejemplo para el id de la visita (visit_id)

    curl -X GET \
      https://api.simpliroute.com/v1/routes/visits/{{visit_id}}\
      -H 'authorization: Token 12345678900987sr' \
      -H 'content-type: application/json' \
    
    OkHttpClient client = new OkHttpClient();
    
    Request request = new Request.Builder()
      .url("https://api.simpliroute.com/v1/routes/visits/12345")
      .get()
      .addHeader("content-type", "application/json")
      .addHeader("authorization", "Token 12345678900987sr")
      .build();
    
    Response response = client.newCall(request).execute();
    
    var settings = {
        async: true,
        crossDomain: true,
        url: "https://api.simpliroute.com/v1/routes/visits/12345",
        method: "GET",
        headers: {
            "content-type": "application/json",
            authorization: "Token 12345678900987sr",
        },
    };
    
    $.ajax(settings).done(function (response) {
        console.log(response);
    });
    

    Ejemplo de Respuesta

    [
        {
            "id": 199285905,
            "order": null,
            "tracking_id": "SR17562640764438",
            "status": "pending",
            "title": "SimpliRoute3",
            "address": "vespucio norte 22, las condes",
            "latitude": "-33.413433",
            "longitude": "-70.585503",
            "load": 39.0,
            "load_2": 100.0,
            "load_3": 0.0,
            "window_start": null,
            "window_end": null,
            "window_start_2": null,
            "window_end_2": null,
            "duration": "00:00:10",
            "contact_name": "",
            "contact_phone": "",
            "contact_email": null,
            "reference": "",
            "notes": "",
            "skills_required": [],
            "skills_optional": [],
            "tags": [],
            "planned_date": "2016-06-30",
            "programmed_date": null,
            "route": null,
            "estimated_time_arrival": null,
            "estimated_time_departure": null,
            "checkin_time": null,
            "checkout_time": null,
            "checkout_latitude": null,
            "checkout_longitude": null,
            "checkout_comment": "",
            "checkout_observation": null,
            "signature": null,
            "pictures": [],
            "created": "2022-08-31T17:32:55.626342Z",
            "modified": "2022-08-31T17:32:55.626342Z",
            "eta_predicted": "2016-06-30T00:00:00-04:00",
            "eta_current": "2016-06-30T00:00:00-04:00",
            "priority": false,
            "has_alert": false,
            "priority_level": null,
            "extra_field_values": null,
            "geocode_alert": null,
            "visit_type": null,
            "current_eta": null,
            "fleet": null,
            "items": [
                {
                    "id": 211775,
                    "title": "bar",
                    "status": "pending",
                    "load": 2.0,
                    "load_2": 1.5,
                    "load_3": 0.0,
                    "reference": "bar",
                    "visit": 199285905,
                    "notes": "",
                    "quantity_planned": 2.0,
                    "quantity_delivered": 0.0
                },
                {
                    "id": 211774,
                    "title": "foo",
                    "status": "pending",
                    "load": 15.0,
                    "load_2": 0.0,
                    "load_3": 0.5,
                    "reference": "foo",
                    "visit": 199285905,
                    "notes": "",
                    "quantity_planned": 1.0,
                    "quantity_delivered": 0.0
                }
            ],
            "on_its_way": null
        }
    ]
    

    Recupera los detalles de una visita existente. Envía el identificador único de la visita y la API de SimpliRoute devolverá la información correspondiente a esa visita.

    Agregar artículos a una visita

    A través del siguiente endpoint, se pueden agregar uno o más artículos a una visita determinada. Para esto, debemos tener el identificador de la visita (visit id), el cual debe ser incluido como parte de la estructura en la URL.

    Definición

    
    POST https://api.simpliroute.com/v1/routes/visits/{{VISIT_ID}}/items
    

    JSON de ejemplo

    [
        {
            "id": 63,
            "title": "prueba1",
            "status": "pending",
            "load": null,
            "load_2": null,
            "load_3": 5.0,
            "reference": "",
            "notes": "",
            "quantity_planned": 4.0,
            "quantity_delivered": 1.0
        },
        {
            "id": 64,
            "title": "prueba2",
            "status": "pending",
            "load": null,
            "load_2": null,
            "load_3": 5.0,
            "reference": "",
            "notes": "",
            "quantity_planned": 4.0,
            "quantity_delivered": 1.0
        }
    ]
    

    Eliminar una visita

    Para eliminar una visita, se debe realizar una llamada DELETE al servicio de visitas de SimpliRoute. Esto se realiza de la siguiente manera:

    Definición

    
    DELETE  https://api.simpliroute.com/v1/routes/visits/{{VISIT_ID}}/
    
    

    Es importante mencionar que la eliminación de una visita en una ruta ya construida NO desencadena un recálculo de los tiempos de llegada de los puntos siguientes de la ruta. La única forma de hacerlo actualmente es a través de la interfaz web de SimpliRoute o actualizando manualmente las ETAs (horarios estimados de llegada) de cada visita con un cálculo externo.

    Eliminar múltiples visitas

    Para eliminar múltiples visitas, se debe realizar una llamada de tipo POST al servicio masivo de SimpliRoute. Esto se realiza de la siguiente manera:

    Definición

    
    POST https://api.simpliroute.com/v1/bulk/delete/visits/
    
    

    Example Request body json { "visits": [ 462783899, 462783900, 462783901, 462783902 ] } El arreglo de visitas debe contener los identificadores (id) de las visitas que deseas eliminar.

    Recuperar visitas por fecha

    Definition

    
    GET https://api.simpliroute.com/v1/routes/visits/?planned_date={{planned_date}}
    
    

    Example Request

    curl -X GET \
      'https://api.simpliroute.com/v1/routes/visits/?planned_date=2020-01-01' \
      -H 'authorization: Token 12345678900987sr' \
      -H 'content-type: application/json'
    
    
    OkHttpClient client = new OkHttpClient();
    
    Request request = new Request.Builder()
      .url("https://api.simpliroute.com/v1/routes/visits/?planned_date=2020-01-01")
      .get()
      .addHeader("content-type", "application/json")
      .addHeader("authorization", "Token 12345678900987sr")
      .build();
    
    Response response = client.newCall(request).execute();
    
    var settings = {
        async: true,
        crossDomain: true,
        url: "https://api.simpliroute.com/v1/routes/visits/?planned_date=2020-01-01",
        method: "GET",
        headers: {
            "content-type": "application/json",
            authorization: "Token 12345678900987sr",
        },
    };
    
    $.ajax(settings).done(function (response) {
        console.log(response);
    });
    

    Llamada GET para solicitar todas las visitas de una fecha específica. El formato esperado para la fecha planificada es "YYYY-mm-dd" (Año-mes-día, por ejemplo, 2020-10-22). Esta llamada es útil si deseas rastrear tus entregas en tiempo real, ya que devuelve la lista completa de visitas y la actividad completa de cada una (incluyendo los cierres y la información proporcionada por los conductores en la calle).

    Actualizar una visita

    URL Definition

    
    PUT https://api.simpliroute.com/v1/routes/visits/{{visit_id}}
    
    

    Example Request

    curl -X PUT \
      https://api.simpliroute.com/v1/routes/visits/1111/ \
      -H 'authorization: Token 12345678900987sr' \
      -H 'content-type: application/json' \
      -d '{
      "title": "Updated visit",
      "address": "new address",
      "load": 39,
      "duration": "00:00:10",
      "contact_name": "New visit contact",
      "contact_phone": "+12341345",
      "notes": "New information",
      "planned_date": "2020-06-30"
    }'
    
    OkHttpClient client = new OkHttpClient();
    
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n  \"title\": \"Updated visit\",\n \"address\": \"New address\",\n \"load\": 39,\n  \"duration\": \"00:00:10\",\n  \"contact_name\": \"New visit contact\",\n  \"contact_phone\": \"+12341345\",\n  \"notes\": \"New information\",\n  \"planned_date\": \"2020-06-30\"\n}");
    Request request = new Request.Builder()
      .url("https://api.simpliroute.com/v1/routes/visits/1111/")
      .put(body)
      .addHeader("content-type", "application/json")
      .addHeader("authorization", "Token 12345678900987sr")
      .build();
    
    Response response = client.newCall(request).execute();
    
    var settings = {
        async: true,
        crossDomain: true,
        url: "https://api.simpliroute.com/v1/routes/visits/1111/",
        method: "PUT",
        headers: {
            "content-type": "application/json",
            authorization: "Token 12345678900987sr",
        },
        processData: false,
        data: '{\n  "title": "Updated visit",\n  "address": "New address",\n "load": 39,\n  "duration": "00:00:10",\n  "contact_name": "New visit contact",\n  "contact_phone": "+12341345",\n  "notes": "New information",\n  "planned_date": "2020-06-30"\n}',
    };
    
    $.ajax(settings).done(function (response) {
        console.log(response);
    });
    

    Actualiza el argumento especificado estableciendo los valores de los parámetros proporcionados. Cualquier parámetro no incluido permanecerá sin cambios.

    Información detallada de una visita

    A través del siguiente endpoint puedes obtener la información detallada de una visita.

    GET https://api.simpliroute.com/plans/v1/visits/{{VISIT_ID}}/detail/
    
    
    

    Example response

    {
    "window_start":"09:00:00",
    "reference":"",
    "planned_date":"2017-03-13",
    "time_service":"00:00:03",
    "window_end":"19:00:00",
    "checkout_comment":"",
    "duration":"00:20:00",
    "estimated_time_arrival":"09:05:00",
    "id":89273,
    "checkin_time":"2017-03-13T20:17:08Z",
    "pictures":[],
    "window_start_2":"23:59:00",
    "checkout_observation":"Testing",
    "latitude":"-33.442880",
    "status":"completed",
    "checkout_time":"2017-03-13T20:17:11Z",
    "window_end_2":"23:59:00",
    "vehicle_name":"KILASK31",
    "address":"FANOR VELASCO 85, SANTIAGO, Santiago",
    "title":"PELUQUERIA DI GIANCARLO",
    "longitude":"-70.659729",
    "driver_name":"Paperito",
    "order":1
    }
    

    Este endpoint proporciona más información, incluyendo comentarios del cierre (Checkout Comment) e imágenes.

    Obtener detalles de la visita

    A través del siguiente endpoint puedes obtener la información detallada de un lote de visitas.

    URL Definition

    GET https://api.simpliroute.com/v1/routes/visits/{{VISIT_ID}}
    
    

    Validación de ventanas de tiempo en la API - Visitas

    Situación actual

    Al crear/editar una visita, la API no valida las ventanas de tiempo que se informan en ella. Esto causa eventualidades en la optimización.

    Los dos problemas encontrados son:

    • No se valida que la hora de inicio sea menor que la hora de fin.
    • No se valida la superposición de ventanas de tiempo al cargar ambas posibles ventanas para una visita. Este problema aparece únicamente a través de la integración con la API, ya que existen validaciones tanto en la carga manual como en la carga mediante Excel.

    Situación esperada

    Al crear una visita que tenga ventanas de tiempo, se debe replicar la misma validación que se usa actualmente para la carga manual, que consiste en: - La hora de inicio no puede ser mayor que la hora de fin (Ej: hora de inicio 19:00 - hora de fin: 16:00). - La ventana de tiempo no puede extenderse al día siguiente (Ej: hora de inicio 23:00 - hora de fin: 04:00). Aunque cumpla con la validación mencionada anteriormente, es importante aclarar que no existe una ventana de tiempo "Nocturna".

    El mensaje de error que devolverá la API es:

    Example Time error: the time window order is inverted.

    Tanto la carga manual como mediante Excel manejan los mismos mensajes que antes.

    Para el segundo problema mencionado, es necesario validar:

    • Que la ventana de tiempo 1 NO sea posterior a la ventana de tiempo 2 (Ej: ventana 1 de 12:00 a 14:00 y ventana 2 de 08:00 a 10:00).

    • Que NO haya intersección entre las dos ventanas (Ej: ventana 1 de 12:00 a 14:00 y ventana 2 de 13:00 a 18:00).

    El mensaje de error que devolverá la API será: Error de tiempo: el orden de las ventanas de tiempo está invertido. Tanto la carga manual como mediante Excel manejan los mismos mensajes que antes.

    Para más información, contacta a tu ejecutivo de cuenta, al chat de soporte o escríbenos un correo a [email protected].

    Finalizar una visita (Checkout)

    Visit checkout (minimal payload)

    curl --location --request POST 'https://api.simpliroute.com/v1/mobile/visit/<visit_id>/checkout/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "status": "completed", 
        "checkout_time": "2024-04-24 13:24:53", 
        "checkout_latitude": -12.105513, 
        "checkout_longitude": -76.965618, 
        "checkout_comment": "everything was OK" 
      }'
    

    Para finalizar (checkout) una visita, está disponible el siguiente servicio: https://api.simpliroute.com/v1/mobile/visit/<visit_id>/checkout/

    Un payload mínimo en cURL se muestra en el panel derecho 👉

    Si planeas implementar las mismas funciones que nuestra aplicación móvil, consulta El proceso de checkout.

    Parameter type description
    status string one of the following statuses: pending, completed, failed
    checkout_time string date and hour of checkout following the ISO 8601 standard
    checkout_latitude float latitude at the point of delivery
    checkout_longitude float longitude at the point of delivery
    checkout_comment string optional comment

    Gestión de planes

    Un plan es una serie de emparejamientos de Vehículos y Conductores para un día específico.

    El plan es la entidad que abarca una ejecución del sistema. Para evitar problemas, se sugiere que la creación del plan se realice utilizando el nombre del plan como una marca de tiempo (timestamp). La fecha de inicio y fin del plan, en casos generales, corresponde al día de ejecución del plan.

    Crear un plan

    En primer lugar, hay dos objetos principales a considerar en un plan:

    • Rutas → La entidad del sistema que abarca un conjunto de visitas.
    • Visitas → Cualquier tarea que un conductor debe realizar en la calle: una orden de servicio, una entrega, un retiro.

    Además, necesitamos conocer el identificador (id) del conductor y del vehículo que vamos a incluir en la ruta. Esto se puede hacer utilizando los siguientes endpoints: - GET Vehicles: https://api.simpliroute.com/v1/routes/vehicles/ - GET Drivers: https://api.simpliroute.com/v1/accounts/drivers/

    Donde debemos guardar el campo ‘id’ de cada vehículo y conductor para usarlo más adelante. Una vez que obtengamos esos campos, deberíamos poder crear un plan completo utilizando todo lo mencionado anteriormente.

    URL Definition

    
    POST https://api.simpliroute.com/v1/plans/create-plan/
    
    

    Example request

    {
      "name": "Plan created through API 2022-09-02 12:55:18",
      "start_date": "2022-09-02",
      "end_date": "2022-09-02",
      "routes": [
        {
          "driver": "183371",
          "vehicle": "288202",
          "planned_date": "2022-09-02",
          "total_distance": "0",
          "total_duration": "00:38:00",
          "total_load": 0,
          "total_load_percentage": 0,
          "total_load_2": 0,
          "total_load_2_percentage": 0,
          "total_load_3": 0,
          "total_load_3_percentage": 0,
          "estimated_time_start": "08:00:00",
          "estimated_time_end": "08:38:00",
          "request_status": "created",
          "comment": null,
          "location_start_address": "Av. San Borja Sur 486, Cercado de Lima 15036",
          "location_start_latitude": -12.101389,
          "location_start_longitude": -77.004534,
          "location_end_address": "Av. San Borja Sur 486, Cercado de Lima 15036",
          "location_end_latitude": -12.101389,
          "location_end_longitude": -77.004534,
          "visits": [
            {
              "title": "Order 1234",
              "address": "Jirón Vesalio 252, San Borja",
              "latitude": -12.105329,
              "longitude": -77.005524,
              "order": 1,
              "load": 1,
              "window_start": "09:00:00",
              "window_end": "17:00:00",
              "duration": "00:10:00",
              "contact_name": "David Rosales",
              "contact_email": "[email protected], [email protected]",
              "reference": "",
              "notes": "Watch out with the dog!",
              "planned_date": "2022-09-02",
              "estimated_time_arrival": "08:02",
              "estimated_time_departure": "08:12",
              "request_status": "created"
            },
            {
              "title": "Order 4567",
              "address": "Jirón Tasso 423, San Borja",
              "latitude": -12.105779,
              "longitude": -77.019189,
              "order": 2,
              "load": 1,"window_start": "09:00:00",
              "window_end": "17:00:00",
              "duration": "00:10:00",
              "contact_name": "David Rosales",
              "contact_email": "[email protected]",
              "reference": "",
              "notes": "Ask for David",
              "planned_date": "2022-09-02",
              "estimated_time_arrival": "08:20",
              "estimated_time_departure": "08:30",
              "request_status": "created"
            }
          ]
        }
      ]
    }
    

    Example response

    {
    "id": "4363095e-8d7c-46d0-9a14-8c895c37fa88",
    "name": "Plan created through API 2022-09-02 12:55:18",
    "start_date": "2022-09-02",
    "end_date": "2022-09-02",
    "reset_day": 1,
    "created": "2022-09-02T06:51:24.937690Z",
    "modified": "2022-09-02T06:51:24.937690Z",
    "is_cluster": false,
    "routes": [
    "349cd8a2-5149-4732-b46f-1073fb90ea07"
    ],
    "plan_metadata": null,
    "start_time": null,
    "end_time": null
    }
    > Example request
    
    ```json
    {
            "name": "Agosto",
            "start_date": "2016-08-01",
            "end_date": "2016-08-01"
        }
    
    

    Example response

    [{
            "id": "fc65b49f-1f5c-4ca5-9b03-98565e1589f3",
            "name": "Agosto",
            "start_date": "2016-08-01",
            "end_date": "2016-08-01",
            "created": "2016-08-25T15:28:32.400027Z",
            "modified": "2016-08-25T15:28:32.400365Z",
            "is_cluster": false
    }]
    
    

    Consideraciones importantes

    Todos los parámetros en negrita se consideran importantes para crear planes.

    Plan

    • name debe ser único.
    • start_date y end_date deben ser iguales.

    Rutas (Routes)

    • driver → Identificador del conductor.
    • vehicle → Identificador del vehículo.
    • planned_date debe ser igual a start_date y end_date del plan.
    • estimated_time_start → Hora en la que el vehículo comienza a trabajar.
    • estimated_time_end → Hora en la que el vehículo terminará de trabajar.
    • request_status → Crear una nueva ruta.

    Visitas (Visits)

    Un arreglo con todas las visitas de una ruta.

    • title → Identificador de la tienda o persona para entregar (se mostrará en la aplicación móvil).
    • address → Dirección de la entrega (se mostrará en la aplicación móvil).
    • order → El orden en el que se realizará la entrega.
    • planned_date → Fecha de la entrega.
    • estimated_time_arrival → Hora estimada de llegada.
    • estimated_time_departure → Hora estimada de salida.
    • request_status → Crear una nueva visita.

    El resto de los parámetros no son obligatorios y deben configurarse con datos ficticios si la información no está disponible.

    Rutas (Routes)

    La ruta es la entidad del sistema que abarca un conjunto de visitas. Sobre esta entidad se pueden realizar las operaciones típicas de CRUD.

    Crear Rutas

    URL Definition

    POST https://api.simpliroute.com/v1/routes/routes/
    

    Example request

    [
      {
        "vehicle": 2032,
        "driver": null,
        "plan": "ab20be8f-e98e-4402-8519-98d6752e0f1a",
        "planned_date": "2016-05-20",
        "estimated_time_start": "03:00:00",
        "estimated_time_end": "19:33:00",
        "status": "pending",
        "total_duration": "16:33:00",
        "total_distance": 0,
        "total_load": 2086,
        "total_load_percentage": 0,
        "location_start_address": "Enrique Mac Iver 524, Santiago, Chile",
        "location_start_latitude": "-33.436571",
        "location_start_longitude": "-70.647308",
        "location_end_address": "Suecia 151, Providencia, Chile",
        "location_end_latitude": "-33.421958",
        "location_end_longitude": "-70.607270",
        "reference": "my reference"
      }
    ]
    

    Example response

    [
      {
        "id": "33ddc43b-5ca8-4455-b3af-16a2f1971c1e",
        "vehicle": 2032,
        "driver": null,
        "plan": "ab20be8f-e98e-4402-8519-98d6752e0f1a",
        "status": "pending",
        "planned_date": "2016-05-20",
        "estimated_time_start": "03:00:00",
        "estimated_time_end": "19:33:00",
        "total_duration": "16:33:00",
        "total_distance": 0,
        "total_load": 2086,
        "total_load_percentage": 0,
         "total_load_2": 0.0,
        "total_load_2_percentage": 0,
        "total_load_3": 0.0,
        "total_load_3_percentage": 0,
        "location_start_address": "Enrique Mac Iver 524, Santiago, Chile",
        "location_start_latitude": "-33.436571",
        "location_start_longitude": "-70.647308",
        "location_end_address": "Suecia 151, Providencia, Chile",
        "location_end_latitude": "-33.421958",
        "location_end_longitude": "-70.607270",
        "comment": "Route 1",
        "start_time": null,
        "end_time": null,
        "created": "2016-08-01T20:45:25.672207Z",
        "modified": "2016-08-01T20:45:25.674460Z",
        "kilometers": null,
        "total_visits": 0,
        "latitude_init": null,
        "longitude_init": null,
        "latitude_finish": null,
        "longitude_finish": null,
        "is_revised": false,
        "reference": "my reference"
      }
    ]
    

    Lista de vehículos con rutas para una fecha

    URL Definition

    GET https://api.simpliroute.com/v1/plans/{{planned_date}}/vehicles/
    

    Example response

    [
      {
        "color": "#FFCC33",
        "routes": [
          {
            "plan_id": "f61cd65a-075e-454f-a080-d2c573d2be3e",
            "id": "e708c5ba-6d49-4418-b87e-9061e1194b1b"
          }
        ],
        "driver":{
          "id": 742,
          "name": "Conductor Demo"
        },
        "name": "Mi auto",
        "id": 287
      }
    ]
    

    Un vehículo puede tener múltiples rutas en un día. Una ruta se identifica mediante un uuid.

    Lista de visitas por ruta

    GET https://api.simpliroute.com/v1/plans/routes/{{PLAN_ID}}/visits/
    

    Example response

    [
      {
        "status": "failed",
        "plan_id": "f61cd65a-075e-454f-a080-d2c573d2be3e",
        "reference": "",
        "title": "STARK INDUSTRIES",
        "checkout_time": "2017-03-13T20:17:20Z",
        "longitude": "-70.651066",
        "id": 89274,
        "route_id": "e708c5ba-6d49-4418-b87e-9061e1194b1b",
        "address": "HUERFANOS 1011, SANTIAGO, Santiago",
        "latitude": "-33.439626",
        "estimated_time_arrival": "09:28:00",
        "order": 2
      },
      {
        "status": "completed",
        "plan_id": "f61cd65a-075e-454f-a080-d2c573d2be3e",
        "reference": "",
        "title": "PELUQUERIA DI GIANCARLO",
        "checkout_time": "2017-03-13T20:17:11Z",
        "longitude": "-70.659729",
        "id": 89273,
        "route_id": "2d3ced6c-70e4-414e-8313-d5abe9166a15",
        "address": "FANOR VELASCO 85, SANTIAGO, Santiago",
        "latitude": "-33.442880",
        "estimated_time_arrival": "09:05:00",
        "order": 1
      }
    ]
    

    Un vehículo puede tener múltiples rutas en un día. Una ruta se identifica mediante un uuid.

    Actualizar el campo de referencia por ruta

    PATCH https://api.simpliroute.com/v1/routes/routes/{{route_id}}/
    

    Example request

    {
      "reference": "my own reference"
    }
    

    Example response

    {
      "id": "32024005-7b45-455d-b901-f3f9afa2679e",
      "vehicle": 278533,
      "driver": 129373,
      "plan": "ab20be8f-e98e-4402-8519-98d6752e0f1a",
      "status": "pending",
      "planned_date": "2024-02-28",
      "estimated_time_start": "09:00:00",
      "estimated_time_end": "10:54:00",
      "total_duration": "01:54:00",
      "total_distance": 60992,
      "total_load": 0.0,
      "total_load_percentage": 0,
      "total_load_2": 0.0,
      "total_load_2_percentage": 0,
      "total_load_3": 0.0,
      "total_load_3_percentage": 0,
      "location_start_address": "Lord Cochrane 298, Santiago, Chile",
      "location_start_latitude": "-33.449977",
      "location_start_longitude": "-70.654465",
      "location_end_address": "Av. Vicuña Mackenna 2365, Ñuñoa, San Joaquín, Región Metropolitana, Chile",
      "location_end_latitude": "-33.473420",
      "location_end_longitude": "-70.624235",
      "comment": "Route 1",
      "start_time": null,
      "end_time": null,
      "created": "2024-02-28T17:20:37.919471Z",
      "modified": "2024-04-02T20:14:46.945819Z",
      "kilometers": null,
      "total_visits": 2,
      "latitude_init": null,
      "longitude_init": null,
      "latitude_finish": null,
      "longitude_finish": null,
      "is_revised": false,
      "reference": "my own reference"
    }
    

    Route Properties

    Attributes Data Type Description
    color String Stores the color assigned to the route when creating a plan. To use this property, the account configuration enable_colors_for_contiguous_routes must be enabled.
    is_start_blocked Boolean This property is used to block the start of a route.

    Get Route Properties

    URL Definition

    
    GET https://api.simpliroute.com/v1/routes/routes-properties/{{ROUTE_ID}}
    
    

    Example Response

    {
      "route": "3d20088b-02b8-456b-80f9-ecfa8dbf27d6",
      "color": "#0000FF",
      "is_start_blocked": false
    }
    

    Este endpoint recupera todas las propiedades de una ruta especificada.

    Crear Propiedades de Ruta

    URL Definition

    
    POST https://api.simpliroute.com/v1/routes/routes-properties/
    
    

    Example Request

    {
      "route": "3d20088b-02b8-456b-80f9-ecfa8dbf27d6",
      "color": null,
      "is_start_blocked": false
    }
    

    Este endpoint se utiliza para crear propiedades para una ruta especificada. Si las propiedades para la ruta ya existen, se devolverá una respuesta de error.

    Actualizar Propiedades de Ruta

    URL Definition

    
    PUT https://api.simpliroute.com/v1/routes/routes-properties/{{ROUTE_ID}}
    
    

    Example Request

    {
      "color": "#D50000",
      "is_start_blocked": true
    }
    

    Este endpoint se utiliza para actualizar todas las propiedades de una ruta especificada.

    Actualización Parcial de Propiedades de Ruta

    
    PATCH https://api.simpliroute.com/v1/routes/routes-properties/{{ROUTE_ID}}
    
    

    Example Request

    {
      "is_start_blocked": false
    }
    

    Este endpoint permite la actualización parcial de las propiedades de una ruta. Solo se actualizarán las propiedades incluidas en el cuerpo de la solicitud.

    Eliminar Propiedades de Ruta

    
    DELETE https://api.simpliroute.com/v1/routes/routes-properties/{{ROUTE_ID}}
    
    

    Este endpoint se utiliza para eliminar todas las propiedades de una ruta especificada.

    Búsqueda Masiva de Propiedades de Rutas

    
    POST https://api.simpliroute.com/v1/routes/routes-properties/bulk-search/
    
    

    Example Request

    {
      "route_ids": [
        "da6c3bac-898d-4343-8b05-5b80f2d7c26a",
        "3d20088b-02b8-456b-80f9-ecfa8dbf27d6"
      ]
    }
    

    Example Response

    [
        {
            "route": "3d20088b-02b8-456b-80f9-ecfa8dbf27d6",
            "color": "#658900",
            "is_start_blocked": false
        },
        {
            "route": "da6c3bac-898d-4343-8b05-5b80f2d7c26a",
            "color": null,
            "is_start_blocked": true
        }
    ]
    

    Este endpoint se utiliza para recuperar las propiedades de múltiples rutas en una sola solicitud. Al proporcionar una lista de IDs de rutas, puedes obtener las propiedades de cada ruta especificada.

    Vehículos

    Para facilitar el flujo de integración, la carga de los vehículos de cada cliente se puede realizar a través de la API utilizando los siguientes endpoints. La entidad de entrega está separada de la entidad del vehículo en SimpliRoute. Esto con el objetivo de realizar un mejor seguimiento del rendimiento de los vehículos u otras métricas internas del usuario.

    Crear vehículos

    URL Definition

    
    POST https://api.simpliroute.com/v1/routes/vehicles/
    
    

    Example Request with mandatory fields

    
    {
        "name": "ASDFQWER",
        "capacity": 2000,
        "default_driver": null,
        "location_start_address": "Direccion A",
        "location_start_latitude": -33.3456,
        "location_start_longitude": -70.2345,
        "location_end_address": "Direccion B",
        "location_end_latitude": -33.34234,
        "location_end_longitude": -70.23456,
        "skills": []
    }
    

    Ejemplo de Solicitud con todos los campos disponibles

    
    {
        "name": "Camión-1",
        "capacity": 1000,
        "default_driver": null,
        "location_start_address": "1 Calle A, Guatemala City, Guatemala",
        "location_end_address": "1 Calle A, Guatemala City, Guatemala",
        "location_end_latitude": "14.582131",
        "location_end_longitude": "-90.487034",
        "location_start_latitude": "14.582131",
        "location_start_longitude": "-90.487034",
        "skills": [],
        "capacity2": "1",
        "capacity3": "1",
        "cost": null,
        "shift_start": null,
        "shift_end": null,
        "reference_id": "12AB",
        "license_plate": "ABCD",
        "min_load": 0,
        "min_load_2": 0,
        "min_load_3": 0,
        "max_visit": null,
        "max_time": null,
        "rest_time_start": null,
        "rest_time_end": null,
        "rest_time_duration": null,
        "codrivers": []
    }
    

    Example Response

    {
        "id": 487294,
        "name": "Camión-1",
        "shift_start": null,
        "shift_end": null,
        "capacity": 1000.0,
        "capacity_2": 1.0,
        "capacity_3": 1.0,
        "default_driver": null,
        "location_start_address": "1 Calle A, Guatemala City, Guatemala",  //(warehouse starting point of the vehicle)
        "location_start_latitude": "14.582131",
        "location_start_longitude": "-90.487034",
        "location_end_address": "1 Calle A, Guatemala City, Guatemala",  //(warehouse or last point of the vehicle)
        "location_end_latitude": "14.582131",
        "location_end_longitude": "-90.487034",
        "skills": [],
        "created": "2024-06-26T16:28:39.193486Z",
        "modified": "2024-06-26T16:28:39.193486Z",
        "color": "#FF8C00",
        "reference_id": "12AB",
        "license_plate": "ABCD",
        "cost": null,
        "min_load": 0,
        "min_load_2": 0,
        "min_load_3": 0,
        "max_visit": null,
        "rest_time_start": null,
        "rest_time_end": null,
        "rest_time_duration": null,
        "deleted": false,
        "max_time": null,
        "codrivers": [],
        "status": "active"
    }
    

    Listado de vehículos

    URL Definition

    
    GET https://api.simpliroute.com/v1/routes/vehicles/
    

    Example Response

    [{
        "id": 487294,
        "name": "Camión-1",
        "shift_start": null,
        "shift_end": null,
        "capacity": 1000.0,
        "capacity_2": 1.0,
        "capacity_3": 1.0,
        "default_driver": null,
        "location_start_address": "1 Calle A, Guatemala City, Guatemala",
        "location_start_latitude": "14.582131",
        "location_start_longitude": "-90.487034",
        "location_end_address": "1 Calle A, Guatemala City, Guatemala",
        "location_end_latitude": "14.582131",
        "location_end_longitude": "-90.487034",
        "skills": [],
        "created": "2024-06-26T16:28:39.193486Z",
        "modified": "2024-06-26T16:28:39.193486Z",
        "color": "#FF8C00",
        "reference_id": "12AB",
        "license_plate": "ABCD",
        "cost": null,
        "min_load": 0,
        "min_load_2": 0,
        "min_load_3": 0,
        "max_visit": null,
        "rest_time_start": null,
        "rest_time_end": null,
        "rest_time_duration": null,
        "deleted": false,
        "max_time": null,
        "codrivers": [],
        "status": "active"
    }]
    
    

    Eliminar un vehículo

    URL Definition

    
    DELETE https://api.simpliroute.com/v1/routes/vehicles/{VECHICLE_ID}
    

    Clientes

    Un cliente es un individuo o una empresa. Los clientes son los usuarios finales.

    Crear Clientes

    URL Definition

    
    POST https://api.simpliroute.com/v1/accounts/clients/
    
    

    Example Request

    
    [{
        "key": "123456",
        "title": "Coop Enargas",
        "address": "",
        "latitude": null,
        "longitude": null,
        "load": null,
        "load_2": 0.0,
        "load_3": 0.0,
        "window_start": null,
        "window_end": null,
        "window_start_2": null,
        "window_end_2": null,
        "duration": "00:00:00",
        "contact_name": null,
        "contact_phone": null,
        "contact_email": null,
        "notes": null,
        "priority_level": null,
        "skills_required": [
                30744,
                47593
            ],
            "skills_optional": [
                30567
            ],
        "tags": [],
    }]
    

    Mediante el siguiente método POST, los clientes/usuarios finales pueden ser cargados en la aplicación de SimpliRoute. Esto genera el maestro de clientes para cada una de las cuentas que se registrarán y que se conectarán con los servicios web de cada ERP. Cada cliente principal debe tener su propio token para realizar la conexión e insertar los datos en la plataforma.

    Cuando creas clientes, estos pueden ser visualizados desde la extensión del maestro de clientes en la plataforma de SimpliRoute.

    Obtener Clientes

    URL Definition

    
    GET https://api.simpliroute.com/v1/accounts/clients/?key={{CLIENT_ID}}
    
    

    Example Request

    [{
        "id": 68156,
        "key": "123456",
        "title": "Cliente Ejemplo",
        "address": "Pedro Montt 2245, Valparaíso, V Región",
        "latitude": "-33.464115",
        "longitude": "-70.652859",
        "load": 4.0,
        "load_2": 2.0,
        "load_3": 1.0,
        "window_start": "09:00:00",
        "window_end": "17:00:00",
        "window_start_2": null,
        "window_end_2": null,
        "duration": "00:00:00",
        "contact_name": "",
        "contact_phone": "",
        "contact_email": "[email protected]",
        "notes": "Notas de Texto",
        "priority_level": null
        }
    ]
    

    A través del método GET de clientes, puedes obtener el ID y la información relacionada con el cliente vía API. Con esta información, podemos generar las visitas.

    Eliminar un Cliente

    URL Definition

    DELETE https://api.simpliroute.com/v1/accounts/clients/{{CLIENT_ID}}/
    

    Delete Customers

    URL Definition

    DELETE https://api.simpliroute.com/v1/accounts/clients/
    

    Example Request body

    {
     [000000, 000001...]
    }
    
    

    El arreglo debe contener los identificadores (id) de los clientes que deseas eliminar.

    Actualizar Clientes

    URL Definition

    PUT https://api.simpliroute.com/v1/accounts/clients/
    

    Example Request

    
    [{
        "id": 68156,
        "key": "123456",
        "title": "Coop Enargas",
        "address": "",
        "latitude": null,
        "longitude": null,
        "load": null,
        "load_2": 0.0,
        "load_3": 0.0,
        "window_start": null,
        "window_end": null,
        "window_start_2": null,
        "window_end_2": null,
        "duration": "00:00:00",
        "contact_name": null,
        "contact_phone": null,
        "contact_email": null,
        "notes": null,
        "priority_level": null,
        "skills_required": [
                30744,
                47593
            ],
            "skills_optional": [
                30567
            ],
        "tags": [],
    }]
    

    Este endpoint permite actualizar la información de múltiples clientes.

    Propiedades Personalizadas de Clientes

    Las propiedades personalizadas de clientes son atributos adicionales que se pueden agregar a los clientes para almacenar cualquier tipo de información necesaria. Para agregar propiedades personalizadas a tus clientes, primero debes crear el atributo en tu cuenta. Una vez creado, estos atributos pueden usarse al crear y modificar registros de clientes.

    Crear Propiedad Personalizada

    URL Definition

    POST https://api.simpliroute.com/v1/planner/client-properties/
    

    Example Request

    {
      "label": "price",
      "type": "int"
    }
    

    Este endpoint se utiliza para crear una propiedad personalizada para los clientes en el sistema o cuenta. Las propiedades personalizadas te permiten agregar atributos específicos adaptados a tus necesidades, los cuales pueden usarse al crear o modificar registros de clientes.

    Attributes Data Type Description
    label String The name of the custom property.
    type String The data type of the custom property. Possible values include 'str', 'int', 'float', 'bool'

    Usando Propiedades Personalizadas

    Example Request

    [
        {
            "key": "SFKK8976678",
            "title": "Cliente Ejemplo",
            "address": "Pedro Montt 2246, Valparaíso, V Región, Chile",
            "latitude": "-33.047400",
            "longitude": "-71.612920",
            "skills_required": [],
            "skills_optional": [],
            "load": "4",
            "load_2": "2",
            "load_3": "1",
            "window_start": "09:00:00",
            "window_end": "17:00:00",
            "window_start_2": null,
            "window_end_2": null,
            "duration": "00:00:00",
            "contact_name": "Cliente",
            "contact_email": "[email protected]",
            "contact_phone": "56995466337",
            "tags": [],
            "visit_type": null,
            "notes": "The doorbell is faulty",
            "priority_level": null,
            "custom_properties": {
                "price": 100
            }
        }
    ]
    

    Una vez que hayas creado tu propiedad personalizada, puedes usarla en la creación y modificación de registros de clientes.

    ForceField

    Example Request

    [
        {
            "key": "SFKK8976678",
            "title": "Cliente Ejemplo",
            "address": "Pedro Montt 2246, Valparaíso, V Región, Chile",
            "latitude": "-33.047400",
            "longitude": "-71.612920",
            "skills_required": [],
            "skills_optional": [],
            "load": "4",
            "load_2": "2",
            "load_3": "1",
            "window_start": "09:00:00",
            "window_end": "17:00:00",
            "window_start_2": null,
            "window_end_2": null,
            "duration": "00:00:00",
            "contact_name": "Cliente",
            "contact_email": "[email protected]",
            "contact_phone": "56995466337",
            "tags": [],
            "visit_type": null,
            "notes": "The doorbell is faulty",
            "priority_level": null,
            "sales_visit_scheduled": {
                "period": 7,
                "interval": 4,
                "frequency": 2
            },
            "scheduled_visit_days": {
                "any_week": [
                    "Monday",
                    "Tuesday"
                ]
            },
            "custom_properties": {
                "price": 100,
                "currency": "USD"
            }
        },
            {
            "key": "SFKK89766100",
            "title": "Cliente 2 Ejemplo",
            "address": "Pedro Montt 2250, Valparaíso, V Región, Chile",
            "latitude": "-33.047400",
            "longitude": "-71.612920",
            "skills_required": [],
            "skills_optional": [],
            "load": "4",
            "load_2": "2",
            "load_3": "1",
            "window_start": "09:00:00",
            "window_end": "17:00:00",
            "window_start_2": null,
            "window_end_2": null,
            "duration": "00:00:00",
            "contact_name": "Cliente 2",
            "contact_email": "[email protected]",
            "contact_phone": "56995466337",
            "tags": [],
            "visit_type": null,
            "notes": "The doorbell is faulty",
            "priority_level": null,
            "sales_visit_scheduled": {
                "period": 28,
                "interval": 1,
                "frequency": 3
            },
            "scheduled_visit_days": {
                "week_3": [
                  "Monday",
                  "Tuesday",
                  "Sunday"
                ]
            },
            "custom_properties": {
                "price": 200,
                "currency": "USD"
            }
        }
    ]
    

    Para usar los atributos de ForceField, es necesario activar el complemento (addon) territory_planner. Los nuevos atributos son sales_visit_scheduled y scheduled_visit_days. Estos pueden usarse en los endpoints para crear, modificar y recuperar clientes.

    Objeto de Programación de Visitas de Ventas

    Attributes Data Type Description
    frequency Integer Represents the number of times a client should be visited within a given period.
    period Integer Represents the duration of a visit cycle for a particular client. Possible values are weekly (7), biweekly (14), or monthly (28).
    interval Integer Represents the time gap between visits.
    seller Integer Specifies who conducts the visit to the client, which can be either a seller or a vehicle.

    Objeto de Días de Visitas Programadas del Cliente

    Este objeto define los días de la semana en los que un cliente tiene visitas programadas. Los atributos están organizados por semanas, incluyendo una opción general para cualquier semana en la que no se haya definido una semana específica. Cada atributo enumera los posibles días de la semana que se pueden seleccionar para la programación.

    Attributes Data Type Description
    any_week Array This attribute is used when there is no predefined week. Possible values are 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'.
    week_1 Array This attribute corresponds to the first week of the month. Possible values are 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'.
    week_2 Array This attribute corresponds to the second week of the month. Possible values are 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'.
    week_3 Array This attribute corresponds to the third week of the month. Possible values are 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'.
    week_4 Array This attribute corresponds to the fourth week of the month. Possible values are 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'.

    Usuarios

    Un usuario en SimpliRoute es un repartidor que realizará entregas a través de nuestra aplicación móvil.

    Listar usuarios

    URL Definition

    
     GET https://api.simpliroute.com/v1/accounts/drivers/
    
    

    Example Response ```json [{ "id": 114, "username": "user2", "name": "", "phone": "", "email": "", "is_owner": false, "is_admin": false, "is_driver": true, "old_id": 1477, "created": "2016-06-24T20:47:06.859895Z", "modified": "2016-06-30T20:04:51.043122Z", "last_login": null }, { "id": 24, "old_id": 930, "username": "test", "name": "Test", "phone": "", "email": "", "is_owner": false, "is_admin": false, "is_driver": true, "old_id": 1477, "created": "2016-06-24T20:47:06.859895Z", "modified": "2016-06-30T20:04:51.043122Z", "last_login": null }]

    ## Crear usuario
    
    Con el siguiente endpoint puedes crear un usuario mediante la API.
    
    > URL Definition
    
    ```url
    
    POST https://api.simpliroute.com/v1/accounts/drivers/
    
    

    Example Body ```json [{ "username": "testtest2", "name": "Conductor 1", "phone": "", "email": "", "is_admin": false, "password": "driver", "is_driver": true }]

    > Example Response
    ```json
    [{
        "id": 40779,
        "username": "testtest2",
        "name": "Conductor 1",
        "phone": "",
        "email": "",
        "is_owner": false,
        "is_admin": false,
        "is_driver": true,
        "is_router_jr": false,
        "is_monitor": false,
        "is_coordinator": false,
        "is_router": false,
        "is_staff": false,
        "old_id": null,
        "created": "2020-03-19T19:13:45.178268Z",
        "modified": "2020-03-19T19:13:45.223900Z",
        "last_login": null
    }]
    

    Obtener un usuario determinado

    URL Definition

    
    GET https://api.simpliroute.com/v1/accounts/drivers/{{user_id}}/
    
    

    Example Response json [ {"id": 203, "username": "driver33", "name": "Driver 3", "phone": "", "email": "", "is_owner": false, "is_admin": false, "is_driver": true, "old_id": 1979, "created": "2016-08-01T20:23:31.966307Z", "modified": "2016-08-01T20:23:32.158526Z", "last_login": null } ]

    Actualizar usuario

    URL Definition

    
    PUT https://api.simpliroute.com/v1/accounts/drivers/{{USER_ID}}/
    
    
    

    Example Body ```json [{ "username": "driver3", "name": "Driver 3", "email": "", "is_admin": false, "password": "driver" }]

    > Example Response
    ``` json
    [{
        "id": 24,
      "old_id": 930,
      "username": "test",
      "name": "Test",
      "created": "2016-03-08T15:54:03.095458Z",
      "modified": "2016-03-08T15:54:03.268615Z",
      "last_login": null}]
    
    

    Eliminar usuario

    URL Definition

    
    DELETE https://api.simpliroute.com/v1/accounts/drivers/{{user_id}}/
    
    
    

    Habilidades

    Las habilidades son una forma de etiquetar a nuestros visitantes y vehículos para que el algoritmo utilice esas etiquetas como restricciones. Si un visitante requiere la habilidad "FRÍO" (COLD), los vehículos que pueden transportar ese despacho también deben tener la habilidad "FRÍO" (COLD).

    Para obtener la lista de habilidades

    URL Definition

    
    GET https://api.simpliroute.com/v1/routes/skills/
    
    

    Example response

    
    [
      {
        "id": 295,
        "skill": "frío",
        "created": "2017-01-24T21:06:42.545448Z",
        "modified": "2017-01-24T21:06:42.545683Z"
      },
      {
        "id": 296,
        "skill": "calderon",
        "created": "2017-01-24T21:06:46.328027Z",
        "modified": "2017-01-24T21:06:46.328273Z"
      }
    ]
    

    Zonas

    El módulo de Zonas te permite definir y dibujar zonas personalizadas en el mapa, que luego pueden asignarse a vehículos específicos, asegurando que solo operen dentro de esas áreas designadas.

    Si este módulo aún no está habilitado en tu cuenta, comunícate con nosotros a [email protected] para activarlo.

    Parameter Type Description
    id int Unique identifier for the zone.
    name string The name of the zone, in this case "ZONA-TEST2".
    coordinates array List of geographical coordinates (latitude and longitude) defining the zone.
    lat string Latitude of a point in the zone.
    lng string Longitude of a point in the zone.
    vehicles array List of vehicle IDs assigned to the zone.
    enabled boolean Indicates whether the zone is enabled or not.
    schedules array List of days when the zone is active (e.g., "Monday", "Saturday", etc.).

    URL Definition

    
    GET https://api.simpliroute.com/v1/zones/
    
    

    Example response

    
    [
        {
            "id": 67664,
            "name": "ZONA-TEST2",
            "coordinates": [
                {
                    "lat": "-12.105433",
                    "lng": "-77.017408"
                },
                {
                    "lat": "-12.099576",
                    "lng": "-77.017308"
                },
                {
                    "lat": "-12.094063",
                    "lng": "-77.012727"
                },
                {
                    "lat": "-12.099921",
                    "lng": "-77.004068"
                },
                {
                    "lat": "-12.105433",
                    "lng": "-77.017056"
                }
            ],
            "vehicles": [
                28202
            ],
            "enabled": true,
            "schedules": [
                "Monday",
                "Saturday",
                "Thursday",
                "Friday",
                "Tuesday",
                "Sunday",
                "Wednesday"
            ]
        }
    ]
    

    Flotas

    El módulo de Flotas te permite organizar tus vehículos en flotas y asignarlos a usuarios específicos. Por ejemplo, puedes crear rutas para todos los vehículos de tu cuenta y restringir el acceso de los usuarios para que solo puedan ver los vehículos asignados a ellos.

    Si este módulo aún no está habilitado en tu cuenta, comunícate con nosotros a [email protected] para activarlo.

    Parameter Type Description
    id int Unique identifier for the fleet.
    name string The name of the fleet (e.g., "Almacén A").
    vehicles array List of vehicle IDs assigned to the fleet.
    users array List of user IDs assigned to the fleet.
    created string The timestamp when the fleet was created.
    modified string The timestamp when the fleet was last modified.

    URL Definition

    
    GET https://api.simpliroute.com/v1/fleets/
    
    

    Example response

    [
       {
            "id": 33867,
            "name": "Almacén A",
            "vehicles": [
                404639,
                297117,
                312450,
                280202
            ],
            "users": [
                185434,
                183371,
                247042,
                295087
            ],
            "created": "2022-01-27T22:53:43.254711Z",
            "modified": "2024-02-29T17:56:34.177789Z"
      }
    ]
    

    Webhooks

    Usa webhooks para recibir notificaciones sobre eventos que ocurren en una cuenta de SimpliRoute.

    Cómo trabajar con los webhooks de SimpliRoute

    SimpliRoute puede enviar eventos de webhook que notifiquen a tu aplicación cada vez que ocurre un evento en tu cuenta. Esto es especialmente útil para eventos—como entregas completadas o fallidas—que no son desencadenados por una solicitud directa de la API. Cuando ocurre el evento, SimpliRoute enviará un POST a tu URL configurada.

    Este objeto Event contiene toda la información relevante sobre lo que acaba de suceder, incluyendo el tipo de evento y los datos asociados. SimpliRoute envía el objeto Event, a través de una solicitud HTTP POST, a cualquier URL de endpoint que hayas definido en la configuración de Webhooks de tu cuenta.

    Qué eventos pueden ser notificados

    Actualmente, SimpliRoute puede notificar los siguientes eventos:

    • Plan creado
    • Edición de plan
    • Creación de ruta
    • Edición de ruta
    • Eliminación de ruta
    • Inicio de ruta
    • Finalización de ruta
    • En camino
    • Checkout
      • Entrega completada
      • Entrega fallida
      • Entrega parcial
    • Detalles del Checkout

    Si necesitas otros eventos, háznoslo saber para agregarlos a nuestro roadmap. No dudes en contactarnos por correo electrónico en [email protected].

    Configuración de tus ajustes de Webhooks

    A continuación describimos los pasos a seguir para leer, crear, actualizar y eliminar webhooks a través de la API.

    Claves disponibles para webhooks:

    • plan_created
    • plan_edited
    • route_created
    • route_edited
    • route_started
    • route_finished
    • on_its_way
    • visit_checkout
    • visit_checkout_detailed

    Importante: Cada webhook está relacionado con una URL y cabeceras. Por ejemplo: route_created está relacionado con: - route_created_webhook_url - route_created_webhook_headers

    Además, las solicitudes deben incluir el encabezado:

    Example Headers

    [{
        Content-Type: application/json
        authorization: token {{TOKEN}}
    }]
    
    // Where {{TOKEN}} equals the SR account token.
    
    
    Attributes Description
    webhook Name of the available webhook object.
    url URL provided by the customer
    headers Necessary parameters for communication towards the final server

    Si tienes dudas o problemas para configurar los Webhooks: - Envía un correo electrónico a nuestro equipo a [email protected] - En este correo, indica la URL en la que deseas recibir el webhook. - Te avisaremos cuando la configuración esté lista.

    Crear Webhook

    URL Definition

    
    POST https://api.simpliroute.com/v1/addons/webhooks
    
    

    Example body

    {
      "webhook": "plan_created",
      "url": "https://estoesunwebhookdeprueba.com",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Token 16a57ec5ad76c627959c75323274d33d8cc0451e"
      }
    }
    

    Example response

    [
      {
        "title": "plan_created_webhook_url webhook url",
        "key": "plan_created_webhook_url",
        "value": "https://estoesunwebhookdeprueba.com",
        "description": "plan_created_webhook_url webhook url Luis Bermudez SR Team",
        "add_on_id": 29950
      },
      {
        "title": "plan_created_webhook_headers webhook headers",
        "key": "plan_created_webhook_headers",
        "value": "{\"Content-Type\": \"application/json\", \"Authorization\": \"Token 16a57ec5ad76c627959c75323274d33d8cc0451e\"}",
        "description": "plan_created_webhook_headers webhook url Luis Bermudez SR Team",
        "add_on_id": 29950
      }
    ]
    

    Listado de Webhooks

    URL Definition

    
    GET https://api.simpliroute.com/v1/addons/webhooks
    
    

    Example response

    [
      {
        "title": "plan_created_webhook_url webhook url",
        "key": "plan_created_webhook_url",
        "value": "https://estoesunwebhookdeprueba.com",
        "description": "plan_created_webhook_url webhook url Luis Bermudez SR Team",
        "add_on_id": 29950
      },
      {
        "title": "plan_created_webhook_headers webhook headers",
        "key": "plan_created_webhook_headers",
        "value": "{\"Content-Type\": \"application/json\", \"Authorization\": \"Token 16a57ec5ad76c627959c75323274d33d8cc0451e\"}",
        "description": "plan_created_webhook_headers webhook url Luis Bermudez SR Team",
        "add_on_id": 29950
      }
    ]
    

    Actualizar Webhooks

    URL Definition

    
    PUT https://api.simpliroute.com/v1/addons/webhooks
    
    

    Example body

    {
      "webhook": "plan_created",
      "url": "https://estoesunwebhookdeprueba.com/nueva-url",
      "headers": {
        "Content-Type": "application/json"
      }
    }
    
    

    Example response

    [
      {
        "title": "plan_created_webhook_url webhook url",
        "key": "plan_created_webhook_url",
        "value": "https://estoesunwebhookdeprueba.com/nueva-url",
        "description": "plan_created_webhook_url webhook url Luis Bermudez SR Team"
      },
      {
        "title": "plan_created_webhook_headers webhook headers",
        "key": "plan_created_webhook_headers",
        "value": "{\"Content-Type\":\"application/json\"}",
        "description": "plan_created_webhook_headers webhook url Luis Bermudez SR Team"
      }
    ]
    

    Eliminar Webhooks

    URL Definition

    
    DELETE https://api.simpliroute.com/v1/addons/webhooks
    
    
    

    Example body

    {
        "webhook": "plan_created"
    }
    
    

    Example response

    [{
      "message": "The webhook was deleted"
    }]
    

    Webhook para creación de planes

    SimpliRoute puede enviar un Webhook al crear un Plan. La información disponible se detalla en la tabla anterior al momento en que el Plan se crea utilizando el método POST, con las cabeceras que el cliente puede especificar. El webhook espera una respuesta con el código de estado 200; de lo contrario, reintentará después de 30 segundos, hasta un máximo de 3 intentos en total.

    URL Definition

    
    POST https://api.simpliroute.com/v2/plans/create-plan/ 
    
    

    Example

    [{
      "account_id": 295,
      "id": "9503f703-ba7c-41a0-b91f-3bcebeca7b17",
      "start_date": "2020-03-19",
      "end_date": "2020-03-19",
      "reset_day": 1,
      "route_ids": [
        "9894ddcd-e844-4c77-90e8-9d9a2a226f05"
      ],
      "fleet_id": 647
    }]
    
    Attributes Type Description
    id UUID Plan ID
    account_id int Account id.
    start_date Date format YYYY-MM-DD The date when the plan starts.
    end_date Date format YYYY-MM-DD The date when the plan ends.
    reset_day Int, 1=Monday, 2=Tuesday…, 100=no reset The day when the plan resets.
    route_ids Array of uuid List of the routes in the plan.
    fleet_id int Id of the fleet assigned to the plan

    Webhook al editar un plan

    SimpliRoute puede enviar un Webhook cuando se edita un plan. Para utilizar este webhook, el cliente debe proporcionar un servicio web preparado para procesar solicitudes POST con la información detallada en las tablas anteriores.

    El webhook espera una respuesta con el código de estado 200; de lo contrario, reintentará después de 30 segundos, hasta un máximo de 3 intentos en total.

    URL Definition

    
    POST https://api.simpliroute.com/v2/plans/edit-plan/ 
    
    

    Example

    {
     "id": "9b420e42-m492-29m1-a214-f2ad927707b4",
     "account": {
       "id": 1,
       "name": "[email protected]"
     },
     "end_date": "2019-12-24",
     "reset_day": 1,
     "start_date": "2019-12-24",
     "fleet_id": 647,
     "routes": [
       {
         "id": "900787e1-k582-0185-9eeb-d93b68c98b85",
         "planned_date": "2019-12-24",
         "total_load": 50,
         "total_load_2": 0,
         "total_load_3": 0,
         "estimated_time_end": "11:37:00",
         "estimated_time_start": "09:00:00",
         "comment": null,
         "driver": {
           "id": 1,
           "name": "Driver Demo"
         },
         "vehicle": {
           "id": 1,
           "reference": "XXXX11",
           "name": "Vehicle Demo"
         },
         "visits": [
           {
             "id": 20661418,
             "title": "foo",
             "planned_date": "2019-12-24",
             "latitude": "-33.370405",
             "longitude": "-70.684798",
             "load": 0,
             "load_2": 0,
             "load_3": 0,
             "duration": "0:10:00",
             "estimated_time_departure": "09:30:00",
             "estimated_time_arrival": "09:20:00",
             "notes": "",
             "order": 1
           },
           {
             "load": 25,
             "estimated_time_departure": "10:00:00",
             "planned_date": "2019-12-24",
             "load_3": 0,
             "load_2": 0,
             "duration": "0:15:00",
             "estimated_time_arrival": "09:45:00",
             "id": 20661406,
             "title": "bar",
             "notes": "",
             "longitude": "-70.758134",
             "latitude": "-33.384390",
             "order": 2
           },
           {
             "load": 0,
             "estimated_time_departure": "10:24:00",
             "planned_date": "2019-12-24",
             "load_3": 0,
             "load_2": 0,
             "duration": "0:10:00",
             "estimated_time_arrival": "10:14:00",
             "id": 20661420,
             "title": "foo-bar",
             "notes": "",
             "longitude": "-70.703681",
             "latitude": "-33.427045",
             "order": 3
           }       
         ]     
       }
     ]
    }
    

    Plan Object

    Attributes Type Description
    id UUID Plan ID
    account {id, name} id: int - name: string. Account information.
    start_date Date format YYYY-MM-DD The date when the plan starts.
    end_date Date format YYYY-MM-DD The date when the plan ends.
    reset_day Int, 1=Monday, 2=Tuesday…, 100=no reset The day when the plan resets.
    fleet_id int Id of the fleet assigned to the plan
    routes list(Route) List of the routes in the plan. See Route Object for details.

    Route Object

    Attributes Type Description
    id UUID Id of the route in SimpliRoute.
    planned_date date (YYYY-MM-DD) Date of the route
    total_load double The total load 1 of the route.
    total_load2 double The total load 2 of the route.
    total_load_3 double The total load 3 of the route.
    estimated_time_start time (hh:mm:ss) Estimated time of the route to start in local timezone of the account.
    estimated_time_end time (hh:mm:ss) Estimated time of the route to end in local timezone of the account.
    comment string Comment of the route.
    driver {id, name} id: id of the driver in SimpliRoute- name: name of the driver Driver information.
    vehicle {id, reference, name} id: id of the vehicle in SimpliRoute.reference: reference id, it could be the licence plate for example.name: name of the vehicle in SimpliRoute Vehicle information
    visits list(Visit) List of the visits in the route. See Visit Object for details.

    Visit Object

    Attributes Type Description
    id int Id of the visit in SimpliRoute.
    title string Title of the visit.
    planned_date Date format YYYY-MM-DD Date of the delivery.
    latitude double The date when the plan ends.
    longitude double The day when the plan resets.
    load double Load 1.
    load2 double Load 2.
    load3 double Load 3.
    duration double Service time of the visit.
    estimated_time_arrival double Estimated time to arrive to the visit.
    estimated_time_departure double Estimated time of departure from the visit. It should be estimated_time_arrival + duration.
    notes string Notes of the visit.
    order int Order of the visit in the route

    Webhook para la creacion de rutas

    SimpliRoute puede enviar Webhooks para la creación de rutas. La información disponible se detalla en la tabla a continuación. En el momento en que se crea la ruta utilizando el método POST, se pueden especificar las cabeceras que desee el cliente. El webhook espera una respuesta con el código de estado 200; de lo contrario, intentará de nuevo después de 30 segundos, hasta un máximo de 3 intentos en total.

    Example body

    {
      "id": "e5bb5b51-d494-483f-8180-ace00c89c06d",
      "comment": null,
      "planned_date": "2024-01-12",
      "plan": {
        "id": "1ef9f5c4-2197-41da-8f23-adfcabd272b5",
        "name": "12-01-2024 14:53:03"
      },
      "driver": {
        "id": 118553,
        "name": "rapidoqa1"
      },
      "route_start": {
        "lat": "-33.449977",
        "lon": "-70.654465",
        "address": "Lord Cochrane 298, Santiago, Chile",
        "start_time": null,
        "estimated_time_start": "09:42:00"
      },
      "route_end": {
        "lat": "-33.449977",
        "lon": "-70.654465",
        "address": "Lord Cochrane 298, Santiago, Chile",
        "estimated_time_end": "10:08:00",
        "end_time": null
      },
      "visit_ids": [
        370679703
      ],
      "info_visits": [
        {
          "id": 370679703,
          "reference": "",
          "tracking_id": "SR68561793642931",
          "order": 1,
          "estimated_time_arrival":"09:42:00",
          "notes":"notes"
        }
      ],
      "vehicle": {
        "id": 266603,
        "name": "VEH1F",
        "reference": "XXX333"
      },
      "timestamp": "2024-01-30 15:14:45.708968",
      "order": 3,
      "status": "created"
    }
    
    
    Attributes Type Description
    vehicle {id, name} id: int - name: string Vehicle information.
    plan {id, name} id: int - name: string Plan information
    timestamp timestamp UTC timestamp of the creation of the route.
    route_start {lat, lon, start_time, estimated_time_start, address} lat: float - lon: float - start_time: time - estimated_time_start: time - address: string Route start information. start_time is the time that the driver started the route, so it will be null always at this point, but if we extend this webhook in the future for edition it will have the “real” start_time.
    route_end {lat, lon, end_time, estimated_time_end, address} lat: float - lon: float - end_time: time - estimated_time_end: time- address: string. Route end information
    planned_date Date in format YYYY-MM-DD. Date for the route.
    visit_ids id List of the visit ids in the route.
    driver {id, name} id: int - name: string. Driver information.
    order int show the order of the vehicle route.
    status string Display the operation's status event, 'created'

    Webhook para al edicion de rutas

    SimpliRoute puede enviar Webhooks para la edición de rutas. La información disponible se detalla en la tabla a continuación. En el momento en que se actualiza la ruta utilizando el método POST, se pueden especificar las cabeceras que desee el cliente. El webhook espera una respuesta con el código de estado 200; de lo contrario, intentará de nuevo después de 30 segundos, hasta un máximo de 3 intentos en total.

    Example body

    [
      {  
       "vehicle":{  
          "id":1,
          "name":"Test",
          "reference": "1234FF"
       },
       "plan":{  
          "id":"528e6fa8-129d-4049-9a3c-8ad5ea12502e",
          "name":"Plan name"
       },
       "timestamp":"2019-07-17 14:32:14.799962",
       "route_start":{  
          "lat":"-33.448890",
          "start_time":null,
          "estimated_time_start":"09:00:00",
          "lon":"-70.669265",
          "address":"Santiago, Chile"
       },
       "route_end":{  
          "lat":"-33.448890",
          "lon":"-70.669265",
          "end_time":null,
          "estimated_time_end":"16:23:00",
          "address":"Santiago, Chile"
       },
       "planned_date":"2019-07-17",
       "visit_ids":[15901924, 15901923, 15901922, 15901921, 15901920, 15901919, 15901918, 15901917, 15901916, 15901915, 15901914, 15901913, 15901912, 15901911, 15901910, 15901909],
       "info_visits": [
            {
              "id": 15901924, "reference": "", "tracking_id": "SR88515397622033", "order": 1,   "estimated_time_arrival":"09:42:00", "notes":"notes",
              "id": 15901923, "reference": "", "tracking_id": "SR88515397622034", "order": 2, "estimated_time_arrival":"09:42:00", "notes":"notes",
              "id": 15901922, "reference": "", "tracking_id": "SR88515397622035", "order": 3, "estimated_time_arrival":"09:42:00", "notes":"notes",
              "id": 15901921, "reference": "", "tracking_id": "SR88515397622036", "order": 4, "estimated_time_arrival":"09:42:00", "notes":"notes"
            }
        ],
       "driver":{  
          "id":23870,
          "name":"Conductor 1"
       },
       "order":1,
       "status":"edited",
       "id":"51019ab7-c464-4503-bcd6-d00c3d6209f2"
    }]
    
    
    Attributes Type Description
    vehicle {id, name} id: int - name: string Vehicle information.
    plan {id, name} id: int - name: string Plan information
    timestamp timestamp UTC timestamp of the creation of the route.
    route_start {lat, lon, start_time, estimated_time_start, address} lat: float - lon: float - start_time: time - estimated_time_start: time - address: string Route start information. start_time is the time that the driver started the route, so it will be null always at this point, but if we extend this webhook in the future for edition it will have the “real” start_time.
    route_end {lat, lon, end_time, estimated_time_end, address} lat: float - lon: float - end_time: time - estimated_time_end: time- address: string. Route end information
    planned_date Date in format YYYY-MM-DD. Date for the route.
    visit_ids id List of the visit ids in the route.
    info_visits list(visit) List of the visits in the route.
    driver {id, name} id: int - name: string. Driver information.
    order int show the order of the vehicle route.
    status string Display the operation's status event, indicating whether the route has been edited or deleted.

    Webhook para el inicio de ruta

    SimpliRoute puede enviar un Webhook cuando una ruta comienza. La información disponible se detalla en la tabla anterior en el momento en que la ruta se inicia utilizando el método POST con cabeceras que el cliente puede especificar. El webhook espera una respuesta con el código de estado 200; de lo contrario, reintentará después de 30 segundos, hasta un máximo de 3 intentos en total.

    Url Definition

    
    POST https://api.simpliroute.com/v1/events/register/
    

    Example request

    
    curl 
    --location 
    --request POST 'http://api.simpliroute.com/v1/events/register/' \
    --header 'Authorization: Token b2de5a16bccec465aeb9083a4db41e1666520uij' \
    --header 'content-type: application/json;charset=UTF-8' \
    --header 'Content-Type: text/plain' \
    --data-raw '{
        "date_time" : "2020-05-27 16:35:00",
        "route_id": "402ecd99-a0c9-418c-9cd9-088a0cb70242",
        "type" : "ROUTE_STARTED"
    }'
    

    Example

    [
    {
      "vehicle": {
        "id": 101174,
        "name": "KGST"
      },
      "plan": {
        "id": "728c5d34-ff14-4ccf-9fd8-16257f4332e9",
        "name": "26-05-2020 21:37:25"
      },
      "timestamp": "2020-05-27 20:43:40.650476",
      "route_start": {
        "lat": "-33.459425",
        "start_time": "2020-05-27 16:35:00+00:00",
        "estimated_time_start": "09:00:00",
        "lon": "-70.654531",
        "address": "Aldunate 1047, Santiago, Región Metropolitana, Chile"
      },
      "route_end": {
        "lat": "-33.459425",
        "lon": "-70.654531",
        "end_time": null,
        "estimated_time_end": "09:15:00",
        "address": "Aldunate 1047, Santiago, Región Metropolitana, Chile"
      },
      "planned_date": "2020-05-26",
      "visit_ids": [
        32397185
      ],
      "driver": {
        "id": 26351,
        "name": "Flash"
      },
      "id": "e1d12cf7-25c6-4f01-98d5-83a52c9b3aed"
    }
    ]
    
    Attributes Type Description
    vehicle {id, name} id: int - name: string Vehicle information.
    plan {id, name} id: int - name: string Plan information
    timestamp timestamp UTC timestamp of the creation of the route.
    route_start {lat, lon, start_time, estimated_time_start, address} lat: float - lon: float - start_time: time - estimated_time_start: time - address: string Route start information. start_time is the time that the driver started the route, so it will be null always at this point, but if we extend this webhook in the future for edition it will have the “real” start_time.
    route_end {lat, lon, end_time, estimated_time_end, address} lat: float - lon: float - end_time: time - estimated_time_end: time- address: string. Route end information
    planned_date Date in format YYYY-MM-DD. Date for the route.
    visit_ids id List of the visit ids in the route.
    driver {id, name} id: int - name: string. Driver information.
    id id String with the route id.

    Webhook la finalización de ruta

    SimpliRoute puede enviar un Webhook cuando se finaliza una ruta. La información disponible se detalla en la tabla anterior al momento en que la ruta se finaliza utilizando el método POST con cabeceras que el cliente puede especificar. El webhook espera una respuesta con el código de estado 200; de lo contrario, reintentará después de 30 segundos, hasta un máximo de 3 intentos en total.

    Url Definition

    
    POST https://api.simpliroute.com/v1/events/register/
    

    Example request

    curl 
    --location 
    --request POST 'http://api.simpliroute.com/v1/events/register/' \
    --header 'Authorization: Token b2de5a16bccec465aeb9083a4db41e1666520uij' \
    --header 'content-type: application/json;charset=UTF-8' \
    --header 'Content-Type: text/plain' \
    --data-raw '{
        "date_time" : "2020-05-27 17:35:00",
        "route_id": "402ecd99-a0c9-418c-9cd9-088a0cb70242",
        "type" : "ROUTE_FINISHED"
    }'
    
    
    

    Example

    [{
      "vehicle": {
        "id": 101174,
        "name": "KGST"
      },
      "plan": {
        "id": "728c5d34-ff14-4ccf-9fd8-16257f4332e9",
        "name": "26-05-2020 21:37:25"
      },
      "timestamp": "2020-05-27 20:46:01.471879",
      "route_start": {
        "lat": "-33.459425",
        "start_time": "2020-05-27 16:35:00+00:00",
        "estimated_time_start": "09:00:00",
        "lon": "-70.654531",
        "address": "Aldunate 1047, Santiago, Región Metropolitana, Chile"
      },
      "route_end": {
        "lat": "-33.459425",
        "lon": "-70.654531",
        "end_time": "2020-05-27 17:35:00+00:00",
        "estimated_time_end": "09:15:00",
        "address": "Aldunate 1047, Santiago, Región Metropolitana, Chile"
      },
      "planned_date": "2020-05-26",
      "visit_ids": [
        32397185
      ],
      "driver": {
        "id": 26351,
        "name": "Flash"
      },
      "id": "e1d12cf7-25c6-4f01-98d5-83a52c9b3aed"
    }
    ]
    
    Attributes Type Description
    vehicle {id, name} id: int - name: string Vehicle information.
    plan {id, name} id: int - name: string Plan information
    timestamp timestamp UTC timestamp of the creation of the route.
    route_start {lat, lon, start_time, estimated_time_start, address} lat: float - lon: float - start_time: time - estimated_time_start: time - address: string Route start information. start_time is the time that the driver started the route, so it will be null always at this point, but if we extend this webhook in the future for edition it will have the “real” start_time.
    route_end {lat, lon, end_time, estimated_time_end, address} lat: float - lon: float - end_time: time - estimated_time_end: time- address: string. Route end information
    planned_date Date in format YYYY-MM-DD. Date for the route.
    visit_ids id List of the visit ids in the route.
    driver {id, name} id: int - name: string. Driver information.

    Webhook "En camino"

    SimpliRoute puede enviar información de visitas en el momento en que se lanza un evento de "en camino" llamando a un método POST a un servicio web proporcionado por los clientes. La información disponible se describe en la siguiente tabla (no necesariamente en ese orden). El webhook espera obtener una respuesta con el código 200; de lo contrario, intentará nuevamente cada 30 segundos, con un máximo de 3 intentos.

    Example body

    Attributes Type Description
    id int Id of the visit in SimpliRoute.
    load double Load 1.
    load2 double Load 2.
    load3 double Load 3.
    window_start Time Initial Hour when the visit can be visit
    window_end Time Final Hour when the visit can be visit
    window_start_2 Time Initial Hour when the visit can be visit
    window_end_2 Time Final Hour when the visit can be visit
    reference String Reference or internal identifier of the company. Example: Invoice or order number.
    planned_date date YYYY-MM-DD Date for the route.
    order int planned delivery order
    checkout_comment text Comments on delivery time
    duration time Service time
    calculated_service_time time Calculated service time
    title varchar(254) Visit Title.
    contact_name varchar(254) Contact name
    contact_email text e-mail contat
    contact_phone varchar(254) Contact phone
    notes text Notes of the visit .
    latitude numeric(9,6) Latitud of the visit
    longitude numeric(9,6) Longitud of the visit
    status varchar(100) Status of the visit: pending, completed or failed.
    address varchar(254) Address of the visit
    account varchar(254) Account name
    route varchar(254) Route name.
    status_changed timestamp Date and time of the last status change.
    priority_level int Visit priority.
    created timestamp Creation time of the visit.
    modified timestamp Time of the last modification of the visit.
    estimated_time_arrival time estimated time of arrival to the visit.
    current_eta date Estimated time of arrival of the visit.
    estimated_time_departure time estimated time of departure from the visit.
    tracking_id varchar(254) Tracking id.
    signature varchar(100) Address where the signature is stored
    checkin_time timestamp Arrival time at visit (by GPS driver).
    checkin_latitude numeric(9,6) Latitude of arrival at the visit.
    checkin_longitude numeric(9,6) Longitude of arrival at visit.
    checkout_longitude numeric(9,6) Longitude of checkout.
    checkout_observation uuid Id of the observation selected at checkout.
    checkout_latitude numeric(9,6) Latitude of checkout
    checkout_time timestamp Checkout date and time.
    geocode_alert varchar(22) Alert when georeferencing the address.
    postal_code varchar(15) Zip Code if the visit.
    programmed_date date Scheduled date of visit.
    visit_type json Type of the visit that is being made.
    fleet json Information of the fleet to which the visit belongs.
    has_alert boolean Deprecated.
    priority boolean Deprecated.

    Webhook Checkout

    SimpliRoute puede enviar información sobre la visita en el momento del cierre (checkout) mediante una llamada al método POST a un servicio web proporcionado por los clientes. La información disponible se describe en la siguiente tabla (no necesariamente en ese orden). El webhook espera obtener una respuesta con el código 200; de lo contrario, intentará nuevamente cada 30 segundos, con un máximo de 3 intentos.

    Example body

    Ejemplo:
    [{
       "id": 18843965,
       "load": 0.0,
       "load_2": 0.0,
       "load_3": 0.0,
       "window_start": "09:00:00",
       "window_end": "19:00:00",
       "window_start_2": "23:59:00",
       "window_end_2": "23:59:00",
       "reference": "",
       "planned_date": "2019-09-09",
       "order": 4,
       "checkout_comment": "Test",
       "duration": "0:20:00",
       "calculated_service_time": "0:00:00",
       "title": "INDUSTRIAS RIC\u00d3N",
       "contact_name": "Victor Gonzalez",
       "contact_email": "",
       "contact_phone": "978567812",
       "notes": "",
       "latitude": "-33.439046",
       "longitude": "-70.648752",
       "status": "completed",
       "address": "HUERFANOS 835 OF. 202, SANTIAGO, Santiago",
       "account": "[email protected]",
       "route": "2019-09-09 - Test",
       "status_changed": "2019-09-09 21:23:01.251595+00:00",
       "priority_level": 0,
       "created": "2019-08-29 22:33:44.015108+00:00",
       "modified": "2019-09-09 21:23:01.251582+00:00",
       "estimated_time_arrival": "10:12:00",
       "estimated_time_departure": "10:32:00",
       "tracking_id": "SR67118024023080",
       "signature": "visit-signatures/2019/09/09/ac6bf49a-35b.png",
       "checkin_time": null,
       "checkin_latitude": null,
       "checkin_longitude": null,
       "checkout_observation": null,
       "checkout_latitude": "-33.420471",
       "checkout_longitude": "-70.603384",
       "checkout_time": "2019-09-09 21:22:56.068000+00:00",
       "on_its_way": null,
       "geocode_alert": null,
       "has_alert": false,
       "priority": false
    }]
    
    
    Attributes Type Description
    id int Id of the visit in SimpliRoute
    load double Load 1
    load2 double Load 2
    load3 double Load 3
    window_start time Start time window 1. Format HH:MM:SS
    window_end time End time window 1. Format HH:MM:SS
    window_start_2 time Start time window 2. Format HH:MM:SS
    window_end_2 time End time window 2. Format HH:MM:SS.
    reference varchar(254) Visit reference
    planned_date date Delivery date. Format YYYY-MM-DD
    order int Planned delivery order
    checkout_comment string Comments upon delivery
    duration time Service time of the visit
    checkout_comment string Comments upon delivery
    duration time Service time
    calculated_service_time time Calculated service time
    title varchar(254) Title of the visit
    contact_name varchar(254) Contact name
    contact_email string Contact e mail
    contact_phone varchar(254) Contact phone number
    notes string Notes of the visit
    latitude double Latitude of the visit
    longitude double Longitude of the visit
    status varchar(100) Status of the visit: pending, completed, failed, partial
    address varchar(254 Address of the visit
    account varchar(254 Account name
    route varchar(254 Route name
    status_changed timestamp Date and time of the last status change
    priority_level integer Priority of the Visit. Ej 1 high priority, 2 second priority
    created timestamp Creation time of the visit.
    modified timestamp Time of the last modification of the visit.
    estimated_time_arrival time Estimated time of arrival for the visit
    estimated_time_departure time Estimated time of departure from the visit.
    tracking_id varchar(254) Id of tracking
    signature varchar(100) Address where the signature is stored.
    checkin_time timestamp Arrival time for the visit (by GPS driver).
    checkin_latitude double Latitude of arrival at the visit
    checkin_longitude doube Longitude of arrival at the visit
    checkout_observation uuid Id of the observation selected at checkout
    checkout_latitude double Checkout latitude
    checkout_longitude double Checkout longitude
    checkout_time timestamp Checkout date and time
    on_its_way timestamp Date and time when “On its way” was marked.
    geocode_alert Alert when georeferencing the address

    Webhook Checkout detallado

    SimpliRoute puede enviar información detallada sobre la visita en el momento del cierre (checkout) mediante una llamada al método POST a un servicio web proporcionado por los clientes. La información disponible se describe en la siguiente tabla (no necesariamente en ese orden). El webhook espera obtener una respuesta con el código 200; de lo contrario, intentará nuevamente cada 30 segundos, con un máximo de 3 intentos.

    Example

    {
        "load": 50.0,
        "window_start": "09:00:00",
        "reference": "96018725010003",
        "planned_date": "2020-09-02",
        "has_alert": false,
        "address": "SANTA MARIA 2670, PROVIDENCIA, Santiago",
        "load_3": 0.0,
        "load_2": 0.0,
        "programmed_date": null,
        "window_end": "19:00:00",
        "postal_code": null,
        "longitude": "-70.609643",
        "duration": "0:20:00",
        "status_changed": "2020-09-02 22:36:12.886508+00:00",
        "contact_name": "Paulina Mu\u00f1oz",
        "id": 44678051,
        "window_start_2": "23:59:00",
        "visit_type": null,
        "title": "CONFITERIA SAN RODRIGO",
        "pictures": [
        "https://simpli-visit-images-dev.s3.amazonaws.com/visit-pictures/2020/09/02/vi93grwrv.jpg"
        ],
        "checkout_longitude": "-122.406417",
        "priority": false,
        "checkout_observation": null,
        "latitude": "-33.416713",
        "contact_phone": "967603803",
        "status": "completed",
        "estimated_time_departure": "09:37:00",
        "route": {
            "comment": "Comentario",
            "vehicle": { 
                "id": 153969, 
                "name": "asd",
                "reference": "1234FF"
            },
            "plan": {
                "id": "9ab4c716-020d-44cd-a90c-4dc88cabf884",
                "name": "2-09-2020 18:34:49"
            },
            "timestamp": "2020-09-02 22:36:16.361577",
            "route_start": {
                "lat": "-33.415468",
                "start_time": "2020-09-02 22:35:48.034000+00:00",
                "estimated_time_start": "09:00:00",
                "lon": "-70.667961",
                "address": "Avenida Domingo Santa Mar\u00eda 12, Independencia, Chile"
            },
            "route_end": {
                "lat": "-33.415468",
                "lon": "-70.667961",
                "end_time": null,
                "estimated_time_end": "11:41:00",
                "address": "Avenida Domingo Santa Mar\u00eda 12, Independencia, Chile"
            },
            "planned_date": "2020-09-02",
            "visit_ids": [44678051, 44678052, 44678053, 44678054, 44678055],
            "driver": { "id": 75388, "name": "f" },
            "id": "e05b954e-754d-4774-b91b-000859eef55b"
        },
        "window_end_2": "23:59:00",
        "extra_field_values": {
            "numero_interior": null,
            "cantidad": null,
            "codigo_postal": null,
            "entre_calles_1": null,
            "edificio": null,
            "comentarios": null,
            "remision": null
        },
        "checkout_time": "2020-09-02 22:36:12.330000+00:00",
        "geocode_alert": null,
        "contact_email": "[email protected]",
        "current_eta": null,
        "calculated_service_time": "0:00:00",
        "account": { "id": 28387, "name": "11FabianUrrutia" },
        "priority_level": 0,
        "checkout_latitude": "37.785834",
        "observation": {},
        "created": "2020-09-02 22:35:01.950457+00:00",
        "on_its_way": null,
        "checkin_time": null,
        "modified": "2020-09-02 22:36:12.886496+00:00",
        "checkout_comment": "Comentario del conductor",
        "order": 1,
        "estimated_time_arrival": "09:17:00",
        "tracking_id": "SR99086101951738",
        "signature": "",
        "checkin_latitude": null,
        "fleet": null,
        "notes": "",
        "checkin_longitude": null,
        "plan": {
            "route_ids": ["e05b954e-754d-4774-b91b-000859eef55b"],
            "fleet_id": null,
            "name": "2-09-2020 18:34:49",
            "end_date": "2020-09-02",
            "reset_day": 1,
            "id": "9ab4c716-020d-44cd-a90c-4dc88cabf884",
            "account_id": 28387,
            "start_date": "2020-09-02"
        },
        "invoices": [{
            "id": "21bbbce0-d97f-4735-bd58-afa510c20398",
            "reference": "08224267",
            "type": "bill",
            "items": [{
                "id": 198907,
                "delivery_issue": null,
                "product": "5be6599e-652d-4dcd-b2a2-c6899d4d63ac",
                "reference": "121076",
                "status": "completed",
                "title": "Nordic Zero Ginger Ale PT3,0 x 6",
                "sku": "121076",
                "unit_price": 9335,
                "planned_units": 10,
                "delivered_units": 10,
                "type": "pack"
            },
            {
                "id": 198908,
                "delivery_issue": null,
                "product": null,
                "reference": "122615",
                "status": "completed",
                "title": "Vital C/G PT 1,6 x 6 term.",
                "sku": "122615",
                "unit_price": 13744,
                "planned_units": 10,
                "delivered_units": 10,
                "type": "pack"
            },
            {
                "id": 198909,
                "delivery_issue": {
                    "id": 115,
                    "title": "14 Duplicado/Mal digitado"
                },
                "product": null,
                "reference": "120111",
                "status": "failed",
                "title": "Coca Cola RP2,0cc x 8",
                "sku": "120111",
                "unit_price": 9916,
                "planned_units": 10,
                "delivered_units": 0,
                "type": "box"
            }],
            "label": null,
            "payment_method": "cash",
            "payment_method_details": null,
            "status": "partial"
        }]
    }
    
    
    
    Attributes Type Description
    id int Id of the visit in SimpliRoute
    load double Load 1
    load2 double Load 2
    load3 double Load 3
    window_start time Start time window 1. Format HH:MM:SS
    window_end time End time window 1. Format HH:MM:SS
    window_start_2 time Start time window 2. Format HH:MM:SS
    window_end_2 time End time window 2. Format HH:MM:SS.
    reference varchar(254) Visit reference
    planned_date date Delivery date. Format YYYY-MM-DD
    order int Planned delivery order
    checkout_comment string Comments upon delivery
    duration time Service time of the visit
    checkout_comment string Comments upon delivery
    duration time Service time
    calculated_service_time time Calculated service time
    title varchar(254) Title of the visit
    contact_name varchar(254) Contact name
    contact_email string Contact e mail
    contact_phone varchar(254) Contact phone number
    notes string Notes of the visit
    latitude double Latitude of the visit
    longitude double Longitude of the visit
    status varchar(100) Status of the visit: pending, completed, failed, partial
    address varchar(254 Address of the visit
    account varchar(254) Account name
    account.id integer Id of the account
    account.name varchar(254) Account namme
    route varchar(254) Route name
    route.id varchar(254) Id of the route
    route.comment varchar(254) Route name
    route.driver varchar(254) Route name
    route.driver.id varchar(254) Route name
    route.driver.name varchar(254) Route name
    route.plan varchar(254) Route name
    route.plan.id varchar(254) Route name
    route.plan.name varchar(254) Route name
    route.route_start varchar(254) Route name
    route.route_start.address varchar(254) Route name
    route.route_start.estimated_time_start varchar(254) Route name
    route.route_start.lat varchar(254) Route name
    route.route_start.lon varchar(254) Route name
    route.route_start.start_time varchar(254) Route name
    route.route_end varchar(254) Route name
    route.route_end.address varchar(254) Route name
    route.route_end.estimated_time_start varchar(254) Estimated completion time
    route.route_end.lat double Latitude of the end of the route.
    route.route_end.lon double Longitude of the end of the route
    route.route_end.end_time time Real moment of the end of the route
    route.timestamp date Current time of information request.
    route.vehicle json Contains route vehicle information.
    route.vehicle.id integer Id of the vehicle of the route.
    route.vehicle.name varchar(254) Route vehicle name.
    route.visit_ids array Array with a list of visits corresponding to the assigned checkout route
    route.planned_date date Date of the route planning.
    status_changed timestamp Date and time of the last status change
    priority_level integer Priority of the Visit. Ej 1 high priority, 2 second priority
    created timestamp Creation time of the visit.
    modified timestamp Time of the last modification of the visit.
    estimated_time_arrival time Estimated time of arrival for the visit
    estimated_time_departure time Estimated time of departure from the visit.
    tracking_id varchar(254) Id of tracking
    signature varchar(100) Address where the signature is stored.
    checkin_time timestamp Arrival time for the visit (by GPS driver).
    checkin_latitude double Latitude of arrival at the visit
    checkin_longitude doube Longitude of arrival at the visit
    checkout_observation uuid Id of the observation selected at checkout
    checkout_latitude double Checkout latitude
    checkout_longitude double Checkout longitude
    checkout_time timestamp Checkout date and time
    on_its_way timestamp Date and time when “On its way” was marked.
    geocode_alert varchar (22) Alert when georeferencing the address
    pictures array Array with urls of the photos added to the visit.
    postal_code varchar (15) Postal code of the visit.
    programmed_date date Scheduled date of visit.
    visit_type json Type of the visit that is being made.
    extra_fields_values array Extra values ​​of the visit. Format: [{“key”:”value”}]
    current_eta date Estimated time of arrival to the visit.
    observation json Contains observation information added to the visit
    observation.id integer Id of the Observation
    observation.labe varchar (254) Observation visit label
    fleet json Information of the fleet to which the visit belongs.
    plan json Contains plan information associated with the visit
    plan.id uuid id of the plan associated with the visit.
    plan.route_ids array Array with id of the plan routes.
    plan.fleet_id integer id of the fleet which the plan belongs
    plan.name varchar (254) Name of the plan
    plan.end_date date Plan termination date.
    plan.reset_day integer Plan reset time.
    plan.account_id id Id of the account assigned to the plan
    plan.start_date date Plan start date
    invoices list List of invoices of the visit. See Invoice for its fields.

    Optimización

    Optimization Endpoint

    
    http://optimizer.simpliroute.com/vrp/optimize/sync
    
    

    Debido a nuestra amplia experiencia en la optimización de rutas, garantizamos que esta es la mejor manera de crear las rutas de entrega de tu empresa. Creemos que los problemas cotidianos merecen soluciones simples, por eso ahora tienes a tu disposición la API de nuestro algoritmo. Resuelve tus problemas de logística de entrega de la forma más rápida y sencilla posible.

    SimpliRoute tiene en cuenta las siguientes restricciones:

    • Capacidades de tus vehículos.
    • Puntos de inicio y fin diferentes para tus vehículos.
    • Turnos de los conductores.
    • Ventanas de tiempo de tus clientes.
    • Y mucho más.

    En las próximas secciones, profundizaremos en nuestra API, los objetos que contiene y muchos ejemplos prácticos para que empieces a desarrollar tu aplicación usando nuestra API. Si tienes preguntas, puedes enviarnos un correo a [email protected]

    Instancia de Optimización

    Input json

    [{
        "vehicles": [
            {
                "ident": "Vehicle 1",
                "location_start": {
                    "ident": "warehouse A",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                },
                "location_end": {
                    "ident": "warehouse C",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                },
                "capacity": 3500,
                "capacity_2": 3500,
                "capacity_3": 3500,
                "shift_start": "9:00",
                "shift_end": "22:00",
                "skills": []
            },
            {
                "ident": "Vehicle 2",
                "location_start": {
                    "ident": "warehouse B",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                },
                "location_end": {
                    "ident": "warehouse C",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                },
                "capacity": 3500,
                "capacity_2": 3500,
                "capacity_3": 3500,
                "shift_start": "9:00",
                "shift_end": "22:00",
                "skills": []
            }
        ],
        "nodes": [
            {
                "ident": "El Salto 4875",
                "lat": -33.3887,
                "lon": -70.62304,
                "window_start": "09:00",
                "window_end": "17:00",
                "window_start_2": "19:00",
                "window_end_2": "22:00",
                "duration": 15
            },
            {
                "ident": "Avenida Del Valle 7",
                "lat": -33.39124,
                "lon": -70.61387,
                "load": 2530,
                "window_start": "9:00",
                "window_end": "11:00",
                "window_start_2": "19:00",
                "window_end_2": "22:00",
                "duration": 15
            },
            {
                "ident": "Larrain 5862",
                "lat": -33.45066,
                "lon": -70.54915,
                "load": 77,
                "window_start": "09:00",
                "window_end": "17:00",
                "window_start_2": "19:00",
                "window_end_2": "22:00",
                "priority_level": 1,
    
                "duration": 10
            }
        ],
        "balance": true,
        "all_vehicles": false,
        "join": true,
        "open_ended": false,
        "single_tour": true,
        "fmv": 1.0
    }]
    

    Nuestra API recibe un objeto JSON como entrada. El JSON de Optimización puede dividirse en las siguientes secciones:

    • Vehículos: Arreglo de vehículos con su información, que será optimizada con nuestra API.
    • Nodos: Arreglo de entregas con sus restricciones, que serán enrutadas con nuestra API.
    • Opciones de optimización: Diferentes criterios de optimización para ajustar la optimización a tus necesidades.

    En las siguientes secciones, hablaremos con más detalle sobre cada uno de estos objetos. También mostraremos algunos ejemplos de cómo hacer una solicitud a nuestra API en diferentes casos de uso, para facilitarte el comienzo con SimpliRoute.

    Vehículos

    Vehicle's object example:

    [{
        "ident": "Vehicle 1",
        "location_start": {
            "ident": "warehouse B",
            "lat": -33.4233926,
            "lon": -70.6104996
        },
        "location_end": {
            "ident": "warehouse C",
            "lat": -33.345523,
            "lon": -70.456992
        },
        "capacity": 3500,
        "capacity_2": 3500,
        "capacity_3": 3500,
        "shift_start": "09:00",
        "shift_end": "18:00",
        "refill": 30,     
        "skills": [
            "47076"
            "47054"
        ],
        "zones": [
            14730
        ],
        "max_tour_duration": 40,
        "cost": 100,
        "min_load": 0,
        "min_load_2": 0,
        "min_load_3": 0,
        "max_visit": 35,
        "max_number_of_routes": 2
    }]
    

    Al usar nuestra API, el primer objeto que debes comprender es el objeto vehículo. En nuestra API, un vehículo es cualquier dispositivo móvil en tu ciudad. Si trabajas con flotas, servicios en terreno o personal de ventas, todos ellos deben ser creados como un "vehículo" en nuestra API. Cada uno de los atributos se describe a continuación:

    Attributes Mandatory Type Description
    ident Mandatory String Unique identifier for the object.
    location_start Mandatory Object Location of the vehicle when the optimization was called
    location_end Optional Object Location where the vehicle should end its route
    capacity Optional Float Vehicle's capacity load
    capacity_2 Optional Float Vehicle's second capacity load
    capacity_3 Optional Float Vehicle's third capacity load
    shift_start Optional String String "HH:mm" (military time). When the vehicle's shift starts.
    shift_end Optional String String "HH:mm" (military time). When the vehicle's shift ends.
    skills Optional String array Skills that the vehicles supports. Deliveries must have skills in order to be used.
    refill Optional Integer Minutes that takes to refill the vehicle when it returns to the depot before starts a new route.
    zones Optional Integer array Identifiers of the zones to which the vehicle belongs. A vehicle can belong to more than one zone.
    max_tour_duration Optional Integer Maximum minutes that the vehicle is allowed to make all its routes.
    min_load Optional Integer Percentage of minimum load associated with capacity attribute that the vehicle must have to go out on the road.
    min_load_2 Optional Integer Percentage of minimum load associated with capacity_2 attribute that the vehicle must have to go out on the road.
    min_load_3 Optional Integer Percentage of minimum load associated with capacity_3 attribute that the vehicle must have to go out on the road.
    max_visit Optional Integer Maximum number of visits that the routes carried out by the vehicle can have.
    max_number_of_routes Optional Integer Maximum number of routes that each vehicle can have. If the value is 0 or null, the maximum is infinity.
    open_start Optional Boolean When true, this feature allows vehicles to begin their routes from locations other than the depot. It's false by default.
    open_end Optional Boolean When true, this feature allows vehicles to end their routes in locations other than the depot. It's false by default. If open_ended is true, it overwrites this parameter.

    Entrega

    Delivery's object example:

    [{
        "nodes": [
            {
                "ident": "Delivery 1",
                "group_id": "Delivery 1",
                "lat": -33.3887,
                "lon": -70.62304
            },
            {
                "ident": "Delivery 2",
                "group_id": "Delivery 1",
                "address": "Ricardo Flores Magon # 28. Nave 12. Parque industrial San Jeronimo Caleras. San Jeronimo Caleras, Pue.",
                "lat": -33.39124,
                "lon": -70.61387,
                "load": 253.1,
                "load_2": 2.0,
                "load_2": 3.2,
                "window_start": "09:00",
                "window_end": "11:00",
                "window_start_2": "13:00",
                "window_end_2": "15:00",
                "duration": 15,
                "skills_required": [
                    30744,
                    47593
                ],
                "skills_optional": [
                    30567
                ],
                "priority_level": 2,
                "zones": [
                    14730
                ],
                "open_start": true,
                "open_end": false
            }
        ]
    }]
    

    Una entrega es cualquier tarea que tu vehículo deba realizar en la calle: órdenes de entrega, oportunidades de venta, órdenes de servicio en terreno, etc.

    Attributes Mandatory Type Description
    ident Mandatory String Unique identifier for the object.
    lat Mandatory Float Latitude of the delivery's location.
    lon Mandatory Float Longitude of the delivery's location.
    address Optional String Address of the delivery. If there are lat and lon attributes, it will privilege those fields over this
    group_id Optional String Identifier of the delivery to which this delivery will be linked when using join_v2 (see optimization options).
    load Optional Float Load of this delivery. Must be on same units as vehicle's load.
    load_2 Optional Float Secondary load of this delivery. Must be on same units as vehicle's load 2.
    load_3 Optional Float Third load of this delivery. Must be on same units as vehicle's load 3.
    window_start Optional String String "HH:mm" (military time). Minimum time this delivery can be attended.
    window_end Optional String String "HH:mm" (military time). Maximum time this delivery can be attended.
    window_start_2 Optional String String "HH:mm" (military time). Secondary minimum time this delivery can be attended. (Ex: I can visit this place from 10:00 to 12:00 and from 15:00 to 19:00)
    window_end_2 Optional String String "HH:mm" (military time). Secondary maximum time this delivery can be attended.
    duration Optional Integer Minutes that the vehicle will stay on the delivery.
    skills_required Optional Integer array Skills this delivery needs to be fulfilled. Only the vehicles who have all of these skills will attend the delivery.
    skills_optional Optional Integer array Skills this delivery needs to be fulfilled. Only the vehicles who have at least one of these skills will attend the delivery.
    priority_level Optional Integer Used to indicate this delivery is more important than others. Possible values are 1: First of the day, 2: Last of its route, 3: High Priority, 4: Medium Priority, 5: Low Priority.
    zones Optional Integer array Identifier of the zone to which this delivery belongs. Only vehicles that have this area will attend the delivery.

    Opciones de optimización

    SimpliRoute ofrece algunas características adicionales que te permiten configurar la optimización de la mejor forma posible para adaptarse a las necesidades de tu empresa.

    Attributes Mandatory Type Description
    country Mandatory String ISO code referring to the country where the delivery locations are located.
    balance Optional Boolean Default: False. If true, there will be an enforced balance between all the vehicles, in time and number of locations for the algorithm procedure
    fmv Optional Float Default: 2.0, Speed traffic factor. It could be 1.0 = Low Traffic, 1.5 = Medium Traffic, 2.0 = High Traffic or 3.0 = Intense Traffic.
    all_vehicles Optional Boolean Default: False. If true, the algorithm will use all the selected vehicles. If false, will minimize the number of vehicles.
    open_ended Optional Boolean Default: False. If true, the route will be created assuming the vehicle won't return the depot at the end of the day.
    single_tour Optional Boolean Default: False. If true, all vehicles will have only one route.
    join_v2 Optional Boolean Default: False. If true, the algorithm performs a union of visits with the same address, respecting the capacity of the vehicles, and seeking to minimize the number of vehicles that have similar visits.
    beauty Optional Boolean Default: False. If true, the algorithm groups visits into clusters and creates routes within these clusters.
    fmb Optional Integer Default: 5. Clustering factor. It could be 1.0 = Zero Clustering, 2.0 = Low Clustering, 3.0 = Medium Clustering, 4.0 = High Clustering or 5.0 = Intense Clustering
    use_euclidean_distance Optional Boolean Default: False. If true, it is considered as the distance between two locations, the direct line that joins both nodes.
    autoZone Optional Boolean Default: False. If true, the algorithm assigns the vehicles that serve each specified zone in the visits.
    intensive_intra Optional Boolean Default: False. If true, the algorithm performs a more intensive search on the solution space. Response time may increase.
    open_routes_logic Optional Boolean Default: False. If true, the route will be created assuming the vehicle won't return the depot at the end of the day, BUT it does.
    vehicle_capacities_increment Optional Integer Default: 0. Percentage increase in load capacity of all vehicles.
    vehicle_journey_extention Optional Integer Default: 0. Percentage of increase in the time window of all vehicles.
    enable_soft_window Optional Boolean Default: False. If true, it allows not respecting the deliveries time windows, but seeking to minimize the total delay time.
    isReorder Optional Boolean Default: False. When enabled, this feature will try to insert all nodes, considering only the first time windows. If this is not achievable, it will try again ignoring the time window constraints.
    radial_routing Optional Integer Default: 0. When its value is 1, each route will start close to the depot and end far from the depot. When its value is -1, each route will start far from the depot and end close to the depot. When its value is 0, the option is disabled. Other values are not accepted.

    Example - Basic Optimization JSON input

    {
        "vehicles": [
            {
                "ident": "Vehicle 1",
                "location_start": {
                    "ident": "depot_1_start",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                }
            }
        ],
        "nodes": [
            {
                "ident": "1",
                "lat": -33.436135,
                "lon": -70.6509688
            },
            {
                "ident": "2",
                "lat": -33.4334123,
                "lon": -70.653234
            },
            {
                "ident": "3",
                "lat": -33.333413,
                "lon": -70.5534688
            }
        ]
    }
    

    JSON output

    {
        "vehicles": [
            {
                "ident": "Vehicle 1",
                "tours": [
                    {
                        "nodes": [
                            {
                                "arrival": "00:00:00",
                                "ident": "depot_1_start",
                                "lon": -70.6104996,
                                "departure": "00:00:00",
                                "lat": -33.4233926,
                                "order": 0,
                                "priority": null,
                                "load": 0,
                                "load_2": 0,
                                "load_3": 0
                            },
                            {
                                "load": 0,
                                "arrival": "00:17:00",
                                "ident": "3",
                                "lon": -70.5534688,
                                "departure": "00:17:00",
                                "lat": -33.333413,
                                "order": 1,
                                "priority": 0,
                                "load": 0,
                                "load_2": 0,
                                "load_3": 0
                            },
                            {
                                "load": 0,
                                "arrival": "00:39:00",
                                "ident": "2",
                                "lon": -70.653234,
                                "departure": "00:39:00",
                                "lat": -33.4334123,
                                "order": 2,
                                "priority": 0,
                                "load": 0,
                                "load_2": 0,
                                "load_3": 0
                            },
                            {
                                "load": 0,
                                "arrival": "00:40:00",
                                "ident": "1",
                                "lon": -70.6509688,
                                "departure": "00:40:00",
                                "lat": -33.436135,
                                "order": 3,
                                "priority": 0,
                                "load": 0,
                                "load_2": 0,
                                "load_3": 0
                            },
                            {
                                "arrival": "01:42:00",
                                "ident": "depot_1_start",
                                "lon": -70.6104996,
                                "departure": "01:42:00",
                                "lat": -33.4233926,
                                "order": 4,
                                "priority": null,
                                "load": 0,
                                "load_2": 0,
                                "load_3": 0
                            }
                        ]
                    }
                ]
            }
        ],
        "num_vehicles_used": 1,
        "filteredClientsNodes": [],
        "unattendedClientsNodes": []
    }
    

    El ejemplo más básico de optimización de rutas con nuestra API es cuando hay un solo depósito desde el cual todos tus vehículos comenzarán y terminarán el día.

    Además, en cada ubicación que tus vehículos necesitan visitar no hay restricciones relacionadas con carga o ventanas de tiempo. Esto ocurre normalmente en casos como:

    • Entrega de cartas y documentos
    • Reparto de comida con vehículos donde las restricciones de carga no son un problema

    Puedes ver un ejemplo de entrada y salida en formato JSON en el lado derecho.

    En este ejemplo, hay dos entidades relevantes: vehículos y nodos. La primera debe contener:

    "Ident" es obligatorio y corresponde al ID del vehículo. El objeto "location_start" es la ubicación desde donde el vehículo comenzará su operación diaria. Dado que en este ejemplo no definimos un "location_end", nuestro algoritmo asumirá que el vehículo terminará su día en "location_start".

    En el caso de los nodos, debes definir lo siguiente:

    Usamos "ident" como un ID para la visita, y "lat" y "lon" para especificar la latitud y longitud del nodo. Dado que en este ejemplo no hay ventanas de tiempo ni cargas, no es necesario especificar nada más en cada visita.

    Ventanas de tiempo del vehículo (Time Windows)

    Si no se especifican ventanas de tiempo para el vehículo, nuestro algoritmo asumirá que el vehículo trabajará entre las 00:00 y las 23:59 horas de ese día. Si deseas especificar una ventana de tiempo para el vehículo, debes agregar los valores "shift_start" y "shift_end". Un ejemplo de esto:

    Tiempo de servicio (Service Times)

    Si no se especifica el tiempo de servicio, nuestro algoritmo asumirá que el tiempo de servicio en esa ubicación es de 0 (cero) minutos. Si deseas agregar un valor, puedes especificarlo en el objeto nodo de la siguiente manera:

    "Duration" debe ser un entero en minutos. Representa cuánto tiempo permanecerá el vehículo en esa ubicación.

    Respuesta de la optimización

    La respuesta de la optimización, que es la salida de la optimización, puede dividirse en las siguientes secciones:

    • Vehículos: Arreglo de vehículos provenientes del JSON de entrada.
    • Tours: Arreglo de recorridos. Un recorrido es la lista de todas las rutas que el vehículo toma desde el inicio de su jornada hasta el final.
    • Nodos: Arreglo de entregas que se incluyeron en alguna ruta.
    • num_vehicles_used: Número de vehículos utilizados para crear las rutas.
    • filteredClientsNodes: Arreglo de identificadores de entregas eliminadas del JSON de entrada antes de optimizar las rutas, debido a la imposibilidad de atenderlas por las restricciones del problema.
    • unattendedClientsNodes: Arreglo de identificadores de entregas, no eliminadas, que no pudieron incluirse en alguna ruta durante la optimización del problema.

    Algunos de los atributos que los nodos tienen en la respuesta de la optimización son los mismos que se enviaron en la solicitud, excepto por estos:

    Attributes Type Description
    arrival String String "HH:mm:ss" (military time). Vehicle arrival time at delivery.
    departure String String "HH:mm:ss" (military time). Vehicle departure time from delivery.
    order Integer Order in which delivery is visited.

    Example - Multiple depots

    De forma similar al caso anterior, puedes definir para cada vehículo una ubicación diferente para iniciar y finalizar el día. De esta manera, puedes simular operaciones más complejas en las que un vehículo debe comenzar el día en una ciudad y terminarlo en otro lugar. Un ejemplo en JSON se encuentra a la derecha.

    JSON input:

    {
        "vehicles": [
            {
                "ident": "Vehicle 1 different start and end",
                "shift_start": "09:00",
                "shift_end": "19:00",
                "location_start": {
                    "ident": "depot_1_start",
                    "lat": -33.4233926,
                    "lon": -70.6104996
                },
                "location_end": {
                    "ident": "depot_2_end",
                    "lat": -33.436662,
                    "lon": -70.577584
                }
            }
        ],
        "nodes": [
            {
                "ident": "1",
                "lat": -33.436135,
                "lon": -70.6509688
            },
            {
                "ident": "2",
                "lat": -33.4334135,
                "lon": -70.6534688,
                "duration": 5
            },
            {
                "ident": "3",
                "lat": -33.333413,
                "lon": -70.5534688,
                "duration": 5
            }
        ]
    }
    

    JSON output:

    {
        {
        "vehicles": [{
            "ident": "Vehicle 1 different start and end",
            "tours": [{
                "nodes": [{
                    "arrival": "09:00",
                    "ident": "depot_1_start",
                    "lon": -70.6104996,
                    "departure": "09:00",
                    "lat": -33.4233926,
                    "order": 0
                }, {
                    "load": 0,
                    "arrival": "09:17",
                    "ident": "2",
                    "lon": -70.6534688,
                    "departure": "09:22",
                    "lat": -33.4334135,
                    "order": 1
                }, {
                    "load": 0,
                    "arrival": "10:05",
                    "ident": "1",
                    "lon": -70.6509688,
                    "departure": "10:35",
                    "lat": -33.436135,
                    "order": 2
                }, {
                    "load": 0,
                    "arrival": "10:49",
                    "ident": "3",
                    "lon": -70.5534688,
                    "departure": "11:19",
                    "lat": -33.333413,
                    "order": 3
                },{
                    "arrival": "11:56",
                    "ident": "depot_2_end",
                    "lon": -70.577584,
                    "departure": "11:56",
                    "lat": -33.436662,
                    "order": 4
                }]
            }]
        }],
        "num_vehicles_used": 1
    }
    
    

    Optimización de Backhaul (Rutas con recogidas y entregas)

    Example of Nodes Object with Loads and Pickloads

    {
        "nodes": [
            {
                "ident": "Regular Delivery",
                "lat": -33.3887,
                "lon": -70.62304,
                "load": 10.1,
                "load_2": 2.0,
                "load_3": 3.2
            },
            {
                "ident": "Regular Pick up",
                "lat": -33.39124,
                "lon": -70.61387,
                "pickload": 5.1,
                "pickload_2": 1.0,
                "pickload_3": 1.2
            },
            {
                "ident": "Pick up and Delivery",
                "lat": -33.4887,
                "lon": -70.92304
                "load": 7.2,
                "load_2": 1.0,
                "load_2": 2.2,
                "pickload": 4.1,
                "pickload_2": 3.0,
                "pickload_3": 3.2
            }
        ]
    }
    

    Nuestro algoritmo se amplía para admitir rutas en las que tus vehículos deben entregar productos a tus clientes y, además, recoger productos de tus clientes que deben regresar a tu depósito o almacén. En este escenario, en cada cliente puedes realizar entregas, recogidas, o ambas (recoger y entregar productos).

    Este tipo de enrutamiento se conoce comúnmente como Optimización de Rutas Backhaul, que no debe confundirse con la Optimización de Recogida y Entrega, que es un problema ligeramente diferente. En este tipo de optimización de rutas, se debe verificar la capacidad del vehículo en cada parada, para no sobrecargarlo a la mitad de la ruta.

    Para utilizar nuestra Optimización de Backhaul, debes emplear el mismo endpoint de optimización de rutas que se usa para optimizaciones regulares, pero agregando algunos parámetros opcionales al objeto de nodos para cada visita.

    Estos son los nuevos parámetros que puedes agregar y cómo se relacionan con los parámetros de la optimización de rutas regular:

    Attributes Mandatory Type Description
    load Optional Float Load that must be delivered on this client. Must be on the same unit as vehicle's load.
    load_2 Optional Float Secondary Load that must be delivered on this client. Must be on the same unit as vehicle's secondary load.
    load_3 Optional Float Third Load that must be delivered on this client. Must be on the same unit as vehicle's third load.
    pickload Optional Float Load that must be picked up on this client. Must be on the same unit as vehicle's load and this visit's load.
    pickload_2 Optional Float Secondary Load that must be picked up on this client. Must be on the same unit as vehicle's secondary load and this visit's load_2.
    pickload_3 Optional Float Third Load that must be picked up on this client. Must be on the same unit as vehicle's third load and this visit's load_3.

    Stop Routing

    El objeto visit_joiner se agrega a la solicitud de optimización y puede usarse con los endpoints vrp o big-vrp.

    Example Request for "Merging Stops by Distance"

    {
        "visit_joiner": {
            "enable_visit_join": true,
            "maximum_distance": 0.5,
            "match_skills": true,
            "match_zones": true,
            "match_time_windows": true
        }
    }
    
    

    La función Stop Routing permite agrupar o fusionar visitas en una única parada basándose en criterios específicos de proximidad geográfica y otros parámetros configurables por el cliente. El objetivo de esta función es optimizar las rutas reduciendo el número de visitas individuales cuando comparten condiciones similares de ubicación y restricciones.

    Parametros

    Parameter Type Description
    enable_visit_join Boolean Enables the stop routing feature when set to true.
    maximum_distance Number Maximum distance (in kilometers) for grouping visits into a stop. Set to 0 to enable merging by exact location.
    match_skills Boolean Groups visits with the same required skills when active.
    match_zones Boolean Groups visits within the same zone when active.
    match_time_windows Boolean Groups visits with the same time window when active.

    Agrupar Visitas por Distancia

    El servicio procesa solicitudes para agrupar visitas en una sola parada cuando cumplen con los siguientes criterios:

    • Están dentro de una distancia máxima configurada.
    • Comparten las mismas habilidades requeridas.
    • Comparten la misma ventana de tiempo.

    Agrupar Visitas Similares por Dirección (Distancia 0)

    Example Request for "Merging Similar Stops" (Distance 0) json { "visit_joiner": { "enable_visit_join": true, "maximum_distance": 0, "match_skills": true, "match_zones": true, "match_time_windows": true } } Esta opción agrupa visitas ubicadas exactamente en el mismo lugar que comparten:

    • La misma latitud y longitud.
    • Las mismas habilidades requeridas.
    • La misma ventana de tiempo.

    Salida para ambos modos

    • Carga combinada: Se suman las cargas de las visitas individuales.
    • Tiempo de servicio: Se asigna el tiempo de servicio más largo entre las visitas fusionadas.

    Condiciones especiales y validaciones

    • Compatibilidad con similars_by_priority: Cuando está habilitado, dos visitas con la misma prioridad no se fusionarán.
    • Verificación de capacidad del vehículo: Si la carga combinada de las visitas fusionadas supera la capacidad del vehículo, las visitas no se agruparán.
    • Ventana de tiempo principal: Para visitas con la misma latitud y longitud pero diferentes ventanas de tiempo, se utiliza la ventana de tiempo de la visita principal (parada).

    Consideraciones de uso de la API

    • "Fusionar paradas similares" no valida el campo address; solo se verifican lat y lon.
    • Esta funcionalidad es exclusivamente del backend; no actives join:true en el frontend.

    Respuesta de la API

    Para verificar que una visita se ha agrupado en la respuesta de optimización, puedes comprobar las visitas atendidas en el parámetro order:number. Si tienen el mismo orden, indica que estas visitas se han agrupado en una sola parada.

    Recogida y Entrega

    Ejemplo del objeto Job: un nodo de recogida.

    {
      "jobs": [
        {
          "pickNodes": [
            {
              "ident": "OnlyPickUp_1",
              "lat": -22.931935311303512,
              "lon": -43.39394580787891,
              "duration": 11,
              "load": 2,
              "load_2": 1,
              "load_3": 1,
              "window_start": "09:00",
              "window_end": "23:59",
              "skills_required": [],
              "skills_optional": [],
              "priority_level": 0
        }],
        "deliveryNodes": [
          ]}
      ]
    }
    

    Ejemplo del objeto Job: un nodo de entrega.

    {
      "jobs": [
        {
          "pickNodes": [
          ],
          "deliveryNodes": [
            {
              "ident": "OnlyDelivery_1",
              "lat": -22.928792360672404,
              "lon": -43.389912163599,
              "duration": 12,
              "load": 2,
              "load_2": 1,
              "load_3": 1,
              "window_start": "09:00",
              "window_end": "23:59",
              "skills_required": [],
              "skills_optional": [],
              "priority_level": 0
        }]}
      ]
    }
    

    Ejemplo del objeto Job: un nodo de recogida y un nodo de entrega.

    {
      "jobs": [
        {
          "pickNodes": [
            {
              "ident": "PickUp_1",
              "lat": -22.92770862905761,
              "lon": -43.37154320004268,
              "duration": 29,
              "load": 2,
              "load_2": 1,
              "load_3": 1,
              "window_start": "09:00",
              "window_end": "23:59",
              "skills_required": [],
              "skills_optional": [],
              "priority_level": 0
        }],
          "deliveryNodes": [
            {
              "ident": "Delivery_1",
              "group":[],
              "lat": -22.930334385243487,
              "lon": -43.390728465304214,
              "duration": 3,
              "load": 2,
              "load2": 1,
              "load3": 1,
              "window_start": "09:00",
              "window_end": "23:59",
              "skills_required": [],
              "skills_optional": [],
              "priority_level": 0
        }]}
      ]
    }
    

    Una de las variantes que admite el algoritmo de enrutamiento es el Problema de Recogida y Entrega (Pick-up and Delivery Problem). En este problema, los nodos se dividen en dos categorías que persiguen objetivos diferentes: recogidas y entregas. Mientras que una recogida consiste en recolectar una carga desde una ubicación fija, una entrega implica llevar esa carga a su destino.

    La unidad fundamental de este problema se conoce como un trabajo (job), que consiste en un grupo de nodos. Cada trabajo pertenece a uno de los siguientes tres casos:

    • Un nodo de recogida: En este caso, después de visitar el nodo, el conductor recogerá y transportará su carga en el vehículo hasta el siguiente depósito.
    • Un nodo de entrega: En este caso, cuando el conductor llegue al nodo, entregará la carga que proviene originalmente de un depósito.
    • Un nodo de recogida y un nodo de entrega: En este escenario, el conductor debe pasar primero por el nodo de recogida para recoger la carga, que posteriormente debe llevarse a un nodo de entrega específico.

    En cuanto a la restricción de capacidad, cabe señalar que la carga total de un vehículo cambia dinámicamente dependiendo de si recoge o entrega carga durante la ruta.

    La entrada de optimización es un objeto JSON con una estructura similar al caso de optimización regular. Está compuesto por opciones de optimización, una lista de vehículos y una lista de trabajos (jobs, en lugar de nodos). Cada trabajo, a su vez, está compuesto por una lista de nodos de recogida y una lista de nodos de entrega, para cubrir los tres casos de trabajo explicados anteriormente. Para utilizar este modo, la solicitud debe enviarse al siguiente endpoint: https://optimizer.simpliroute.com/pd/optimize/sync/.

    Un pickNode o deliveryNode es muy similar al objeto nodo (entrega) definido previamente y es compatible con los siguientes atributos:

    Attributes Mandatory Type Description
    ident Mandatory String Unique identifier for the object.
    lat Mandatory Float Latitude of the pick or delivery's location.
    lon Mandatory Float Longitude of the pick or delivery's location.
    address Optional String Address of the pick or delivery. If there are lat and lon attributes, it will prioritize those fields over this.
    load Optional Float Load of this pick or delivery. Must be on same units as vehicle's load.
    load_2 Optional Float Secondary load of this pick or delivery. Must be on same units as vehicle's load 2.
    load_3 Optional Float Third load of this pick or delivery. Must be on same units as vehicle's load 3.
    window_start Optional String String "HH:mm" (military time). Minimum time this pick or delivery can be visited.
    window_end Optional String String "HH:mm" (military time). Maximum time this pick delivery can be visited.
    window_start_2 Optional String String "HH:mm" (military time). Secondary minimum time this pick or delivery can be attended. (Ex: I can visit this place from 10:00 to 12:00 and from 15:00 to 19:00)
    window_end_2 Optional String String "HH:mm" (military time). Secondary maximum time this pick or delivery can be attended.
    duration Optional Integer Minutes that the vehicle will stay on the pick or delivery.
    skills_required Optional Integer array Skills this pick or delivery needs to be fulfilled. Only the vehicles who have all of these skills will visit it.
    skills_optional Optional Integer array Skills this pick or delivery needs to be fulfilled. Only the vehicles who have at least one of these skills will visit it.
    priority_level Optional Integer Used to indicate this pick or delivery is more important than others. Possible values are 1: First of the day, 2: Last of its route, 3: High Priority, 4: Medium Priority, 5: Low Priority.

    Tiempo de Descanso (Routes with a break time)

    Example of Vehicles Object with rest time

    {
           "vehicles": [
            {
                "ident": "159331",
                "location_start": {
                    "ident": "vehicle-start-159331",
                    "lat": -33.405976,
                    "lon": -70.652035
                },
                "location_end": {
                    "ident": "vehicle-end-159331",
                    "lat": -33.405976,
                    "lon": -70.652035
                },
                "capacity": 10.0,
                "capacity_2": 1.0,
                "capacity_3": 1.0,
                "shift_start": "11:00",
                "shift_end": "23:00",
                "skills": [
                    "32073",
                    "32074"
                ],
                "refill": 0,
                "rest_time_start": "12:00",
                "rest_time_end": "14:00",
                "rest_time_duration": 60
            },
            {
                "ident": "159351",
                "location_start": {
                    "ident": "vehicle-start-159351",
                    "lat": -33.594771,
                    "lon": -70.520194
                },
                "location_end": {
                    "ident": "vehicle-end-159351",
                    "lat": -33.594771,
                    "lon": -70.520194
                },
                "capacity": 10.0,
                "capacity_2": 1.0,
                "capacity_3": 1.0,
                "shift_start": "08:00",
                "shift_end": "14:00",
                "skills": [
                    "32076"
                ],
                "refill": 0,
                "rest_time_start": "12:00",
                "rest_time_end": "14:00",
                "rest_time_duration": 60
            },
            {
                "ident": "159349",
                "location_start": {
                    "ident": "vehicle-start-159349",
                    "lat": -33.486415,
                    "lon": -70.609595
                },
                "location_end": {
                    "ident": "vehicle-end-159349",
                    "lat": -33.486415,
                    "lon": -70.609595
                },
                "capacity": 10.0,
                "capacity_2": 1.0,
                "capacity_3": 1.0,
                "shift_start": "08:00",
                "shift_end": "14:00",
                "skills": [
                    "32073"
                ],
                "refill": 0,
                "rest_time_start": "12:00",
                "rest_time_end": "14:00",
                "rest_time_duration": 60
            }
        ],
        "enable_rest_time": true
    }
    

    Nuestro algoritmo puede considerar un tiempo de descanso definido para cada vehículo (conductor) con el fin de incluir una pausa en el recorrido que debe realizarse durante el día. Esta funcionalidad considera únicamente una pausa en la ruta de un vehículo, en un horario definido en la solicitud.

    Para usar el Tiempo de Descanso, debes emplear el mismo endpoint de optimización de rutas que se utiliza para optimizaciones regulares, pero añadiendo algunos parámetros opcionales en el objeto vehicles para cada vehículo. Además, debes habilitar un parámetro adicional que permita utilizar esta funcionalidad. Solo se considerará un tiempo de descanso para aquellos vehículos que tengan los parámetros adicionales configurados.

    Estos son los nuevos parámetros que puedes agregar:

    Attributes Mandatory Type Description
    rest_time_start Mandatory String String "HH:mm" (military time). Minimum time in which this vehicle must take the rest period. This time must be less than the shift end attribute.
    rest_time_end Mandatory String String "HH:mm" (military time). Maximum time in which this vehicle must take the rest period. This time must be greater than the shift start attribute.
    rest_time_duration Mandatory Integer Minutes that this vehicle will remain in a rest time. This duration must be less than or equal to the time window established to take the break.
    enable_rest_time Optional Boolean Default: False. If true, the vehicles considering a rest time on the route, which is defined with the previous parameters.

    Ruteo Incremental (Vehicles with previously created routes)

    Example of Vehicle object with pre-created routes for each vehicle

    {
      "vehicles": [
        {
          "ident": "7247",
          "location_start": {
            "ident": "7247",
            "lat": -21.6698437,
            "lon": -49.7495409
          },
          "shift_start": "09:12",
          "shift_end": "18:00",
          "partial_tour": {
            "ident": "7247",
            "partial_routes": [
              {
                "nodes": [
                  "18112000205726",
                  "10081834157634",
                  "10089320449243"
                ],
                "fixed_nodes_number": 2
              },
              {
                "nodes": [
                  "10089034859206",
                  "18162900171426",
                  "18109901985501",
                  "18162900171339"
                ],
                "fixed_nodes_number": 3
              }
            ]
          }
        }
      ],
        "incremental_routing": true
    }
    

    En algunos escenarios, ya existen rutas creadas y se desea optimizar teniendo en cuenta que estas rutas no se desarmen, sino que se integren nuevos nodos en los mismos vehículos u otros. Esta optimización, llamada enrutamiento incremental, permite optimizar considerando que hay rutas que deben permanecer fijas.

    La optimización de enrutamiento incremental tiene dos secciones principales:

    • Partial Tour: Objeto que indica que el vehículo tiene rutas parciales creadas previamente. Contiene un ident que corresponde al mismo identificador del vehículo. Si no deseas que el vehículo tenga rutas parciales, este objeto debe ser null.
    • Partial Routes: Arreglo de objetos de ruta parcial. Cada objeto de ruta parcial es una ruta pre-creada que contiene una lista de identificadores de nodos.

    Para utilizar la optimización de ruteo incremental, debes emplear el mismo endpoint de optimización de rutas que se usa para optimizaciones regulares, pero agregando estas secciones y algunos parámetros opcionales en el objeto vehicles para cada vehículo. Solo los vehículos que tengan los objetos y parámetros adicionales serán considerados como vehículos con rutas pre-creadas. Es importante tener en cuenta que tanto los nodos pertenecientes a rutas parciales como los nuevos nodos deben estar dentro de la lista de entregas del objeto Nodes Object.

    Estos son los nuevos parámetros que puedes agregar en el objeto de ruta parcial:

    Attributes Mandatory Type Description
    nodes Mandatory String array Ident of the nodes that are part of the route that you want to keep in the vehicle.
    fixed_nodes_number Mandatory Integer First n nodes that remain fixed in the vehicle and in the position in this previously created route. If the value is equal to 0, all the nodes can change their position but not the vehicle. If the value is equal to the size of the list of nodes, this partial route remains as it is, no node moves.

    Además, debes habilitar este parámetro adicional que permite utilizar esta funcionalidad:

    Attributes Mandatory Type Description
    incremental_routing Optional Boolean Default: False. If true, the vehicles considering the previouly created routes which are defined with the previous objetcs and parameters.

    Rutas Largas

    Ejemplo de objetos Vehicles y Nodes con optimización de rutas largas, donde una ruta nocturna comienza a las 10:00 p.m. y termina a las 7:00 a.m. del día siguiente (equivalente a 31:00 hrs).

    {
      "vehicles": [
        {
          "ident": "Vehicle 1",
          "location_start": {
            "ident": "warehouse A",
            "lat": -12.101389,
            "lon": -77.004534
          },
          "capacity": 3500,
          "shift_start": "22:00",
          "shift_end": "31:00"
        }
      ],
      "nodes": [
        {
          "ident": "Jirón Vesalio 252, San Borja",
          "lat": -12.105329,
          "lon": -77.005524,
          "arrayOfTimeWindows": [
            [
              "25:00",
              "28:00"
            ]
          ],
          "load": 77,
          "duration": 10
        },
        {
          "ident": "Jirsón Tasso 423, San Borja",
          "lat": -12.098615,
          "lon": -77.007240,
          "arrayOfTimeWindows": [
            [
              "26:00",
              "30:00"
            ]
          ],
          "load": 77,
          "duration": 10
        }
      ],
      "longRoutes": true
    }
    

    Nuestro algoritmo extiende la creación de rutas para realizar operaciones de enrutamiento nocturnas, es decir, más allá de las 24 horas de un día, denominadas Optimización de Rutas Largas.

    Para utilizar la Optimización de Rutas Largas, debes emplear el mismo endpoint de optimización de rutas que se usa para optimizaciones regulares, pero añadiendo algunos parámetros opcionales a todos los objetos de nodo. Además, debes activar un parámetro adicional que permita utilizar esta funcionalidad.

    Es importante tener en cuenta que esta característica está enfocada en realizar optimizaciones de enrutamiento nocturnas, pero es posible crear rutas de más de un día. Sin embargo, esta funcionalidad solo admite horizontes de no más de 7 días, con un máximo de 10 vehículos y/o 40 nodos por vehículo.

    Estos son los nuevos parámetros que puedes agregar:

    Attributes Mandatory Type Description
    arrayOfTimeWindows Optional Object Array of time windows (array of two String in format "HH:mm") to attend the visit. Times can be set for more than 24 hours. This attribute only works if longRoutes is True.
    longRoutes Optional Boolean Default: False. If true, it allows the vehicle to have a shift_end greater than 24 hours. In the visits the time windows must be sent.

    Radial Routing

    Esta opción de enrutamiento hace que las rutas tiendan a ser más radiales respecto al depósito. Cuando se establece "radial_routing": 1, las rutas tenderán a comenzar más cerca del depósito y terminar más lejos, y en la secuencia de visitas, cada visita tenderá a estar más lejos del depósito que la anterior. Cuando se establece "radial_routing": -1, las rutas tenderán a comenzar más lejos del depósito y terminar más cerca, y en la secuencia de visitas, cada visita tenderá a estar más cerca del depósito que la anterior. El efecto será más notable y está diseñado para el caso de una ruta por vehículo ("single_tour": true). Es importante señalar que, para los propósitos de esta opción, la proximidad de las visitas se refiere a la proximidad en el tiempo de viaje, no en la distancia.

    Para utilizar el Radial Routing, debes activar el parámetro radial_routing (estableciendo su valor en 1 o -1) y se debe cumplir una o más de las siguientes condiciones:

    • El parámetro beauty está activado ("beauty": true).
    • El parámetro min_load tiene un valor mayor a 0.
    • Hay más de 800 nodos.

    Cálculo de Tiempo Estimado

    ETC Update Endpoint

    
    https://optimizator.simpliroute.com/etc/sync
    
    

    JSON input

    {
        "vehicle": {
            "vehicle_id": "Vehicle 1",
            "lat": -33.45754,
            "lon": -70.92697,
            "departure_time": "09:00"
        },
        "tours": [
            {
                "nodes": [
                    {
                        "id": "id1",
                        "lat": -33.45754,
                        "lon": -70.62697,
                        "service_time": 30.0,
                        "order": 0
                    },
                    {
                        "id": "id2",
                        "lat": -33.45744,
                        "lon": -70.77532,
                        "service_time": 90.0,
                        "order": 1
                    },
                    {
                        "id": "id3",
                        "lat": -33.45742,
                        "lon": -70.60364,
                        "service_time": 90.0,
                        "order": 2
                    }
                ]
            }
        ],
        "fmv": 2.0
    }
    

    Una vez que tu vehículo está en ruta, pueden ocurrir muchas cosas:

    • Congestionamientos de tráfico.
    • Tiempos de servicio más largos de lo esperado.
    • Situaciones inesperadas en las calles.
    • Nuevas prioridades a lo largo del día.

    Entonces, después de un tiempo, la ETA inicial calculada ya no es válida y necesitas recalcularla. Para estos casos, contamos con un endpoint dedicado que resuelve este problema. Algunas consideraciones sobre este endpoint:

    • Debes proporcionar la hora actual para recalcular la ETA ("departure_time").
    • Solo acepta un vehículo con un recorrido por solicitud.
    • Mantendrá el orden proporcionado; no realizará ninguna optimización (VRP o TSP).
    • La ETA/ETD predicha se basará en nuestras estimaciones de tráfico.

    A continuación, puedes ver la información de entrada y los tipos de datos correspondientes al vehículo:

    Attributes Mandatory Type Description
    vehicle_id Mandatory String The vehicle id identifier
    lat Mandatory Double Current vehicle's latitude
    lon Mandatory Double Current vehicle's longitude
    departure_time Mandatory Time Current time to start the ETA recalculation "HH:mm"

    En el lado de los recorridos y los nodos, estos son los atributos:

    Attributes Mandatory Type Description
    id Mandatory String Visit identifier
    lat Mandatory Double Visit latitude
    lon Mandatory Double Visit longitude
    service_time Mandatory Double Minutes to unload deliveries from the vehicle
    order Mandatory Integer Order of visit inside of the tour.

    Por el momento, solo se admite una ruta por recorrido. Si se envían más de una ruta, se responderá con un error.

    La solicitud también puede incluir el factor de tráfico (Traffic factor).

    Attributes Mandatory Type Description
    fmv Optional Integer Default: 2.0, Speed traffic factor. It could be 1.0 = Low Traffic, 1.5 = Medium Traffic, 2.0 = High Traffic or 3.0 = Intense Traffic.

    Puedes ver un ejemplo de la respuesta en el lado derecho de esta documentación.

    JSON response:

    {
        "vehicle": {
            "vehicle_id": "Vehicle 1",
            "lat": -33.45754,
            "lon": -70.92697,
            "departure_time": "09:00"
        },
        "tours": [
            {
                "nodes": [
                    {
                        "id": "id1",
                        "lat": -33.45754,
                        "lon": -70.62697,
                        "service_time": 30,
                        "order": 0,
                        "arrival": "09:48",
                        "departure": "10:18"
                    },
                    {
                        "id": "id2",
                        "lat": -33.45744,
                        "lon": -70.77532,
                        "service_time": 90,
                        "order": 1,
                        "arrival": "10:50",
                        "departure": "12:20"
                    },
                    {
                        "id": "id3",
                        "lat": -33.45742,
                        "lon": -70.60364,
                        "service_time": 90,
                        "order": 2,
                        "arrival": "13:00",
                        "departure": "14:30"
                    }
                ]
            }
        ]
    }
    

    Optimización: Metadatos

    Los Metadatos de Optimización tienen como objetivo proporcionar al cliente información no disponible en el endpoint de optimización, como las distancias planeadas de las rutas de los vehículos proporcionadas por el endpoint de Optimización.

    Distancia

    El endpoint de distancias ofrece los kilómetros estimados para rutas previamente optimizadas.

    Se requiere un encabezado Authorization que contenga un token válido.

    Optimization Metadata Distances Endpoint

    
    https://optimizator.simpliroute.com/v1/optimization/metadata/distance
    
    

    Solicitud

    Respeta la estructura de la Respuesta de Optimización, por lo que debería ser más fácil de construir después de obtener una optimización.

    Objeto raíz:

    Attributes Mandatory Data Type Description
    country Yes String ISO code referring to the country where the delivery locations are located.
    vehicles Yes Object List of vehicles incurred in the Optimization

    Vehicle object:

    Attributes Mandatory Data Type Description
    ident No String Vehicle's identification string
    tours Yes Object List of tours assigned to the current vehicle

    Tour object:

    Attributes Mandatory Data Type Description
    nodes Yes Object List of nodes that forms the current tour graph.

    Node object:

    Attributes Mandatory Data Type Description
    lat Yes Float Coordinate representing the latitude of the visit or depot
    lon Yes Float Coordinate representing the longitude of the visit or depot

    Example of Request

    {
        "country": "CL",
        "vehicles": [
            {
                "ident": "123",
                "tours": [
                    {
                        "nodes": [
                            {
                                "lat": -41.319286,
                                "lon": -72.995719
                            },
                            {
                                "lat": -41.319081,
                                "lon": -72.989037
                            }
                        ]
                    },
                    {
                        "nodes": [
                            {
                                "lat": -41.317910,
                                "lon": -73.006348
                            },
                            {
                                "lat": -41.317449, 
                                "lon": -72.981885
                            }
                        ]
                    }
                ]
            },
            {
                "ident": "456",
                "tours": [
                    {
                        "nodes": [
                            {
                                "lat": -42.319286,
                                "lon": -73.995719
                            },
                            {
                                "lat": -42.319081,
                                "lon": -73.989037
                            }
                        ]
                    },
                    {
                        "nodes": [
                            {
                                "lat": -42.317910,
                                "lon": -73.006348
                            },
                            {
                                "lat": -42.317449, 
                                "lon": -73.981885
                            }
                        ]
                    }
                ]
            }
        ]
    }
    

    Respuesta

    200

    Devolverá 200 cuando la solicitud sea exitosa. Seguirá la misma estructura de objeto que la solicitud.

    200 response example

    {
        "vehicles": [
            {
                "ident": "123",
                "tours": [
                    {
                        "distance": 899.5,
                        "metric": "meters"
                    },
                    {
                        "distance": 2200.6,
                        "metric": "meters"
                    }
                ]
            },
            {
                "ident": "456",
                "tours": [
                    {
                        "distance": 899.5,
                        "metric": "meters"
                    },
                    {
                        "distance": 2200.6,
                        "metric": "meters"
                    }
                ]
            }
        ]
    }
    

    400 response example

    {
        "statusCode": 400,
        "message": "Country value is required"
    }
    

    5XX reponse example

    {
        "errors": [
            {
                "code": "E5000",
                "message": "Internal server error",
                "metadata": {
                    "code": "E5000"
                }
            }
        ]
    }
    

    Validar Incompatibilidades

    El proceso de validación consiste en iterar por cada visita y verificarla con cada vehículo para detectar cualquier tipo de incompatibilidad basada en habilidades requeridas, habilidades opcionales, cargas, ventanas de tiempo o restricciones de zonas.

    Este proceso solo es compatible con problemas de tipo VRP y se realiza en el optimizador al inicio del proceso, justo antes de procesar el problema. Las visitas que se encuentren incompatibles serán excluidas y no se considerarán en el proceso de optimización.

    Dado que una visita puede presentar diferentes incompatibilidades para cada vehículo, es difícil especificar una única causa. En tales casos, se proporcionará una descripción resumida, enumerando las categorías que son incompatibles con la visita.

    Ejemplo

    A continuación, se muestra un ejemplo de una respuesta de problema que contiene una visita y tres vehículos, donde ninguno de los vehículos cumple con los requisitos de la visita:

    JSON response:

    {
      "filteredClientsNodes": [
        {
          "ident": "Visit",
          "cause": {
            "description": "No vehicles matching: required skills, optional skills, time windows, zone, load",
            "codes": [
              "W02002",
              "W02102",
              "W03002",
              "W04002",
              "W01001"
            ],
            "details": [
              {
                "code": "W02002",
                "category": "required skills",
                "description": "None Vehicles has the required skills for this visit.",
                "count": 3
              },
              {
                "code": "W02102",
                "category": "optional skills",
                "description": "None Vehicles has the optional skill for this visit.",
                "count": 3
              },
              {
                "code": "W03002",
                "category": "time windows",
                "description": "The visit's time window falls out outside the working hours of all vehicles.",
                "count": 3
              },
              {
                "code": "W04002",
                "category": "zone",
                "description": "None vehicle has been assigned to the visit's zone",
                "count": 3
              },
              {
                "code": "W01001",
                "category": "load",
                "description": "Some vehicles has not the required capacity for this visit.",
                "count": 2
              }
            ]
          }
        }
      ]
    }
    

    Mientras la descripción nos informa que hay incompatibilidades en las 5 categorías (carga, habilidades requeridas, habilidades opcionales, ventanas de tiempo, zona), en el atributo "details", podemos observar un atributo "counter" que indica la cantidad de vehículos que no son compatibles en cada categoría. Las causas se ordenan en orden descendente según el número de vehículos incompatibles.

    Lista de Códigos

    A continuación, se muestra la descripción del código y la lista de causas de incompatibilidad admitidas.

    Estructura

    <Letra Inicial><Categoría del Problema><Número Específico>

    Letra Inicial:

    • W: Indica una alerta o advertencia relacionada con una visita mal creada.

    Códigos de Incompatibilidad Primaria

    • W00001: Indefinido.
    • W01002: Ningún vehículo tiene la capacidad requerida para esta visita.
    • W02002: Ningún vehículo tiene las habilidades requeridas para esta visita.
    • W02102: Ningún vehículo tiene la habilidad opcional para esta visita.
    • W03002: La ventana de tiempo de la visita está fuera del horario laboral de todos los vehículos.
    • W04002: Ningún vehículo ha sido asignado a la zona de la visita.

    Códigos de Incompatibilidad Secundaria

    • W01001: Algunos vehículos no tienen la capacidad requerida para esta visita.
    • W02001: Algunos vehículos no tienen las habilidades requeridas para esta visita.
    • W02101: Algunos vehículos no tienen la habilidad opcional para esta visita.
    • W03001: La ventana de tiempo de la visita está fuera del horario laboral de algunos vehículos.
    • W04001: Algunos vehículos no han sido asignados a la zona de la visita.

    Facturas

    Para usar esta API, tu cuenta debe tener activado el AddOn de Contabilidad, por favor, contacta a tu especialista de integración.

    Nota: Esta API está en constante actualización, añadiendo campos o haciendo pequeños ajustes. La información presentada puede cambiar.

    Factura

    Entidad principal que representa un documento financiero, como una factura, recibo, nota de entrega, etc. Usamos formalmente esta definición:

    Factura: documento comercial con marca de tiempo que detalla y registra una transacción entre un comprador y un vendedor.

    Invoice creation cURL (minimal payload)

    curl --location --request POST 'http://api.simpliroute.com/v1/accounting/invoices/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "reference" : "external identifier",
        "currency": "CLP",
        "type": "bill",
        "visit": 15081986
    }'
    

    Invoice creation cURL (full payload)

    curl --location --request POST 'http://api.simpliroute.com/v1/accounting/invoices/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "reference" : "external_id 1234",
        "currency": "USD",
        "visit": 185202350,
        "payment_method": "transfer",
        "type": "bill",
        "status": "payed",
        "label": "custom_title",
        "items": [{
            "title": "inline item",
            "type": "paquete"
        }]
    }'
    

    Invoice update cURL

    curl --location --request PATCH 'http://api.simpliroute.com/v1/accounting/invoices/<invoice_id>/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "reference" : "external_id",
        "currency": "CLP",
        "visit": 15081986
    }'
    

    Invoice delete cURL

    curl --location --request DELETE 'http://api.simpliroute.com/v1/accounting/invoices/<invoice_id>/' \
    --header 'Authorization: Token <your_token>'
    

    Una Factura existe de manera independiente de la Visita, aunque está relacionada con ella. Sus propiedades mínimas y obligatorias son:

    Name Type Description
    reference string external identifier for the invoice
    currency string money currency for items prices. Following the ALPHA-3 convention described in the ISO 3166 international standard. Ex: CLP
    visit int visit id to which the invoice relates to
    type string the type of Invoice. Currently supported: ('bill', 'credit_note', 'delivery_note', 'debit_note')

    Una Factura se crea utilizando el servicio https://api.simpliroute.com/v1/accounting/invoices/ un ejemplo en cURL se muestra en el panel derecho 👉)

    Otros campos disponibles para Factura son:

    Name Type Default Description
    payment_method string 'cash' the payment method declared for the Invoice. One of ('cash', 'check', 'credit_card', 'debit_card', 'transfer', 'dated_check', 'credit')
    payment_method_details string none available to store extra information about payment method
    status string 'pending' the invoice status. One of ('pending', 'payed', 'overdue', 'canceled', 'partial', 'completed')
    items list of InvoiceItem [] list of items in invoice. Can be initialized with a list of dictionaries like: [{ "title": "item title", "type": "item type"}]
    delivery_issue one of the available DeliveryIssue for the account null indicates if Invoice had a delivery issue, and which one.
    label string null custom field to store a name or title for the Invoice

    Los servicios para recuperación, actualización y eliminación son los siguientes:

    GET http://api.simrpliroute.com/v1/accounting/invoices/<invoice_id>/

    PATCH http://api.simrpliroute.com/v1/accounting/invoices/<invoice_id>/

    DELETE http://api.simrpliroute.com/v1/accounting/invoices/<invoice_id>/

    El servicio de recuperación admite dos parámetros de consulta: route_id y planned_date.

    route_id para consultar las Facturas asociadas con las visitas de una ruta determinada. Ex.:

    GET http://api.simrpliroute.com/v1/accounting/invoices/?route_id=abs-qq2-asas

    planned_date para consultar las facturas asociadas con visitas de una fecha planificada determinada. Ex.:

    GET http://api.simrpliroute.com/v1/accounting/invoices/?planned_date=2024-02-26

    Itemp para Factura (InvoiceItem)

    Creación o actualización de InvoiceItem mediante cURL

    curl --location --request POST 'http://api.simpliroute.com/v1/accounting/invoices/<invoice_id>/items/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '[
        {
            "title": "a good iteam"
        },
        {
            "reference": "new reference",
            "title": "a not so good item"
        }
    ]'
    

    InvoiceItem deletion cURL

    curl --location --request DELETE 'http://api.simpliroute.com/v1/accounting/invoices/a947125d-da24-447f-8db4-01ab0b5c4bf9/items/1' \
    --header 'Authorization: Token <your_token>'
    

    InvoiceItem representa un ítem dentro de una Factura y puede ser declarado en el momento de crear la Factura o posteriormente. Las propiedades de un InvoiceItem son:

    Name Type Mandatory Description
    title string yes name or title for the item
    reference string yes external identifier for this item
    sku string no item’s SKU
    unit_price float no item unitary price
    planned_units float no number of units expected to be delivered
    delivered_units float no number of units actually delivered
    delivery_issue one of the available DeliveryIssue for the account no indicates if item had a delivery issue, and which one.
    type string no item type
    product string no optional Product identifier

    Los InvoiceItems solo existen dentro de una Factura. Un InvoiceItem se crea utilizando el servicio:

    POST http://api.simpliroute.com/v1/accounting/invoices/<invoice_id>/items/

    Ejemplos de creación, eliminación y actualización de InvoiceItem se pueden encontrar en el panel derecho 👉

    DeliveryIssue

    DeliveryIssue creation cURL

    curl --location --request POST 'http://api.simpliroute.com/v1/accounting/invoices/delivery-issues/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
    "title": "issue title",
    "description": "dog does not allow entrance"
    }'
    

    DeliveryIssue update cURL

    curl --location --request PATCH 'http://api.simpliroute.com/v1/accounting/invoices/delivery-issues/<delivery_issue_id>/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{"title":"delivery issue - new title"}'
    

    DeliveryIssue delete cURL

    curl --location --request DELETE 'http://api.simpliroute.com/v1/accounting/invoices/delivery-issues/<delivery_issue_id>/' \
    --header 'Authorization: Token <your_token>'
    

    Un DeliveryIssue representa una razón de no entrega o un problema en el momento de la entrega. Los valores disponibles son definidos por cada cuenta. Las propiedades de un DeliveryIssue son:

    Name Type Mandatory Description
    title string yes issue name or title
    description string no issue description
    type string no is this issue available for items or invoices. Expects one of ('item', 'invoice')
    reference string no external identifier for this DeliveryIssue

    Ejemplos de creación, eliminación y actualización de DeliveryIssue se pueden encontrar en el panel derecho 👉

    Products and ProductCategory

    Product creation cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/accounting/products/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '[{
    "title": "title",
    "sku": "13231323",
    "category": 1
    }]'
    

    Product update cURL

    curl --location --request PATCH 'https://api.simpliroute.com/v1/accounting/products/ae5e625c-a1ec-413b-9a3f-abe3c2825e4d/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "title": "new title"
    }'
    

    Product delete cURL

    curl --location --request DELETE 'https://api.simpliroute.com/v1/accounting/products/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '[{
    "title": "title",
    "sku": "13231323"
    }]'
    

    Dada la necesidad de que un InvoiceItem sea descrito a partir de una "clase", una "plantilla" o una definición preexistente, se modeló la entidad Product. De esta manera, un InvoiceItem puede estar asociado a un Product de manera opcional.

    Un Product tiene las siguientes propiedades:

    Name Type Mandatory Description
    title string yes Product name or title
    sku string yes stock keeping unit (SKU) of the Product
    price float no price per 1 unit of this Product
    categories list yes ID of corresponding ProductCategory’s ID

    Una ProductCategory permite relacionar varios Products en el mismo grupo o categoría. Un Product puede o no definir una categoría, category es una propiedad opcional para Product.

    Las propiedades de una ProductCategory son:

    Name Type Mandatory Description
    name string yes ProductCategory name
    parent int no when dealing with hierarchy, parent represents the ProductCategory where this ProductCategory belongs.

    Existen servicios de creación (POST), recuperación (GET), actualización (PATCH) y eliminación (DELETE) para Product y ProductCategory en los siguientes endpoints:

    Product - http://api.simpliroute.com/v1/accounting/products/

    ProductCategory - http://api.simpliroute.com/v1/accounting/product-categories/

    Ejemplos de creación, eliminación y actualización de Product se pueden encontrar en el panel derecho 👉

    El proceso de Checkout

    La operación de cierre (checkout) completo es una composición de múltiples servicios:

    1) Iniciar la ruta 2) Finalizar una visita (checkout a visit) 3) Almacenar valores de campos extra (store extra-field-values) 4) Almacenar imágenes (store pictures) 5) Activar notificaciones (trigger notifications)

    1. Iniciar la ruta

    Realizar esta acción permite que el sistema reconozca la hora de inicio de la ruta y actualice la ETA de las visitas en consecuencia.

    start a route cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/events/register/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "date_time": "2024-04-24T14:20:45.446Z", 
        "latitude": "-0.346644", 
        "longitude": "-78.455834", 
        "route_id": "24b87d96-813e-4176-a85b-d72171160000", 
        "type": "ROUTE_STARTED" 
      }'
    
    Parameter type description
    date_time string date and hour of start following the ISO 8601 standard (required)
    latitude string latitude at the point of route start
    longitude string longitude at the point of route start
    route_id string identifier or the route to start (required)
    type string indicates the event, for this case value must be ROUTE_STARTED (required)

    2. Checkout a una visita

    Finalizar una visita (checkout a visit) permite que el sistema registre la acción y muestre los datos correspondientes en nuestras aplicaciones de frontend.

    Visit checkout (minimal payload) cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/mobile/visit/<visit_id>/checkout/' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "status": "completed", 
        "checkout_time": "2024-04-24 13:24:53", 
        "checkout_latitude": -12.105513, 
        "checkout_longitude": -76.965618, 
        "checkout_comment": "everything was OK" 
      }'
    

    Los campos obligatorios son los siguientes:

    Parameter type description
    status string one of the following statuses: pending, completed, failed
    checkout_time string date and hour of checkout following the ISO 8601 standard
    checkout_latitude float latitude at the point of delivery
    checkout_longitude float longitude at the point of delivery
    checkout_comment string optional comment

    Otros parámetros disponibles son:

    Parameter type description
    checkout_user_id int by default the system will register the user asociated with the token as the performer of the checkout action. In case the user is different, use this field to provide the user id
    signature string base64 representation of the signature image as proof of delivery

    3. Almacenar valores de campos extra (extra-field-values)

    Store extrafields values cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/routes/visits/multiple/extra-field-values' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "json": '{\"operation_nice\":true, \"other_extrafield\":\"a value\" }', \"visits\": [123, 456, 789]}'
    

    En caso de que se hayan definido campos extra para la Visita dada, los valores de los campos extra pueden declararse utilizando este servicio: https://api.simpliroute.com/v1/routes/visits/multiple/extra-field-values

    Ejemplo de payload esperado:

    {'json': '{"georeferencia_incorrecta":false}', 'visits': [01407818]}

    Ten en cuenta que un valor de campo extra puede asignarse a múltiples visitas. También es importante que el nombre del campo extra (extrafield_name, como georeferencia_incorrecta en el ejemplo) corresponda a uno de los campos extra disponibles para la cuenta. El valor de un campo extra puede ser bool, int o string, dependiendo de la definición del campo extra.

    Un ejemplo está disponible en el panel derecho 👉

    4. Almacenar imagenes

    store picture cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/routes/visits/multiple/pictures/' \
    --header 'Authorization: Token <your_token>' \
    --form 'visits="[12, 34, 56]"' \
    --form 'image=@"/path/to/image/picture.png"'
    

    En caso de que necesites adjuntar imágenes a la visita que estás cerrando, utiliza este servicio: https://api.simpliroute.com/v1/routes/visits/multiple/pictures/

    Los parámetros esperados son:

    Parameter description
    image path to file using form request
    visits array of visit_id to associate image to

    5. Activar notificaciones

    Trigger notifications cURL

    curl --location --request POST 'https://api.simpliroute.com/v1/routes/visits/multiple/extra-field-values' \
    --header 'Authorization: Token <your_token>' \
    --header 'Content-Type: application/json' \
    --data-raw '
        {"checkout_time": "2024-04-24T16:39:53.076Z", "visits": [407726472]} '
    

    Para activar notificaciones de SMS, WhatsApp, correo electrónico y seguimiento en tiempo real, se debe realizar una solicitud final utilizando el servicio: https://api.simpliroute.com/v1/mobile/visit/multiple/checkout/notify

    Los parámetros esperados son:

    Parameter description
    checkout_time date and hour of checkout following the ISO 8601 standard
    visits array of visit_id to trigger notification of

    TMS: Proveedor de transporte

    IMPORTANTE: Este servicio solo está disponible para los clientes que lo hayan contratado.

    Se ofrecen las siguientes acciones para gestionar la entidad Proveedor de Transporte.

    Se requiere un encabezado Authorization que contenga un Token válido.

    Para acceder a este recurso se requiere la siguiente URL: https://api-gateway.simpliroute.com/tms/api/v1

    Solicitud de creación

    Crea un Proveedor de Transporte en el sistema.

    Basic Request

    {
        "trade_name": "FEDEX",
        "status": "active",
        "contact_person": "Doe Dawson"
    }
    

    HTTP method: POST Resource's path: /transportation-providers Body:

    Attributes Mandatory Data Type Default Description
    trade_name Yes String Commercial name for the provider
    legal_name No String Registered name in administrative institutions
    account_id Yes Integer Account’s id corresponding to the Token
    status No String active Registered name in administrative institutions
    contact_person Yes String Representative person for contact purposes
    contact_email No String
    phone_number No String
    address No String
    tax_id_number No String Legal identification number
    reference No String Identification code used by our clients for this entity

    Responses

    Code Description
    201 Successful creation
    422 Payload has formatting errors
    500 Server error

    List Request

    Listar todos los Proveedores de Transporte.

    HTTP method: GET Resource's path: /transportation-providers Body: empty

    Responses

    Code Description
    200 Successful creation
    500 Server error

    Solicitud para recuperar recurso

    Obtener un Proveedor de Transporte específico.

    HTTP method: GET Resource's path: /transportation-providers/{id} Body: empty

    NOTA: El ID del recurso deseado se especifica en la ruta.

    Respuestas

    Code Description
    200 Successful creation
    404 Resource doesn't exist
    500 Server error

    Actualizar

    Cambiar un Proveedor de Transporte específico.

    HTTP method: GET Resource's path: /transportation-providers/{id} Body: Igual al presentado en la Solicitud de Creación..

    NOTA: El ID del recurso deseado se especifica en la ruta.

    Respuestas

    Code Description
    200 Successful update
    400 Wrong request
    403 User without authorization
    404 Resource doesn't exist
    422 Payoad has formatting errors
    500 Server error

    Eliminar

    Eliminar un Proveedor de Transporte específico.

    HTTP method: GET Resource's path: /transportation-providers/{id} Body: empty

    NOTA: El ID del recurso deseado se especifica en la ruta.

    Respuestas

    Code Description
    204 Successful deletion
    400 Wrong request
    403 User without authorization
    404 Resource doesn't exist
    500 Server error

    Asignar Proveedor de Transporte a Vehículo con Solicitud de Proveedor de Transporte

    Asignar un proveedor de transporte a un vehículo, creando una relación entre ambos.

    Este endpoint permite asignar varios proveedores de transporte en una sola solicitud.

    Basic Request

    [
      {
        "vehicle_id": 2,
        "transportation_provider_id": "14383454-keur-64f7-232e-901434a8f5ga"
      },
      {
        "vehicle_id": 3,
        "transportation_provider_id": "42383454-ba4a-4ff7-b52e-90544e8f5e44"
      }
    ]
    

    HTTP method: POST Resource's path: /vehicles/transportation-providers Body: Array of objects

    Attributes Mandatory Data Type Description
    vehicle_id Yes Integer Commercial name for the provider
    transportation_provider_id Yes UUID Registered name in administrative institutions

    Responses

    Code Description
    200 Successful request
    404 Resource doesn't exist
    500 Server error

    Integración GPS

    Simpliroute puede integrarse con tu sistema GPS para obtener datos importantes.

    Por favor, contacta a nuestro equipo de servicios profesionales para obtener detalles técnicos sobre cómo configurar esta integración en [email protected].

    Frecuencia de envío de datos

    Se recomienda enviar un máximo de 1 dato por vehículo cada 20 segundos. Para flotas de más de 20 vehículos, 1 dato por minuto/vehículo es la frecuencia óptima para una correcta representación de las rutas en el mapa.

    Pérdida de señal y envío de datos almacenados localmente

    En caso de que uno o más vehículos circulen por áreas fuera del rango satelital o ante cualquier factor que genere una pérdida de señal en los dispositivos instalados, se recomienda el uso de “colas” para los datos que no pudieron enviarse por la razón mencionada, y enviarlos posteriormente, cuando la señal se restablezca. Cuando esto último ocurra, el sistema podría enviar los datos acumulados en la cola con un intervalo máximo de 10 segundos entre cada uno, hasta enviar todos los objetos almacenados.

    Importante: El intervalo de 10 segundos solo aplica a los datos almacenados localmente debido a la pérdida de señal. Los vehículos dentro de la cobertura satelital deben seguir la recomendación mencionada al principio de este documento.

    Además, los datos deben enviarse de forma independiente. Un arreglo con todos los objetos podría causar errores en la comunicación de la llamada.

    Example Input

    {
    "latitude":-33.4311548,
    "longitude":-70.5701852 ,
    "timestamp":"2019-02-20 10:35:00-00”,
    "vehicleId”: "JKCT-81",
    "providerName”: "LOCALIZAGPS_AGROSUPER”,
    }
    

    Integración de GPS y datos variables con SimpliRoute

    Para la integración de datos GPS y variables adicionales con SimpliRoute (como temperatura o humedad), se debe enviar la siguiente información, mediante el método POST, al endpoint

    Por favor, contacta a nuestro equipo de servicios profesionales para obtener detalles técnicos sobre cómo configurar esta integración en [email protected].

    Detalles del payload

    Attributes Description
    latitude Decimal number up to 6 decimal digits.
    longitude Decimal number up to 6 decimal digits.
    timestamp Date and time in UTC with format YYYY-MM-DD HH:II:SS-00 Example: 2019-02-20 10:35:00-00
    vehicleId Vehicle ID in SimpliRoute system.
    temperature Temperature data, see “temperature” object. (backwards compatible but deprecated, it is recommended to send the temperature information in the alert object)
    alert Alert data, see “alert” object
    providerName Name of the vehicle GPS information provider.

    Temperature object

    Attributes Description
    value Decimal number with the temperature in degrees Celsius.
    alert_type Alert type, “min” when the temperature is below the limit set or “max” when greater.
    alert_message Message to be sent to the supervisor in charge of the trucks and the transport of refrigerated cargo.

    Alert Object

    Attributes Description
    name Alert type identifier.
    type alert type
    value Alert Value
    message Message to be sent to the supervisor in charge of the trucks.

    Alerts

    Es posible enviar variables adicionales mediante un arreglo de objetos que mantengan la siguiente estructura:

    Attributes Description
    name Alert type identifier.
    type alert type
    value Alert Value
    message Message to be sent to the supervisor in charge of the trucks.

    Available alerts

    Names
    temperature
    geofence
    speed
    humidity
    door
    estado
    brake
    temperature_2
    temperature_3
    jamming
    tiredness
    fuel_cap
    fuel_variation
    driver_door_open
    speeding
    loss_of_load
    no_smoking o smoking
    Demurrage

    Input example

    [
        {
    "latitude": -33.4311548,
    "longitude": -70.5701852,
    "timestamp": "2017-10-19 09:12:02-00",
    "vehicleId": "<<vehicle_id>>",
    "temperature": {
    "value": 2.4,
    "alert_type": null,
    "alert_message": null
    },
    "alert": {
    "name": “door”,
    "type": “open”,
    "value": true,
    “message”: “open door alert”
    },
    “alerts”: [
    {
    "name": “general”,
    "type": “ºC”,
    "value" 4,
    “message”: “temperature is lower than 5 degress”
    },
    ...
    ],
    "providerName": "<<provider>>"
    }
    

    Response example

    {
    "status": "Tracked",
    "id": "2408269119724499",
    "daily_status": "Updated"
    4
    }
    

    API response when exist one or more invalid alerts ``` json

    { "status": "Tracked", "id": "2408269119724499", "daily_status": "Updated", "invalid_alerts": [] "invalid_alert": []

    } ```

    Frecuencia para el envío de datos

    Se recomienda enviar un máximo de un dato por vehículo cada 20 segundos. Para flotas de más de 20 vehículos, un dato por minuto/vehículo es la frecuencia óptima para una correcta representación de las rutas en el mapa

    Pérdida de señal y envío de datos almacenados localmente

    En caso de que uno o más vehículos circulen por áreas fuera del rango satelital o se enfrenten a factores que generen una pérdida de señal en los dispositivos instalados, se recomienda el uso de “colas” para los datos que no pudieron enviarse debido a la razón anterior, de modo que puedan enviarse más tarde, cuando la señal se restablezca. Cuando esto ocurra, el sistema podría enviar los datos acumulados en la cola con un intervalo máximo de 10 segundos entre cada uno, hasta completar el envío de todos los objetos guardados.

    Importante: El intervalo de 10 segundos solo aplica a los datos almacenados localmente como resultado de la pérdida de señal. Los vehículos que están dentro de la cobertura satelital deben mantener la frecuencia recomendada al inicio de este documento.

    Además, los datos deben enviarse de forma independiente. Un arreglo con todos los objetos puede causar errores en la comunicación de la llamada.

    Errors

    The SimpliRoute API uses the following error codes:

    Error Code Meaning
    400 Bad Request -- Your request is invalid. Review the data type and information sent.
    401 Unauthorized -- You are using the wrong API key to request the information.
    404 Not Found -- The request didn't found results.
    405 Method Not Allowed -- You tried to access to the endpoint with an invalid method.
    406 Not Acceptable -- You requested a format that isn't json.
    500 Internal Server Error -- We had a problem with our server. Try again later.
    503 Service Unavailable -- We're temporarily offline for maintenance. Please try again later.

    Datamart

    Datarmat is a REST API for data querying. To use this API, you will need a token that you can obtain from Customer Support.

    This API is located at https://api-gateway.simpliroute.com/datamart

    curl --location 'https://api-gateway.simpliroute.com/datamart/v1/visits' \
    --header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiZG9jdW1lbnRhdGlvbl9leGFtcGxlIiwiZXhwIjoxOTA2Mzg0MjY1LjB9.f2jx7t95gcZPNhUh31XIVv_9nXN5fYa04Om76U29iu4'
    

    An Authorization header is expected with a Bearer token.

    As an example, the cURL at the right panel requests Visits data 👉

    How does pagination work?

    Datamart delivers a maximum of 500 results per page. To request the next page, use the query parameter offset. For example, to request the second page of Visits, you would use /datamart/v1/visits?offset=500

    It is also possible to request pages with fewer than 500 results using the limit query parameter. For example: /datamart/v1/visits?limit=10&offset=20

    The response headers always include Content-Range, which indicates the page size and the total number of results. For cases when the number of results is higher the 100.000 the total won't be provided unless you requested with the header: Prefer: count=estimated

    What data is available in Datamart?

    Here's a list of currently available services:

    • /v1/visits: Provides access to Visits. For more information about Visit properties, check here.
    • /v1/plans: Provides access to Plans. For more information about Plan properties, check here.
    • /v1/routes: Provides access to Routes. For more information about Route properties, check here.
    • /v1/extrafielddefinitions: An extrafield allows for checkout form customization. For more information about Extra Field properties, check here.
    • /v1/extrafieldoptions: If an extrafield uses predefined options, they can be found in this service. For more information about Extra Field properties, check here.
    • /v1/vehicles: Provides access to Vehicles. For more information about Vehicle properties, check here.
    • /v1/vehicles_skills: Lists Skills associated with a Vehicle. For more information about Skill properties, check here.
    • /v1/fleets: A fleet represents a group of Vehicles. For more information about Fleet properties, check here.
    • /v1/vehicles_fleets: Defines the relationship between Fleets and Vehicles. For more information about Fleet properties, check here.
    • /v1/fleets_users: Defines the users (usually of role driver) associated with a given fleet. For more information about Fleet properties, check here.
    • /v1/observations: During checkout, an Observation can be attached to a Visit. This service provides access to those observations. For more information about Observation properties, check here.
    • /v1/skills: Lists the available Skills. For more information about Skill properties, check here.
    • /v1/tags: One or more Tags can be attached to a Visit. Here is the list of available Tags. For more information about Tag properties, check here.
    • /v1/zones: A Zone represents a geographical area. Here is the list of Zones defined for your account(s). For more information about Zone properties, check here.
    • /v1/vehicles_zones: Defines the relationship between Vehicles and Zones. For more information about Zone properties, check here.
    • /v1/visits_skills_optional: Lists optional Skills defined for a Visit. For more information about Skill properties, check here.
    • /v1/visits_skills_required: Lists required Skills defined for a Visit. For more information about Skill properties, check here.
    • /v1/visits_tags: Lists the Tags attached to a Visit. For more information about Tag properties, check here.
    • /v1/visits_extrafieldvalues: Lists the values assigned to Extrafields during Checkout for a Visit. For more information about Extra Field properties, check here
    • /v1/visititems: Access Visit Items, representing products or services tied to a visit. For more information about Visit Item properties, check here.
    • /v1/accounts: Provides access to Accounts related to the Datamart role. It includes information about the account and its associated organization.
    • /v1/users: Lists the Users in your account, including web users such as admins, monitors, and drivers. For more information about User properties, check here.
    • /v1/invoices: Access Invoices, which represent financial documents. For more information about Invoice properties, check here.
    • /v1/invoiceitems: Access Invoice Items, representing products or services listed in an Invoice. For more information about Invoice Item properties, check here.

    What filtering and sorting options does Datamart offer?

    Basic filtering

    This filter allows to query especific properties, for example:

    /v1/visits?select=id,address

    Will result in responses with id and address properties only

    Conditional filtering

    Give a condition to query for especific values. For example:

    /v1/visits?visit_type_id=eq.5335

    Will responde with Visit on which visit_type_id is equal to 5335. Aside from eq operator, gt or lt are available too.