concur-api 0.1.0

A Rust client for the SAP Concur REST APIs (v4 / v4.1).
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
422
423
424
425
426
427
428
429
430
431
432
433
434
//! SAP Concur Travel Request API v4.
//!
//! Covers Request, Workflow, Expected Expenses, and Allocations.

use crate::client::ConcurClient;
use crate::error::Result;
use crate::models::{Link, Money, OwnerRef, StatusRef};
use reqwest::Method;
use serde::{Deserialize, Serialize};

/// Request API.
pub struct RequestApi<'a> {
    client: &'a ConcurClient,
}

impl<'a> RequestApi<'a> {
    pub fn new(client: &'a ConcurClient) -> Self {
        Self { client }
    }

    /// List requests.
    pub async fn list(&self, query: &RequestListQuery) -> Result<RequestList> {
        let mut path = "/travelrequest/v4/requests".to_string();
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(v) = &query.view {
            params.push(("view".to_string(), v.clone()));
        }
        if let Some(v) = &query.user_id {
            params.push(("userId".to_string(), v.clone()));
        }
        if let Some(v) = query.start {
            params.push(("start".to_string(), v.to_string()));
        }
        if let Some(v) = query.limit {
            params.push(("limit".to_string(), v.to_string()));
        }
        if let Some(v) = &query.approved_before {
            params.push(("approvedBefore".to_string(), v.clone()));
        }
        if let Some(v) = &query.approved_after {
            params.push(("approvedAfter".to_string(), v.clone()));
        }
        if let Some(v) = &query.modified_before {
            params.push(("modifiedBefore".to_string(), v.clone()));
        }
        if let Some(v) = &query.modified_after {
            params.push(("modifiedAfter".to_string(), v.clone()));
        }
        if let Some(v) = &query.sort_field {
            params.push(("sortField".to_string(), v.clone()));
        }
        if let Some(v) = &query.sort_order {
            params.push(("sortOrder".to_string(), v.clone()));
        }
        if !params.is_empty() {
            path.push('?');
            path.push_str(
                &params
                    .iter()
                    .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
                    .collect::<Vec<_>>()
                    .join("&"),
            );
        }
        self.client
            .request(Method::GET, &path)
            .await?
            .send()
            .await?
            .json()
            .await
            .map_err(Into::into)
    }

    /// Get a request by UUID.
    pub async fn get(&self, request_uuid: &str, user_id: Option<&str>) -> Result<Request> {
        let mut path = format!("/travelrequest/v4/requests/{}", request_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .request(Method::GET, &path)
            .await?
            .send()
            .await?
            .json()
            .await
            .map_err(Into::into)
    }

    /// Create a new request.
    pub async fn create(&self, request: &Request, user_id: Option<&str>) -> Result<Request> {
        let mut path = "/travelrequest/v4/requests".to_string();
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        let req = self.client.request(Method::POST, &path).await?;
        let req = ConcurClient::with_json(req, request)?;
        self.client.execute(req).await
    }

    /// Update a request.
    pub async fn update(
        &self,
        request_uuid: &str,
        request: &Request,
        user_id: Option<&str>,
    ) -> Result<Request> {
        let mut path = format!("/travelrequest/v4/requests/{}", request_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        let req = self.client.request(Method::PUT, &path).await?;
        let req = ConcurClient::with_json(req, request)?;
        self.client.execute(req).await
    }

    /// Delete a request.
    pub async fn delete(&self, request_uuid: &str, user_id: Option<&str>) -> Result<()> {
        let mut path = format!("/travelrequest/v4/requests/{}", request_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .execute_unit(self.client.request(Method::DELETE, &path).await?)
            .await
    }
}

/// Request Workflow API.
pub struct RequestWorkflowApi<'a> {
    client: &'a ConcurClient,
}

impl<'a> RequestWorkflowApi<'a> {
    pub fn new(client: &'a ConcurClient) -> Self {
        Self { client }
    }

    /// Perform a workflow action: submit, approve, recall, sendback, cancel, close, reopen.
    pub async fn action(
        &self,
        request_uuid: &str,
        action: &str,
        comment: Option<&str>,
        user_id: Option<&str>,
        company_id: Option<&str>,
    ) -> Result<Request> {
        let mut path = format!("/travelrequest/v4/requests/{}/{}", request_uuid, action);
        let mut params: Vec<(String, String)> = Vec::new();
        if let Some(c) = comment {
            params.push(("comment".to_string(), c.to_string()));
        }
        if let Some(uid) = user_id {
            params.push(("userId".to_string(), uid.to_string()));
        }
        if let Some(cid) = company_id {
            params.push(("companyID".to_string(), cid.to_string()));
        }
        if !params.is_empty() {
            path.push('?');
            path.push_str(
                &params
                    .iter()
                    .map(|(k, v)| format!("{}={}", k, urlencoding::encode(v)))
                    .collect::<Vec<_>>()
                    .join("&"),
            );
        }
        let body = comment.map(|c| serde_json::json!({ "comment": c }));
        let req = self.client.request(Method::POST, &path).await?;
        let req = match body {
            Some(b) => ConcurClient::with_json(req, &b)?,
            None => req,
        };
        self.client.execute(req).await
    }
}

/// Request Expected Expenses API.
pub struct ExpectedExpensesApi<'a> {
    client: &'a ConcurClient,
}

impl<'a> ExpectedExpensesApi<'a> {
    pub fn new(client: &'a ConcurClient) -> Self {
        Self { client }
    }

