plansolve 0.27.0

Official Rust client library for the PlanSolve optimization API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use serde::{Deserialize, Serialize};

/// A `[latitude, longitude]` coordinate pair.
pub type Location = [f64; 2];

/// Request model for starting a field service optimization.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FieldServiceRequest {
    /// Vehicles (technicians/resources) available to service the visits.
    pub vehicles: Vec<Vehicle>,
    /// Visits (jobs/stops) to be scheduled across the vehicles.
    pub visits: Vec<Visit>,
    /// Constraint weights as score-notation strings keyed by constraint name, e.g.
    /// `{"minimizeTravelTime": "0hard/0medium/1soft"}`. The server models this as an
    /// open map (`additionalProperties: string`), so any constraint key and score
    /// string passes through unchanged — do not narrow it to a fixed struct.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub weights: Option<std::collections::HashMap<String, String>>,
    /// Optional termination controls for the solve.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<SolverOptions>,
}

/// A vehicle available for scheduling.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Vehicle {
    /// Caller-supplied unique identifier for the vehicle.
    pub id: String,
    /// Human-readable vehicle/resource name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Home/depot coordinates as `[latitude, longitude]`.
    pub location: Location,
    /// Working shifts (time ranges) during which the vehicle is available.
    pub shifts: Vec<Shift>,
    /// Skills the vehicle provides, matched against each visit's required skills.
    pub skills: Vec<String>,
    /// Time the vehicle departs its depot, as an ISO-8601 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub departure_time: Option<String>,
    /// Ordered ids of the visits assigned to this vehicle (populated in the solution).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub visits: Vec<String>,
}

/// A visit (job/task) to be scheduled.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Visit {
    /// Caller-supplied unique identifier for the visit.
    pub id: String,
    /// Human-readable visit name.
    pub name: String,
    /// Visit coordinates as `[latitude, longitude]`.
    pub location: Location,
    /// Allowed time windows during which service may start.
    pub time_windows: Vec<TimeWindow>,
    /// On-site service time, as an ISO-8601 duration or seconds.
    pub service_duration: String,
    /// Relative importance of servicing the visit (e.g. `LOW`, `MEDIUM`, `HIGH`).
    pub priority: String,
    /// Skills a vehicle must have to service this visit.
    pub required_skills: Vec<String>,
    /// When true, the existing assignment is locked and left unchanged by the solver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pinned: Option<bool>,
    /// Solution: id of the vehicle assigned to the visit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vehicle: Option<String>,
    /// Solution: planned arrival time at the visit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arrival_time: Option<String>,
    /// Solution: planned departure time from the visit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub departure_time: Option<String>,
    /// Solution: time service is planned to start.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_service_time: Option<String>,
    /// Solution: driving time in seconds from the previous stop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub driving_time_seconds_from_previous_standstill: Option<i64>,
}

/// A time window during which a vehicle is available.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Shift {
    /// Caller-supplied unique identifier for the shift.
    pub id: String,
    /// Earliest the shift may start.
    pub min_start_time: String,
    /// Latest the shift may end.
    pub max_end_time: String,
}

/// A time window for a visit.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TimeWindow {
    /// Earliest permitted service start, as an ISO-8601 timestamp.
    pub min_start_time: String,
    /// Latest permitted service end, as an ISO-8601 timestamp.
    pub max_end_time: String,
}

/// Solver configuration options.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SolverOptions {
    /// Maximum time the solver can spend (ISO-8601 duration, e.g. `PT5M`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spent_limit: Option<String>,
    /// Maximum time the solver can spend without improvement (ISO-8601 duration).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unimproved_spent_limit: Option<String>,
}

/// Response from starting a field service optimization.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FieldServiceStartResponse {
    /// Public PlanSolve job identifier - use it to poll status and fetch the solution.
    pub job_id: String,
    /// The underlying solver engine's job identifier, when exposed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub solver_job_id: Option<String>,
    /// Inline solver result as raw JSON, when available synchronously.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    /// Error message when the solve request could not be accepted or run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Response from getting field service optimization results.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FieldServiceResultResponse {
    /// Public PlanSolve job identifier, stamped client-side from the request.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub job_id: Option<String>,
    /// Extended vehicles with additional metadata.
    pub vehicles: Vec<ScheduledVehicle>,
    /// Extended visits with additional metadata.
    pub visits: Vec<ScheduledVisit>,
    /// Optimization score from the solver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub score: Option<String>,
    /// Total driving time in seconds across all vehicles.
    #[serde(default)]
    pub total_driving_time_seconds: i64,
    /// Weights in format `Xhard/Ymedium/Zsoft`.
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub weights: std::collections::HashMap<String, String>,
}

