# Trip

### Fetch by ID

**Parameters**:

* `id`: The unique ID of the `Trip`
* `expansions`: A `Set` of `Expansions` for the `Trip`. Defaults to an empty set.

The Expansion includes `events`, `scores`, `geometry`, and `user` and more. Checkout the enum to see more options.

To fetch a trip by ID, the following API can be used.

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let tripService = TripService()
tripService.fetch(id: id,
                  expansions: expansions then: { result in
    guard !result.value.empty else {
        // error
        return
    }
    completionHandler(.success(result.value))
})
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetch(id,
              expansions) { result: Result<Content?>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val content = result.value
    }
})
```

{% endtab %}
{% endtabs %}

### Fetch by user

Fetch a `Trip` collection with expanded detail.

**Parameters**:

* `user`: The user for which trips are being fetched. If `nil`, fetches the trips for the currently authenticated `User`. Defaults to `nil`.
* `filters`: A Set of `Filters` for the request. Defaults to an empty set..
* `expansions`: A `Set` of `Expansion`s for the collection.

To fetch a trip by user, the following API can be used.

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let tripService = TripService()
tripService.fetch(user: user, 
                  filters: [Filter],
                  expansions: expansions,
                  then: { result in
    guard !result.value.empty else {
        // error
        return
    }
    completionHandler(.success(result.value))
})
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetch(user,
                 filters,
                 expansions) { result: Result<Content?>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val content = result.value
    }
})
```

{% endtab %}
{% endtabs %}

### Fetch all

**Parameters**:

* `filters`: A Set of `Filters` for the request. Defaults to an empty set..
* `expansions`: A `Set` of `Expansion`s for the collection.

The filters include `cursor(limit, offset)`, `date(start, end)`, check [here](#filter) for paging through trips from the logbook.

To fetch all trips, the following API can be used.

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let tripService = TripService()
tripService.fetchAll(filters: [Filter],
                     expansions: expansions then: { result in
    guard !result.value.empty else {
        // error
        return
    }
    completionHandler(.success(result.value))
})
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetchAll(filters,
                 expansions) { result: Result<Content?>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val content = result.value
    }
})
```

{% endtab %}
{% endtabs %}

### Update trip

#### Parameters:

* `trip`: The `Trip` to update.
* `transportMode`: The `TransportMode` to apply to the `Trip`.
* `purpose`: The `Purpose` to apply to the `Trip`.

To update the trip, the following API can be used.

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let service = TripService()
service.update(trip,
               transportMode: TransportMode,
               purpose: purpose { result in
    switch result {
    case .success(_):
        // update successful
    case .failure(_):
        // error
    }
})
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.updateTrip(trip,
                   transportationMode,
                   purpose) { result: Result<Content?>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val content = result.value
    }
})
```

{% endtab %}
{% endtabs %}

### Fetch trips by vehicle

#### **Parameters**:

* `startDate` : The earliest date to include, in the format `yyyy-MM-dd`
* `endDate` : The latest date to include, in the format `yyyy-MM-dd`
* `vehicleId`: The `id` of the vehicle for which we want the list of `Trip`
* `vehicleTripsLimit`: The maximum number of trips, default value of `1`
* `offset`: Defines the starting point (index) for fetching trips, relative to the most recent trip
* `role` : Currently unused, will be deprecated in a future update
* `expansions` (iOS) `expand` (Android): A set of `Expansion`, such as scores
* `userId`: Limit the results to a specific user     &#x20;

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let service = TripService()
service.fetchTripsByVehicle(
    startDate: startDate,
    endDate: endDate,
    vehicleId: vehicleId,
    vehicleTripsLimit: vehicleTripsLimit,
    offset: offset,
    role: role,
    userId: userId,
    completionHandler: { result in
        switch result {
        case .success(let trips):
            // handle success
        case .failure(let error):
            // handle failure
        }
    }
)
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetchTripsByVehicle(endDate,
                            startDate,
                            vehicleTripsLimit,
                            offset,
                            role,
                            expand,
                            vehicleID,
                            userID) { result: Result<List<Trip>> ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val content = result.value
    }
})
```

{% endtab %}
{% endtabs %}

### Fetch trips for user by policy

To fetch trips for user by policy, the following API can be used.

\- **Parameters**:

* `userId`: The user ID being requested
* `policyId`: The policy ID being requested
* `startDate`: Optional start date
* `endDate`: Optional end date&#x20;
* `expansions`: A `Set` of `Expansion`s for the trips. Defaults to an empty set.
* `sortOptions`: An array of `SortOption` for ordering the results. Defaults to an empty array.
* `limit`: Maximum number of trips to return
* `offset`: Start at the Nth (0-indexed) trip within the given sort order
* `transportMode`: Optional transport mode filter

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let service = TripService()
service.fetchTripsForUserByPolicy(userId: userId,
                                  policyId: policyId,
                                  startDateTime: startDateTime,
                                  endDateTime: endDateTime,
                                  expansions: expansions,
                                  sortOptions: sortOptions,
                                  limit: limit,
                                  offset: offset,
                                  transportMode: transportMode) { result in
    switch result {
    case .success(let trips):
        // Success - use trips array
    case .failure(let error):
        // Handle error
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetchTripsForUserByPolicy(userId,
                                  policyId,
                                  startDateTime,
                                  endDateTime,
                                  expansions,
                                  sortOptions,
                                  limit,
                                  offset,
                                  transportMode) { result: Result<List<SimplifiedTrip>>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val trips = result.value
    }
}
```