    /// List expected expenses for a request.
    pub async fn list(
        &self,
        request_uuid: &str,
        user_id: Option<&str>,
    ) -> Result<Vec<ExpectedExpense>> {
        let mut path = format!("/travelrequest/v4/requests/{}/expenses", request_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .request(Method::GET, &path)
            .await?
            .send()
            .await?
            .json()
            .await
            .map_err(Into::into)
    }

    /// Create an expected expense.
    pub async fn create(
        &self,
        request_uuid: &str,
        expense: &ExpectedExpense,
        user_id: Option<&str>,
    ) -> Result<ExpectedExpense> {
        let mut path = format!("/travelrequest/v4/requests/{}/expenses", request_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        let req = self.client.request(Method::POST, &path).await?;
        let req = ConcurClient::with_json(req, expense)?;
        self.client.execute(req).await
    }

    /// Get an expected expense.
    pub async fn get(&self, expense_uuid: &str, user_id: Option<&str>) -> Result<ExpectedExpense> {
        let mut path = format!("/travelrequest/v4/expenses/{}", expense_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .request(Method::GET, &path)
            .await?
            .send()
            .await?
            .json()
            .await
            .map_err(Into::into)
    }

    /// Update an expected expense.
    pub async fn update(
        &self,
        expense_uuid: &str,
        expense: &ExpectedExpense,
        user_id: Option<&str>,
    ) -> Result<ExpectedExpense> {
        let mut path = format!("/travelrequest/v4/expenses/{}", expense_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        let req = self.client.request(Method::PUT, &path).await?;
        let req = ConcurClient::with_json(req, expense)?;
        self.client.execute(req).await
    }

    /// Delete an expected expense.
    pub async fn delete(&self, expense_uuid: &str, user_id: Option<&str>) -> Result<()> {
        let mut path = format!("/travelrequest/v4/expenses/{}", expense_uuid);
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .execute_unit(self.client.request(Method::DELETE, &path).await?)
            .await
    }
}

/// Request Allocations API.
pub struct RequestAllocationsApi<'a> {
    client: &'a ConcurClient,
}

impl<'a> RequestAllocationsApi<'a> {
    pub fn new(client: &'a ConcurClient) -> Self {
        Self { client }
    }

    /// Get an allocation.
    pub async fn get(
        &self,
        request_uuid: &str,
        allocation_uuid: &str,
        user_id: Option<&str>,
    ) -> Result<Vec<RequestAllocation>> {
        let mut path = format!(
            "/travelrequest/v4/requests/{}/allocations/{}",
            request_uuid, allocation_uuid
        );
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        self.client
            .request(Method::GET, &path)
            .await?
            .send()
            .await?
            .json()
            .await
            .map_err(Into::into)
    }

    /// Update an allocation.
    pub async fn update(
        &self,
        request_uuid: &str,
        allocation_uuid: &str,
        allocation: &RequestAllocation,
        user_id: Option<&str>,
    ) -> Result<Vec<RequestAllocation>> {
        let mut path = format!(
            "/travelrequest/v4/requests/{}/allocations/{}",
            request_uuid, allocation_uuid
        );
        if let Some(uid) = user_id {
            path.push_str(&format!("?userId={}", urlencoding::encode(uid)));
        }
        let req = self.client.request(Method::PUT, &path).await?;
        let req = ConcurClient::with_json(req, allocation)?;
        self.client.execute(req).await
    }
}

#[derive(Debug, Clone, Default)]
pub struct RequestListQuery {
    pub view: Option<String>,
    pub user_id: Option<String>,
    pub start: Option<u32>,
    pub limit: Option<u32>,
    pub approved_before: Option<String>,
    pub approved_after: Option<String>,
    pub modified_before: Option<String>,
    pub modified_after: Option<String>,
    pub sort_field: Option<String>,
    pub sort_order: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RequestList {
    pub data: Vec<Request>,
    pub operations: Option<Vec<Link>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Request {
    pub id: Option<String>,
    pub href: Option<String>,
    #[serde(rename = "requestId")]
    pub request_id: Option<String>,
    pub name: Option<String>,
    #[serde(rename = "businessPurpose")]
    pub business_purpose: Option<String>,
    pub comment: Option<String>,
    #[serde(rename = "approvalStatus")]
    pub approval_status: Option<StatusRef>,
    pub approved: Option<bool>,
    #[serde(rename = "pendingApproval")]
    pub pending_approval: Option<bool>,
    #[serde(rename = "canceledPostApproval")]
    pub canceled_post_approval: Option<bool>,
    pub closed: Option<bool>,
    pub owner: Option<OwnerRef>,
    #[serde(rename = "startDate")]
    pub start_date: Option<String>,
    #[serde(rename = "endDate")]
    pub end_date: Option<String>,
    #[serde(rename = "startTime")]
    pub start_time: Option<String>,
    #[serde(rename = "endTime")]
    pub end_time: Option<String>,
    #[serde(rename = "creationDate")]
    pub creation_date: Option<String>,
    #[serde(rename = "lastModified")]
    pub last_modified: Option<String>,
    #[serde(rename = "submitDate")]
    pub submit_date: Option<String>,
    #[serde(rename = "totalApprovedAmount")]
    pub total_approved_amount: Option<Money>,
    #[serde(rename = "totalPostedAmount")]
    pub total_posted_amount: Option<Money>,
    #[serde(rename = "totalRemainingAmount")]
    pub total_remaining_amount: Option<Money>,
    #[serde(rename = "mainDestination")]
    pub main_destination: Option<serde_json::Value>,
    pub policy: Option<serde_json::Value>,
    #[serde(rename = "travelAgency")]
    pub travel_agency: Option<serde_json::Value>,
    pub expenses: Option<Vec<serde_json::Value>>,
    pub operations: Option<Vec<Link>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ExpectedExpense {
    pub id: Option<String>,
    pub href: Option<String>,
    #[serde(rename = "expenseType")]
    pub expense_type: Option<serde_json::Value>,
    #[serde(rename = "transactionDate")]
    pub transaction_date: Option<String>,
    #[serde(rename = "transactionAmount")]
    pub transaction_amount: Option<Money>,
    #[serde(rename = "postedAmount")]
    pub posted_amount: Option<Money>,
    #[serde(rename = "approvedAmount")]
    pub approved_amount: Option<Money>,
    #[serde(rename = "remainingAmount")]
    pub remaining_amount: Option<Money>,
    #[serde(rename = "businessPurpose")]
    pub business_purpose: Option<String>,
    pub location: Option<serde_json::Value>,
    #[serde(rename = "tripData")]
    pub trip_data: Option<serde_json::Value>,
    pub allocations: Option<Vec<RequestAllocation>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RequestAllocation {
    #[serde(rename = "allocationId")]
    pub allocation_id: Option<String>,
    #[serde(rename = "expenseId")]
    pub expense_id: Option<String>,
    #[serde(rename = "allocationAmount")]
    pub allocation_amount: Option<Money>,
    #[serde(rename = "approvedAmount")]
    pub approved_amount: Option<Money>,
    #[serde(rename = "postedAmount")]
    pub posted_amount: Option<Money>,
    pub percentage: Option<i32>,
    #[serde(rename = "percentEdited")]
    pub percent_edited: Option<bool>,
    #[serde(rename = "systemAllocation")]
    pub system_allocation: Option<bool>,
}