Skip to main content

redmine_api/api/
my_account.rs

1//! My Account Rest API Endpoint definitions
2//!
3//! [Redmine Documentation](https://www.redmine.org/projects/redmine/wiki/Rest_MyAccount)
4//!
5//! - [x] my account endpoint
6
7use derive_builder::Builder;
8use reqwest::Method;
9use std::borrow::Cow;
10
11use crate::api::custom_fields::CustomFieldEssentialsWithValue;
12use crate::api::{Endpoint, NoPagination, ReturnsJsonResponse};
13
14/// a type for my account to use as an API return type
15///
16/// alternatively you can use your own type limited to the fields you need
17#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
18pub struct MyAccount {
19    /// numeric id
20    pub id: u64,
21    /// login name
22    pub login: String,
23    /// is this user an admin
24    pub admin: bool,
25    /// user's firstname
26    pub firstname: String,
27    /// user's lastname
28    pub lastname: String,
29    /// primary email of the user
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub mail: Option<String>,
32    /// The time when this user was created
33    #[serde(
34        serialize_with = "crate::api::serialize_rfc3339",
35        deserialize_with = "crate::api::deserialize_rfc3339"
36    )]
37    pub created_on: time::OffsetDateTime,
38    /// the time when this user last logged in
39    #[serde(
40        serialize_with = "crate::api::serialize_optional_rfc3339",
41        deserialize_with = "crate::api::deserialize_optional_rfc3339"
42    )]
43    pub last_login_on: Option<time::OffsetDateTime>,
44    /// the user's API key
45    pub api_key: String,
46    /// two-factor authentication scheme
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub twofa_scheme: Option<String>,
49    /// authentication source id
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub auth_source_id: Option<u64>,
52    /// whether the user must change password
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub must_change_passwd: Option<bool>,
55    /// the time when the password was last changed
56    #[serde(
57        default,
58        serialize_with = "crate::api::serialize_optional_rfc3339",
59        deserialize_with = "crate::api::deserialize_optional_rfc3339"
60    )]
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub passwd_changed_on: Option<time::OffsetDateTime>,
63    /// custom fields with values
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub custom_fields: Option<Vec<CustomFieldEssentialsWithValue>>,
66}
67
68/// Mail notification options for a user.
69#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum MailNotificationOption {
72    /// All events.
73    All,
74    /// Only for selected projects.
75    Selected,
76    /// Only for my events.
77    OnlyMyEvents,
78    /// Only for assigned issues.
79    OnlyAssigned,
80    /// Only for issues I own.
81    OnlyOwner,
82    /// Only for things I watch (Redmine 7.0 and later).
83    OnlyMyWatches,
84    /// No notifications.
85    None,
86}
87
88/// Comments sorting order.
89#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
90#[serde(rename_all = "snake_case")]
91pub enum CommentsSorting {
92    /// Ascending order.
93    Asc,
94    /// Descending order.
95    Desc,
96}
97
98/// Textarea font options.
99#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
100#[serde(rename_all = "snake_case")]
101pub enum TextareaFont {
102    /// Monospace font.
103    Monospace,
104    /// Proportional font.
105    Proportional,
106}
107
108/// Toolbar language options.
109#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum ToolbarLanguage {
112    /// C programming language.
113    C,
114    /// C++ programming language.
115    Cpp,
116    /// C# programming language.
117    Csharp,
118    /// CSS stylesheet language.
119    Css,
120    /// Diff format.
121    Diff,
122    /// Go programming language.
123    Go,
124    /// Groovy programming language.
125    Groovy,
126    /// HTML markup language.
127    Html,
128    /// Java programming language.
129    Java,
130    /// Javascript programming language.
131    Javascript,
132    /// Objective-C programming language.
133    Objc,
134    /// Perl programming language.
135    Perl,
136    /// PHP programming language.
137    Php,
138    /// Python programming language.
139    Python,
140    /// R programming language.
141    R,
142    /// Ruby programming language.
143    Ruby,
144    /// Sass stylesheet language.
145    Sass,
146    /// Scala programming language.
147    Scala,
148    /// Shell scripting language.
149    Shell,
150    /// SQL query language.
151    Sql,
152    /// Swift programming language.
153    Swift,
154    /// XML markup language.
155    Xml,
156    /// YAML data serialization language.
157    Yaml,
158}
159
160impl std::fmt::Display for ToolbarLanguage {
161    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162        match self {
163            Self::C => write!(f, "c"),
164            Self::Cpp => write!(f, "cpp"),
165            Self::Csharp => write!(f, "csharp"),
166            Self::Css => write!(f, "css"),
167            Self::Diff => write!(f, "diff"),
168            Self::Go => write!(f, "go"),
169            Self::Groovy => write!(f, "groovy"),
170            Self::Html => write!(f, "html"),
171            Self::Java => write!(f, "java"),
172            Self::Javascript => write!(f, "javascript"),
173            Self::Objc => write!(f, "objc"),
174            Self::Perl => write!(f, "perl"),
175            Self::Php => write!(f, "php"),
176            Self::Python => write!(f, "python"),
177            Self::R => write!(f, "r"),
178            Self::Ruby => write!(f, "ruby"),
179            Self::Sass => write!(f, "sass"),
180            Self::Scala => write!(f, "scala"),
181            Self::Shell => write!(f, "shell"),
182            Self::Sql => write!(f, "sql"),
183            Self::Swift => write!(f, "swift"),
184            Self::Xml => write!(f, "xml"),
185            Self::Yaml => write!(f, "yaml"),
186        }
187    }
188}
189
190/// Auto watch on actions.
191#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
192#[serde(rename_all = "snake_case")]
193pub enum AutoWatchAction {
194    /// Watch issues when created.
195    IssueCreated,
196    /// Watch issues when contributed to.
197    IssueContributedTo,
198}
199
200impl std::fmt::Display for AutoWatchAction {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        match self {
203            Self::IssueCreated => write!(f, "issue_created"),
204            Self::IssueContributedTo => write!(f, "issue_contributed_to"),
205        }
206    }
207}
208
209/// The endpoint to retrieve the current user's my account settings/data
210#[derive(Debug, Clone, Builder)]
211#[builder(setter(strip_option))]
212#[expect(
213    clippy::empty_structs_with_brackets,
214    reason = "derive_builder requires named-field syntax"
215)]
216pub struct GetMyAccount {}
217
218impl ReturnsJsonResponse for GetMyAccount {}
219impl NoPagination for GetMyAccount {}
220
221impl GetMyAccount {
222    /// Create a builder for the endpoint.
223    #[must_use]
224    pub fn builder() -> GetMyAccountBuilder {
225        GetMyAccountBuilder::default()
226    }
227}
228
229impl Endpoint for GetMyAccount {
230    fn method(&self) -> Method {
231        Method::GET
232    }
233
234    fn endpoint(&self) -> Cow<'static, str> {
235        "my/account.json".into()
236    }
237}
238
239/// The endpoint to update the current user's my account settings/data
240#[serde_with::skip_serializing_none]
241#[derive(Debug, Clone, Builder, serde::Serialize)]
242#[builder(setter(strip_option))]
243pub struct UpdateMyAccount<'a> {
244    /// user's firstname
245    #[builder(setter(into), default)]
246    firstname: Option<Cow<'a, str>>,
247    /// user's lastname
248    #[builder(setter(into), default)]
249    lastname: Option<Cow<'a, str>>,
250    /// primary email of the user
251    #[builder(setter(into), default)]
252    mail: Option<Cow<'a, str>>,
253    /// mail notification option
254    #[builder(default)]
255    mail_notification: Option<MailNotificationOption>,
256    /// project ids for which the user has explicitly turned mail notifications on
257    #[builder(default)]
258    notified_project_ids: Option<Vec<u64>>,
259    /// user's language
260    #[builder(setter(into), default)]
261    language: Option<Cow<'a, str>>,
262    /// hide mail address
263    #[builder(default)]
264    hide_mail: Option<bool>,
265    /// user's time zone
266    #[builder(setter(into), default)]
267    time_zone: Option<Cow<'a, str>>,
268    /// comments sorting order ('asc' or 'desc')
269    #[builder(default)]
270    comments_sorting: Option<CommentsSorting>,
271    /// warn on leaving unsaved changes
272    #[builder(default)]
273    warn_on_leaving_unsaved: Option<bool>,
274    /// no self notified
275    #[builder(default)]
276    no_self_notified: Option<bool>,
277    /// notify about high priority issues
278    #[builder(default)]
279    notify_about_high_priority_issues: Option<bool>,
280    /// textarea font ('monospace' or 'proportional')
281    #[builder(default)]
282    textarea_font: Option<TextareaFont>,
283    /// recently used projects
284    #[builder(default)]
285    recently_used_projects: Option<u64>,
286    /// history default tab
287    #[builder(setter(into), default)]
288    history_default_tab: Option<Cow<'a, str>>,
289    /// default issue query
290    #[builder(setter(into), default)]
291    default_issue_query: Option<Cow<'a, str>>,
292    /// default project query
293    #[builder(setter(into), default)]
294    default_project_query: Option<Cow<'a, str>>,
295    /// toolbar language options (comma-separated list of languages)
296    #[builder(default)]
297    toolbar_language_options: Option<Vec<ToolbarLanguage>>,
298    /// auto watch on (comma-separated list of actions)
299    #[builder(default)]
300    auto_watch_on: Option<Vec<AutoWatchAction>>,
301}
302
303impl<'a> UpdateMyAccount<'a> {
304    /// Create a builder for the endpoint.
305    #[must_use]
306    pub fn builder() -> UpdateMyAccountBuilder<'a> {
307        UpdateMyAccountBuilder::default()
308    }
309}
310
311impl Endpoint for UpdateMyAccount<'_> {
312    fn method(&self) -> Method {
313        Method::PUT
314    }
315
316    fn endpoint(&self) -> Cow<'static, str> {
317        "my/account.json".into()
318    }
319
320    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, crate::Error> {
321        use serde_json::json;
322        let mut user_params = serde_json::Map::new();
323        if let Some(ref firstname) = self.firstname {
324            user_params.insert("firstname".to_string(), json!(firstname));
325        }
326        if let Some(ref lastname) = self.lastname {
327            user_params.insert("lastname".to_string(), json!(lastname));
328        }
329        if let Some(ref mail) = self.mail {
330            user_params.insert("mail".to_string(), json!(mail));
331        }
332        if let Some(ref mail_notification) = self.mail_notification {
333            user_params.insert("mail_notification".to_string(), json!(mail_notification));
334        }
335        if let Some(ref notified_project_ids) = self.notified_project_ids {
336            user_params.insert(
337                "notified_project_ids".to_string(),
338                json!(notified_project_ids),
339            );
340        }
341        if let Some(ref language) = self.language {
342            user_params.insert("language".to_string(), json!(language));
343        }
344
345        let mut pref_params = serde_json::Map::new();
346        if let Some(hide_mail) = self.hide_mail {
347            pref_params.insert("hide_mail".to_string(), json!(hide_mail));
348        }
349        if let Some(ref time_zone) = self.time_zone {
350            pref_params.insert("time_zone".to_string(), json!(time_zone));
351        }
352        if let Some(ref comments_sorting) = self.comments_sorting {
353            pref_params.insert("comments_sorting".to_string(), json!(comments_sorting));
354        }
355        if let Some(warn_on_leaving_unsaved) = self.warn_on_leaving_unsaved {
356            pref_params.insert(
357                "warn_on_leaving_unsaved".to_string(),
358                json!(warn_on_leaving_unsaved),
359            );
360        }
361        if let Some(no_self_notified) = self.no_self_notified {
362            pref_params.insert("no_self_notified".to_string(), json!(no_self_notified));
363        }
364        if let Some(notify_about_high_priority_issues) = self.notify_about_high_priority_issues {
365            pref_params.insert(
366                "notify_about_high_priority_issues".to_string(),
367                json!(notify_about_high_priority_issues),
368            );
369        }
370        if let Some(ref textarea_font) = self.textarea_font {
371            pref_params.insert("textarea_font".to_string(), json!(textarea_font));
372        }
373        if let Some(recently_used_projects) = self.recently_used_projects {
374            pref_params.insert(
375                "recently_used_projects".to_string(),
376                json!(recently_used_projects),
377            );
378        }
379        if let Some(ref history_default_tab) = self.history_default_tab {
380            pref_params.insert(
381                "history_default_tab".to_string(),
382                json!(history_default_tab),
383            );
384        }
385        if let Some(ref default_issue_query) = self.default_issue_query {
386            pref_params.insert(
387                "default_issue_query".to_string(),
388                json!(default_issue_query),
389            );
390        }
391        if let Some(ref default_project_query) = self.default_project_query {
392            pref_params.insert(
393                "default_project_query".to_string(),
394                json!(default_project_query),
395            );
396        }
397        if let Some(ref toolbar_language_options) = self.toolbar_language_options {
398            pref_params.insert(
399                "toolbar_language_options".to_string(),
400                json!(
401                    toolbar_language_options
402                        .iter()
403                        .map(|e| e.to_string())
404                        .collect::<Vec<String>>()
405                        .join(",")
406                ),
407            );
408        }
409        if let Some(ref auto_watch_on) = self.auto_watch_on {
410            pref_params.insert(
411                "auto_watch_on".to_string(),
412                json!(
413                    auto_watch_on
414                        .iter()
415                        .map(|e| e.to_string())
416                        .collect::<Vec<String>>()
417                        .join(",")
418                ),
419            );
420        }
421
422        let mut root_map = serde_json::Map::new();
423        if !user_params.is_empty() {
424            root_map.insert("user".to_string(), serde_json::Value::Object(user_params));
425        }
426        if !pref_params.is_empty() {
427            root_map.insert("pref".to_string(), serde_json::Value::Object(pref_params));
428        }
429
430        if root_map.is_empty() {
431            Ok(None)
432        } else {
433            Ok(Some((
434                "application/json",
435                serde_json::to_vec(&serde_json::Value::Object(root_map))?,
436            )))
437        }
438    }
439}
440
441#[cfg(test)]
442mod test {
443    use super::*;
444    use crate::api::users::UserWrapper;
445    use pretty_assertions::assert_eq;
446    use std::error::Error;
447    use tracing_test::traced_test;
448
449    #[traced_test]
450    #[test]
451    fn test_get_my_account() -> Result<(), Box<dyn Error>> {
452        crate::api::test_helpers::setup()?;
453        let redmine = crate::api::Redmine::from_env(
454            reqwest::blocking::Client::builder()
455                .tls_backend_rustls()
456                .build()?,
457        )?;
458        let endpoint = GetMyAccount::builder().build()?;
459        redmine.json_response_body::<_, UserWrapper<MyAccount>>(&endpoint)?;
460        Ok(())
461    }
462
463    #[traced_test]
464    #[test]
465    fn test_update_my_account() -> Result<(), Box<dyn Error>> {
466        crate::api::test_helpers::setup()?;
467        let redmine = crate::api::Redmine::from_env(
468            reqwest::blocking::Client::builder()
469                .tls_backend_rustls()
470                .build()?,
471        )?;
472        let get_endpoint = GetMyAccount::builder().build()?;
473        let original_account: UserWrapper<MyAccount> = redmine.json_response_body(&get_endpoint)?;
474        let update_endpoint = UpdateMyAccount::builder()
475            .firstname("NewFirstName")
476            .build()?;
477        redmine.ignore_response_body(&update_endpoint)?;
478        let updated_account: UserWrapper<MyAccount> = redmine.json_response_body(&get_endpoint)?;
479        assert_eq!(updated_account.user.firstname, "NewFirstName");
480        let restore_endpoint = UpdateMyAccount::builder()
481            .firstname(original_account.user.firstname.as_str())
482            .build()?;
483        redmine.ignore_response_body(&restore_endpoint)?;
484        let restored_account: UserWrapper<MyAccount> = redmine.json_response_body(&get_endpoint)?;
485        assert_eq!(
486            restored_account.user.firstname,
487            original_account.user.firstname
488        );
489        Ok(())
490    }
491
492    /// this tests if any of the results contain a field we are not deserializing
493    ///
494    /// this will only catch fields we missed if they are part of the response but
495    /// it is better than nothing
496    #[traced_test]
497    #[test]
498    fn test_completeness_my_account_type() -> Result<(), Box<dyn Error>> {
499        crate::api::test_helpers::setup()?;
500        let redmine = crate::api::Redmine::from_env(
501            reqwest::blocking::Client::builder()
502                .tls_backend_rustls()
503                .build()?,
504        )?;
505        let endpoint = GetMyAccount::builder().build()?;
506        let UserWrapper { user: value } =
507            redmine.json_response_body::<_, UserWrapper<serde_json::Value>>(&endpoint)?;
508        let o: MyAccount = serde_json::from_value(value.clone())?;
509        let reserialized = serde_json::to_value(o)?;
510        assert_eq!(value, reserialized);
511        Ok(())
512    }
513}