{% endtab %}
{% endtabs %}

### Fetch trips by policy

To fetch trips by policy, the following API can be used.

\- **Parameters**:

* `policyId`: The policy ID being requested
* `startDate`: Optional start date&#x20;
  * iOS: `DateComponents`
  * Android: `LocalDate`
* `endDate`: Optional end date&#x20;
  * iOS: `DateComponents`
  * Android: `LocalDate`
* `expansions`: A `Set` of `Expansion`s for the trips. Defaults to an empty set.
* sortOptions: An array of `SortOption` options for ordering the results. Defaults to an empty array.
* `limit`: Maximum number of trips to return
* `offset`: Start at the Nth (0-indexed) trip within the given sort order
* `transportMode`: Optional transport mode filter

#### Concrete example

{% tabs %}
{% tab title="Swift" %}

```swift
let service = TripService()
service.fetchTripsByPolicy(policyId: policyId,
                           startDate: startDate,
                           endDate: endDate,
                           expansions: expansions,
                           sortOptions: sortOptions,
                           limit: limit,
                           offset: offset,
                           transportMode: transportMode) { result in
    switch result {
    case .success(let trips):
        // Success - use trips array
    case .failure(let error):
        // Handle error
    }
}
```

{% endtab %}

{% tab title="Kotlin" %}

```kotlin
val service = TripService()
service.fetchTripsByPolicy(policyId,
                           startDate,
                           endDate,
                           expansions,
                           sortOptions,
                           limit,
                           offset,
                           transportMode) { result: Result<List<SimplifiedTrip>>? ->
    if (result?.value == null || result.throwable != null) {
        // failure
    } else {
        // Success
        val trips = result.value
    }
}
```

{% endtab %}
{% endtabs %}

### Filter

The Trip APIs support pagination through a **cursor** parameter, which allows efficient navigation through a user's trips. The cursor utilizes two key fields: **limit** and **offset**.

**Cursor Parameters**

* **limit**: Specifies the maximum number of trips to retrieve per request. If not provided, the default value is `50`.
* **offset**: Defines the starting point (index) for fetching trips, relative to the most recent trip.

**Usage Example**

Assume a user has a total of 200 trips. The host application can retrieve trips in pages using the cursor parameters as follows:

1. **Fetch the Most Recent Trips**\
   To retrieve the 50 most recent trips:

   ```
   cursor(limit: 50, offset: 0)
   ```
2. **Fetch the Next Page of Trips**\
   To retrieve the next 50 trips:

   ```
   cursor(limit: 50, offset: 50)
   ```
3. **Continue Paging Through Trips**\
   Subsequent requests can increment the `offset` by the `limit` value to fetch further pages:

   ```
   cursor(limit: 50, offset: 100) // Retrieves trips 101–150
   cursor(limit: 50, offset: 150) // Retrieves trips 151–200
   ```

**Key Points to Note**

* The `limit` value should be chosen based on the application's requirement for batch size, balancing data size and API call frequency.
* Pagination parameters enable efficient navigation through the logbook without overwhelming the API or client application with large data responses.
