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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
use std::collections::HashMap;
use std::env;
use std::error;
use std::fmt;
use std::fmt::Debug;
use std::sync::Arc;
use chrono::naive::NaiveDate;
use reqwest::{header, Client, Method, RequestBuilder, StatusCode, Url};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
const ENDPOINT: &str = "https://api.gusto.com/";
pub struct Gusto {
token: String,
refresh_token: String,
client_id: String,
client_secret: String,
redirect_uri: String,
client: Arc<Client>,
}
impl Gusto {
pub fn new<I, K, R, T, Q>(client_id: I, client_secret: K, redirect_uri: R, token: T, refresh_token: Q) -> Self
where
I: ToString,
K: ToString,
R: ToString,
T: ToString,
Q: ToString,
{
let client = Client::builder().build();
match client {
Ok(c) => {
let g = Gusto {
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
redirect_uri: redirect_uri.to_string(),
token: token.to_string(),
refresh_token: refresh_token.to_string(),
client: Arc::new(c),
};
if g.token.is_empty() || g.refresh_token.is_empty() {
println!("gusto consent URL: {}", g.user_consent_url());
}
g
}
Err(e) => panic!("creating client failed: {:?}", e),
}
}
pub fn new_from_env<T, R>(token: T, refresh_token: R) -> Self
where
T: ToString,
R: ToString,
{
let client_id = env::var("GUSTO_CLIENT_ID").unwrap();
let client_secret = env::var("GUSTO_CLIENT_SECRET").unwrap();
let redirect_uri = env::var("GUSTO_REDIRECT_URI").unwrap();
Gusto::new(client_id, client_secret, redirect_uri, token, refresh_token)
}
fn request<P>(&self, method: Method, path: P) -> RequestBuilder
where
P: ToString,
{
let base = Url::parse(ENDPOINT).unwrap();
let mut p = path.to_string();
if !p.starts_with('/') {
p = format!("/{}", p);
}
let url = base.join(&p).unwrap();
let bt = format!("Token {}", self.token);
let bearer = header::HeaderValue::from_str(&bt).unwrap();
let mut headers = header::HeaderMap::new();
headers.append(header::AUTHORIZATION, bearer);
headers.append(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"));
self.client.request(method, url).headers(headers)
}
pub fn user_consent_url(&self) -> String {
format!("{}oauth/authorize?client_id={}&response_type=code&redirect_uri={}", ENDPOINT, self.client_id, self.redirect_uri)
}
pub async fn refresh_access_token(&mut self) -> Result<AccessToken, APIError> {
let mut headers = header::HeaderMap::new();
headers.append(header::ACCEPT, header::HeaderValue::from_static("application/json"));
let params = [
("grant_type", "refresh_token"),
("refresh_token", &self.refresh_token),
("redirect_uri", &self.redirect_uri),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
let client = reqwest::Client::new();
let resp = client.post(&format!("{}oauth/token", ENDPOINT)).headers(headers).query(¶ms).send().await.unwrap();
let t: AccessToken = resp.json().await.unwrap();
self.token = t.access_token.to_string();
self.refresh_token = t.refresh_token.to_string();
Ok(t)
}
pub async fn get_access_token(&mut self, code: &str) -> Result<AccessToken, APIError> {
let mut headers = header::HeaderMap::new();
headers.append(header::ACCEPT, header::HeaderValue::from_static("application/json"));
let params = [
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", &self.redirect_uri),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
let client = reqwest::Client::new();
let resp = client.post(&format!("{}oauth/token", ENDPOINT)).headers(headers).query(¶ms).send().await.unwrap();
let t: AccessToken = resp.json().await.unwrap();
self.token = t.access_token.to_string();
self.refresh_token = t.refresh_token.to_string();
Ok(t)
}
pub async fn current_user(&self) -> Result<CurrentUser, APIError> {
let rb = self.request(Method::GET, "/v1/me");
let request = rb.build().unwrap();
let resp = self.client.execute(request).await.unwrap();
match resp.status() {
StatusCode::OK => (),
s => {
return Err(APIError {
status_code: s,
body: resp.text().await.unwrap(),
})
}
};
let result: CurrentUser = resp.json().await.unwrap();
Ok(result)
}
pub async fn list_employees(&self) -> Result<Vec<Employee>, APIError> {
let current_user = self.current_user().await.unwrap();
let mut company_id = String::new();
for (t, role) in current_user.roles {
if t == "payroll_admin" {
company_id = role.companies[0].id.to_string();
break;
}
}
let rb = self.request(Method::GET, &format!("/v1/companies/{}/employees", company_id));
let request = rb.build().unwrap();
let resp = self.client.execute(request).await.unwrap();
match resp.status() {
StatusCode::OK => (),
s => {
return Err(APIError {
status_code: s,
body: resp.text().await.unwrap(),
})
}
};
let result: Vec<Employee> = resp.json().await.unwrap();
Ok(result)
}
}
pub struct APIError {
pub status_code: StatusCode,
pub body: String,
}
impl fmt::Display for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: status code -> {}, body -> {}", self.status_code.to_string(), self.body)
}
}
impl fmt::Debug for APIError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "APIError: status code -> {}, body -> {}", self.status_code.to_string(), self.body)
}
}
impl error::Error for APIError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Employee {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub first_name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub middle_initial: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub last_name: String,
#[serde(default)]
pub company_id: u64,
#[serde(default)]
pub manager_id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub department: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub email: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub ssn: String,
pub date_of_birth: NaiveDate,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub jobs: Vec<Job>,
pub home_address: Address,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub garnishments: Vec<Garnishment>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub eligible_paid_time_off: Vec<PaidTimeOff>,
#[serde(default)]
pub onboarded: bool,
#[serde(default)]
pub terminated: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub terminations: Vec<Termination>,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Job {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub employee_id: u64,
#[serde(default)]
pub location_id: u64,
pub location: Location,
pub hire_date: NaiveDate,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub title: String,
#[serde(default)]
pub primary: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub rate: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub payment_unit: String,
#[serde(default)]
pub current_compensation_id: u64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub compensations: Vec<Compensation>,
}
#[derive(Debug, Default, JsonSchema, Clone, Serialize, Deserialize)]
pub struct Location {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub company_id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub phone_number: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub street_1: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub street_2: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub city: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub state: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub zip: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub country: String,
#[serde(default)]
pub active: bool,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Compensation {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub job_id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub rate: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub payment_unit: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub flsa_status: String,
pub effective_date: NaiveDate,
}
#[derive(Debug, Default, JsonSchema, Clone, Serialize, Deserialize)]
pub struct Address {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub employee_id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub street_1: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub street_2: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub city: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub state: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub zip: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub country: String,
#[serde(default)]
pub active: bool,
}
#[derive(Debug, Default, JsonSchema, Clone, Serialize, Deserialize)]
pub struct Garnishment {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub employee_id: u64,
#[serde(default)]
pub active: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub amount: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub description: String,
#[serde(default)]
pub court_ordered: bool,
#[serde(default)]
pub times: u32,
#[serde(default)]
pub recurring: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub annual_maximum: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub deduct_as_percentage: String,
}
#[derive(Debug, Default, JsonSchema, Clone, Serialize, Deserialize)]
pub struct PaidTimeOff {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub accrual_unit: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub accrual_period: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub accrual_rate: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub accrual_balance: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub maximum_accrual_balance: String,
#[serde(default)]
pub paid_at_termination: bool,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Termination {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub version: String,
#[serde(default)]
pub employee_id: u64,
#[serde(default)]
pub active: bool,
pub effective_date: NaiveDate,
#[serde(default)]
pub run_termination_payroll: bool,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct CurrentUser {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub email: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub roles: HashMap<String, Role>,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Role {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub companies: Vec<Company>,
}
#[derive(Debug, Clone, JsonSchema, Serialize, Deserialize)]
pub struct Company {
#[serde(default)]
pub id: u64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub trade_name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub ein: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub entity_type: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub company_status: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub location: Vec<Location>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub compensations: HashMap<String, Compensation>,
pub primary_signatory: Employee,
pub primary_payroll_admin: Employee,
}
#[derive(Debug, JsonSchema, Clone, Default, Serialize, Deserialize)]
pub struct AccessToken {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub access_token: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub token_type: String,
#[serde(default)]
pub expires_in: i64,
#[serde(default)]
pub x_refresh_token_expires_in: i64,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub refresh_token: String,
}