/// A vehicle in the optimization result.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledVehicle {
    /// Caller-supplied unique identifier for the vehicle.
    pub id: String,
    /// Human-readable vehicle/resource name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Home/depot coordinates as `[latitude, longitude]`.
    pub location: Location,
    /// Working shifts (time ranges) during which the vehicle is available.
    pub shifts: Vec<Shift>,
    /// Skills the vehicle provides, matched against each visit's required skills.
    pub skills: Vec<String>,
    /// Ordered ids of the visits assigned to this vehicle.
    pub visits: Vec<String>,
    /// Return time for each day, keyed by ISO-8601 date.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daily_return_times: Option<serde_json::Value>,
    /// Total driving time in seconds for this vehicle.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_driving_time_seconds: Option<i64>,
    /// Actual arrival time back at the depot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arrival_time: Option<String>,
    /// Time the vehicle departs its depot, as an ISO-8601 timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub departure_time: Option<String>,
}

/// A visit in the optimization result.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledVisit {
    /// Caller-supplied unique identifier for the visit.
    pub id: String,
    /// Human-readable visit name.
    pub name: String,
    /// Visit coordinates as `[latitude, longitude]`.
    pub location: Location,
    /// Allowed time windows during which service may start.
    pub time_windows: Vec<TimeWindow>,
    /// Service time in seconds. The solver serializes its `Duration` as a number
    /// (Jackson default), so the result carries seconds — not the ISO-8601 string the
    /// request uses. Matches the .NET SDK's `ScheduledVisit.ServiceDuration` (double).
    #[serde(default)]
    pub service_duration: f64,
    /// Relative importance of servicing the visit (e.g. `LOW`, `MEDIUM`, `HIGH`).
    pub priority: String,
    /// Skills a vehicle must have to service this visit.
    pub required_skills: Vec<String>,
    /// When true, the existing assignment is locked and left unchanged by the solver.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pinned: Option<bool>,
    // Assignment fields are null for a visit the solver could not schedule (e.g. an
    // unassigned visit when the solve is time-boxed). Nullable in the .NET reference
    // (C# strings), so they are `Option` here.
    /// Solution: id of the vehicle assigned to the visit.
    #[serde(default)]
    pub vehicle: Option<String>,
    /// Id of the previous visit in the route.
    #[serde(default)]
    pub previous_visit: Option<String>,
    /// Solution: planned arrival time at the visit.
    #[serde(default)]
    pub arrival_time: Option<String>,
    /// Solution: planned departure time from the visit.
    #[serde(default)]
    pub departure_time: Option<String>,
    /// Solution: time service is planned to start.
    #[serde(default)]
    pub start_service_time: Option<String>,
    /// Minimum start time for the visit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_start_time: Option<String>,
    /// Maximum end time for the visit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_end_time: Option<String>,
    /// Id of the previous visit on the same day.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_visit_same_day: Option<String>,
    /// Whether this is the first visit of the day.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub is_day_head: Option<bool>,
    /// Solution: driving time in seconds from the previous stop.
    #[serde(default)]
    pub driving_time_seconds_from_previous_standstill: i64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_construct_request() {
        let request = FieldServiceRequest {
            vehicles: vec![Vehicle {
                id: "1".into(),
                location: [51.52, -0.1],
                shifts: vec![Shift {
                    id: "full-day".into(),
                    min_start_time: "2024-01-15T08:00:00".into(),
                    max_end_time: "2024-01-15T18:00:00".into(),
                }],
                skills: vec!["English".into()],
                ..Default::default()
            }],
            visits: vec![Visit {
                id: "1".into(),
                name: "Task 1".into(),
                location: [51.51, -0.12],
                service_duration: "PT30M".into(),
                priority: "HIGH".into(),
                required_skills: vec!["English".into()],
                ..Default::default()
            }],
            ..Default::default()
        };
        assert_eq!(request.vehicles.len(), 1);
        assert_eq!(request.visits.len(), 1);
    }

    #[test]
    fn serializes_expected_keys() {
        let json = serde_json::to_string(&FieldServiceRequest::default()).unwrap();
        assert!(json.contains("\"vehicles\""));
        assert!(json.contains("\"visits\""));
        // Optional fields with no value are omitted.
        assert!(!json.contains("\"weights\""));
    }

    #[test]
    fn weights_accept_score_strings_and_arbitrary_keys() {
        // The server models weights as an open map of constraint-name -> score
        // string ("Xhard/Ymedium/Zsoft"). Any key (camelCase or the capitalized
        // PreferEarlierVisitDates) and any score string must round-trip unchanged.
        let json = r#"{
            "vehicles": [],
            "visits": [],
            "weights": {
                "minimizeTravelTime": "0hard/0medium/1soft",
                "noMissingSkills": "1hard/0medium/0soft",
                "PreferEarlierVisitDates": "0hard/0medium/20soft"
            }
        }"#;

        let request: FieldServiceRequest = serde_json::from_str(json).unwrap();
        let weights = request.weights.as_ref().expect("weights present");
        assert_eq!(weights["minimizeTravelTime"], "0hard/0medium/1soft");
        assert_eq!(weights["PreferEarlierVisitDates"], "0hard/0medium/20soft");

        // Round-trips back out as string values (not nested objects).
        let out = serde_json::to_string(&request).unwrap();
        assert!(out.contains("\"minimizeTravelTime\":\"0hard/0medium/1soft\""));
    }

    #[test]
    fn deserializes_result_response() {
        let json = r#"{
            "vehicles": [
                {"id": "1", "location": [51.52, -0.1], "shifts": [], "skills": ["English"], "visits": ["1"]}
            ],
            "visits": [
                {
                    "id": "1", "name": "Task 1", "location": [51.51, -0.12],
                    "timeWindows": [], "serviceDuration": 1800.0, "priority": "HIGH",
                    "requiredSkills": ["English"], "vehicle": "1", "previousVisit": null,
                    "arrivalTime": "2024-01-15T10:15:33", "departureTime": "2024-01-15T10:45:33",
                    "startServiceTime": "2024-01-15T10:15:33",
                    "drivingTimeSecondsFromPreviousStandstill": 933
                }
            ],
            "totalDrivingTimeSeconds": 933
        }"#;

        let result: FieldServiceResultResponse = serde_json::from_str(json).unwrap();
        assert_eq!(result.vehicles.len(), 1);
        assert_eq!(result.visits.len(), 1);
        let v = &result.visits[0];
        assert_eq!(v.vehicle.as_deref(), Some("1"));
        assert_eq!(v.arrival_time.as_deref(), Some("2024-01-15T10:15:33"));
        assert_eq!(v.start_service_time.as_deref(), Some("2024-01-15T10:15:33"));
        assert_eq!(v.driving_time_seconds_from_previous_standstill, 933);
        assert_eq!(result.total_driving_time_seconds, 933);
    }

    #[test]
    fn service_duration_is_numeric_seconds_in_results() {
        // The solver serializes its Duration as a number of seconds (Jackson default),
        // e.g. 3600.0 for a one-hour service — the result field is f64, not a string.
        let json = r#"{
            "vehicles": [],
            "visits": [
                {
                    "id": "1", "name": "Task 1", "location": [51.51, -0.12],
                    "timeWindows": [], "serviceDuration": 3600.0, "priority": "HIGH",
                    "requiredSkills": [], "vehicle": "1", "previousVisit": null,
                    "arrivalTime": "t", "departureTime": "t", "startServiceTime": "t",
                    "isDayHead": true, "previousVisitSameDay": null,
                    "drivingTimeSecondsFromPreviousStandstill": 0
                }
            ],
            "totalDrivingTimeSeconds": 0
        }"#;

        let result: FieldServiceResultResponse = serde_json::from_str(json).unwrap();
        assert_eq!(result.visits[0].service_duration, 3600.0);
        assert_eq!(result.visits[0].is_day_head, Some(true));
    }

    #[test]
    fn unassigned_visit_has_null_assignment_fields() {
        // A visit the solver couldn't schedule (e.g. a time-boxed solve) comes back with
        // null vehicle/arrival/departure/startService — must decode, not error.
        let json = r#"{
            "vehicles": [],
            "visits": [
                {
                    "id": "VISIT_010", "name": "unassigned", "location": [50.7, 3.6],
                    "timeWindows": [], "serviceDuration": 7200, "priority": "LOW",
                    "requiredSkills": [], "vehicle": null, "previousVisit": null,
                    "arrivalTime": null, "departureTime": null, "startServiceTime": null,
                    "minStartTime": null, "maxEndTime": null, "isDayHead": false,
                    "drivingTimeSecondsFromPreviousStandstill": 0
                }
            ],
            "totalDrivingTimeSeconds": 0
        }"#;

        let result: FieldServiceResultResponse = serde_json::from_str(json).unwrap();
        let v = &result.visits[0];
        assert_eq!(v.vehicle, None);
        assert_eq!(v.arrival_time, None);
        assert_eq!(v.start_service_time, None);
        assert_eq!(v.service_duration, 7200.0);
    }

    #[test]
    fn extended_vehicle_and_visit_carry_name_and_pinned() {
        // ExtendedVehicle has a `name`; ExtendedVisit has `pinned` — both must decode.
        let json = r#"{
            "vehicles": [
                {"id": "1", "name": "Van 1", "location": [51.52, -0.1], "shifts": [],
                 "skills": ["English"], "visits": ["1"], "arrivalTime": "t",
                 "totalDrivingTimeSeconds": 10}
            ],
            "visits": [
                {
                    "id": "1", "name": "Task 1", "location": [51.51, -0.12],
                    "timeWindows": [], "serviceDuration": 1800.0, "priority": "HIGH",
                    "requiredSkills": [], "pinned": true, "vehicle": "1",
                    "arrivalTime": "t", "departureTime": "t", "startServiceTime": "t",
                    "drivingTimeSecondsFromPreviousStandstill": 0
                }
            ],
            "totalDrivingTimeSeconds": 10
        }"#;

        let result: FieldServiceResultResponse = serde_json::from_str(json).unwrap();
        assert_eq!(result.vehicles[0].name.as_deref(), Some("Van 1"));
        assert_eq!(result.visits[0].pinned, Some(true));
    }
}