| 1 | use chrono::{DateTime, Duration, SecondsFormat, Utc}; |
| 2 | use serde::Deserialize; |
| 3 | use serde_json::{Value, json}; |
| 4 | use session::{ApiResponse, Method, Request, Scope}; |
| 5 | |
| 6 | use crate::client::Graph; |
| 7 | use crate::error::Result; |
| 8 | use crate::urls; |
| 9 | |
| 10 | const PROFILE_SCOPE: &str = "User.ReadBasic.All"; |
| 11 | const SCHEDULE_SCOPE: &str = "Calendars.Read.Shared"; |
| 12 | |
| 13 | #[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)] |
| 14 | #[serde(rename_all = "camelCase", default)] |
| 15 | pub struct UserProfile { |
| 16 | pub id: String, |
| 17 | pub display_name: Option<String>, |
| 18 | pub job_title: Option<String>, |
| 19 | pub department: Option<String>, |
| 20 | pub company_name: Option<String>, |
| 21 | pub office_location: Option<String>, |
| 22 | pub mail: Option<String>, |
| 23 | pub user_principal_name: Option<String>, |
| 24 | pub business_phones: Vec<String>, |
| 25 | pub mobile_phone: Option<String>, |
| 26 | } |
| 27 | |
| 28 | #[derive(Debug, Clone, Default, Deserialize, PartialEq, Eq)] |
| 29 | #[serde(rename_all = "camelCase", default)] |
| 30 | pub struct OrgPerson { |
| 31 | pub id: String, |
| 32 | pub display_name: Option<String>, |
| 33 | pub job_title: Option<String>, |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 37 | pub struct ProfileDetails { |
| 38 | pub user: UserProfile, |
| 39 | pub manager: Option<OrgPerson>, |
| 40 | pub direct_reports: Vec<OrgPerson>, |
| 41 | } |
| 42 | |
| 43 | impl Graph { |
| 44 | pub async fn user_profile(&self, user_id: &str) -> Result<ProfileDetails> { |
| 45 | let requests = [ |
| 46 | Request::get(urls::user_profile(user_id)), |
| 47 | Request::get(urls::user_manager(user_id)), |
| 48 | Request::get(urls::user_direct_reports(user_id)), |
| 49 | ]; |
| 50 | let mut answers = self |
| 51 | .session() |
| 52 | .batch(&requests, &Scope::graph(PROFILE_SCOPE)) |
| 53 | .await? |
| 54 | .into_iter(); |
| 55 | let (Some(profile), Some(manager), Some(reports)) = |
| 56 | (answers.next(), answers.next(), answers.next()) |
| 57 | else { |
| 58 | return Err(session::Error::api(0, &requests[0].url, Value::Null).into()); |
| 59 | }; |
| 60 | parse_profile_details(&requests[0].url, profile, manager, reports) |
| 61 | } |
| 62 | |
| 63 | pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> { |
| 64 | let body = schedule_body(mail, Utc::now()); |
| 65 | let answer = self |
| 66 | .session() |
| 67 | .send( |
| 68 | Request::with_body(Method::Post, urls::get_schedule(), body), |
| 69 | &Scope::graph(SCHEDULE_SCOPE), |
| 70 | ) |
| 71 | .await?; |
| 72 | Ok(parse_time_zone_name(&answer.body)) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | fn parse_profile_details( |
| 77 | url: &str, |
| 78 | profile: ApiResponse, |
| 79 | manager: ApiResponse, |
| 80 | reports: ApiResponse, |
| 81 | ) -> Result<ProfileDetails> { |
| 82 | if !profile.is_success() { |
| 83 | return Err(session::Error::api(profile.status, url, profile.body).into()); |
| 84 | } |
| 85 | let manager = manager |
| 86 | .is_success() |
| 87 | .then(|| serde_json::from_value(manager.body).ok()) |
| 88 | .flatten(); |
| 89 | let direct_reports = reports |
| 90 | .is_success() |
| 91 | .then(|| reports.body.get("value").cloned()) |
| 92 | .flatten() |
| 93 | .and_then(|value| serde_json::from_value(value).ok()) |
| 94 | .unwrap_or_default(); |
| 95 | Ok(ProfileDetails { |
| 96 | user: serde_json::from_value(profile.body)?, |
| 97 | manager, |
| 98 | direct_reports, |
| 99 | }) |
| 100 | } |
| 101 | |
| 102 | fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value { |
| 103 | let stamp = |moment: DateTime<Utc>| { |
| 104 | json!({ |
| 105 | "dateTime": moment.to_rfc3339_opts(SecondsFormat::Secs, true).trim_end_matches('Z'), |
| 106 | "timeZone": "UTC", |
| 107 | }) |
| 108 | }; |
| 109 | json!({ |
| 110 | "schedules": [mail], |
| 111 | "startTime": stamp(now), |
| 112 | "endTime": stamp(now + Duration::hours(1)), |
| 113 | "availabilityViewInterval": 60, |
| 114 | }) |
| 115 | } |
| 116 | |
| 117 | fn parse_time_zone_name(body: &Value) -> Option<String> { |
| 118 | let name = body |
| 119 | .pointer("/value/0/workingHours/timeZone/name")? |
| 120 | .as_str()? |
| 121 | .trim(); |
| 122 | (!name.is_empty()).then(|| name.to_owned()) |
| 123 | } |
| 124 | |
| 125 | #[cfg(test)] |
| 126 | mod tests { |
| 127 | use chrono::TimeZone; |
| 128 | |
| 129 | use super::*; |
| 130 | |
| 131 | fn answer(status: u16, body: Value) -> ApiResponse { |
| 132 | ApiResponse { |
| 133 | status, |
| 134 | body, |
| 135 | retry_after: None, |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | fn now() -> DateTime<Utc> { |
| 140 | Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap() |
| 141 | } |
| 142 | |
| 143 | #[test] |
| 144 | fn profile_details_parse_fields_manager_and_reports() { |
| 145 | let profile = json!({ |
| 146 | "id": "u1", |
| 147 | "displayName": "Ada Lovelace", |
| 148 | "jobTitle": "Engineer", |
| 149 | "department": null, |
| 150 | "mail": "ada@example.com", |
| 151 | "businessPhones": ["+49 1"], |
| 152 | "mobilePhone": null |
| 153 | }); |
| 154 | let manager = json!({"id": "m1", "displayName": "Grace", "jobTitle": "Lead"}); |
| 155 | let reports = json!({"value": [{"@odata.type": "#microsoft.graph.user", "id": "r1", "displayName": "Bob"}]}); |
| 156 | let details = parse_profile_details( |
| 157 | "u", |
| 158 | answer(200, profile), |
| 159 | answer(200, manager), |
| 160 | answer(200, reports), |
| 161 | ) |
| 162 | .unwrap(); |
| 163 | assert_eq!(details.user.display_name.as_deref(), Some("Ada Lovelace")); |
| 164 | assert_eq!(details.user.department, None); |
| 165 | assert_eq!(details.user.business_phones, vec!["+49 1"]); |
| 166 | assert_eq!(details.manager.unwrap().id, "m1"); |
| 167 | assert_eq!( |
| 168 | details.direct_reports[0].display_name.as_deref(), |
| 169 | Some("Bob") |
| 170 | ); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn missing_manager_and_failed_reports_do_not_fail_the_profile() { |
| 175 | let details = parse_profile_details( |
| 176 | "u", |
| 177 | answer(200, json!({"id": "u1"})), |
| 178 | answer(404, json!({})), |
| 179 | answer(403, json!({})), |
| 180 | ) |
| 181 | .unwrap(); |
| 182 | assert!(details.manager.is_none()); |
| 183 | assert!(details.direct_reports.is_empty()); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn a_failed_profile_is_an_error() { |
| 188 | let failed = parse_profile_details( |
| 189 | "u", |
| 190 | answer(404, json!({})), |
| 191 | answer(200, json!({"id": "m"})), |
| 192 | answer(200, json!({"value": []})), |
| 193 | ); |
| 194 | assert!(failed.is_err()); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn schedule_body_asks_one_hour_in_utc() { |
| 199 | let body = schedule_body("ada@example.com", now()); |
| 200 | assert_eq!(body["schedules"], json!(["ada@example.com"])); |
| 201 | assert_eq!( |
| 202 | body["startTime"], |
| 203 | json!({"dateTime": "2026-10-09T12:00:00", "timeZone": "UTC"}) |
| 204 | ); |
| 205 | assert_eq!(body["endTime"]["dateTime"], "2026-10-09T13:00:00"); |
| 206 | } |
| 207 | |
| 208 | #[test] |
| 209 | fn time_zone_comes_from_working_hours() { |
| 210 | let body = |
| 211 | json!({"value": [{"workingHours": {"timeZone": {"name": "W. Europe Standard Time"}}}]}); |
| 212 | assert_eq!( |
| 213 | parse_time_zone_name(&body).as_deref(), |
| 214 | Some("W. Europe Standard Time") |
| 215 | ); |
| 216 | assert_eq!(parse_time_zone_name(&json!({"value": [{}]})), None); |
| 217 | } |
| 218 | } |