Skip to main content

redmine_api/api/
custom_fields.rs

1//! Custom Fields Rest API Endpoint definitions
2//!
3//! [Redmine Documentation](https://www.redmine.org/projects/redmine/wiki/Rest_CustomFields)
4//!
5//! - [x] all custom fields endpoint
6
7use derive_builder::Builder;
8use reqwest::Method;
9use serde::Serialize;
10use std::borrow::Cow;
11
12use crate::api::issues::RoleFilter;
13use crate::api::projects::ProjectEssentials;
14use crate::api::roles::RoleEssentials;
15use crate::api::trackers::TrackerEssentials;
16use crate::api::versions::VersionStatusFilter;
17use crate::api::{Endpoint, NoPagination, ReturnsJsonResponse};
18
19/// Represents the types of objects that can be customized with customized types
20/// in Redmine
21#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum CustomizedType {
24    /// Redmine Issues
25    Issue,
26    /// Redmine Time Entries
27    TimeEntry,
28    /// Redmine Projects
29    Project,
30    /// Redmine Target Versions
31    Version,
32    /// Redmine Users
33    User,
34    /// Redmine Groups
35    Group,
36    /// Redmine Activities (in time tracking)
37    Activity,
38    /// Redmine Issue Priorities
39    IssuePriority,
40    /// Redmine Document Categories
41    DocumentCategory,
42}
43
44/// The data type or format of a custom field.
45#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum FieldFormat {
48    /// a Redmine user
49    User,
50    /// a Target version
51    Version,
52    /// a string
53    String,
54    /// a text block
55    Text,
56    /// a link
57    Link,
58    /// an integer
59    Int,
60    /// a floating point number
61    Float,
62    /// a date
63    Date,
64    /// a list of values
65    List,
66    /// a boolean
67    Bool,
68    /// an enumeration
69    Enumeration,
70    /// an attachment
71    Attachment,
72    /// a progress bar
73    Progressbar,
74}
75
76/// The style of the edit tag for a custom field.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum EditTagStyle {
79    /// Dropdown list style.
80    DropDown,
81    /// Checkbox style.
82    CheckBox,
83    /// Radio button style.
84    Radio,
85}
86
87impl serde::Serialize for EditTagStyle {
88    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
89    where
90        S: serde::Serializer,
91    {
92        match *self {
93            Self::DropDown => serializer.serialize_str(""),
94            Self::CheckBox => serializer.serialize_str("check_box"),
95            Self::Radio => serializer.serialize_str("radio"),
96        }
97    }
98}
99
100impl<'de> serde::Deserialize<'de> for EditTagStyle {
101    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
102    where
103        D: serde::Deserializer<'de>,
104    {
105        let s = String::deserialize(deserializer)?;
106        match s.as_str() {
107            "" => Ok(Self::DropDown),
108            "check_box" => Ok(Self::CheckBox),
109            "radio" => Ok(Self::Radio),
110            _ => Err(serde::de::Error::unknown_variant(
111                &s,
112                &["", "check_box", "radio"],
113            )),
114        }
115    }
116}
117
118/// How the default value of a date custom field is interpreted
119///
120/// Only returned by Redmine 7.0 and later, and only for custom fields with
121/// the `date` field format
122#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
123#[serde(rename_all = "snake_case")]
124pub enum DefaultValueMode {
125    /// the default value is a fixed date (e.g. `2026-01-01`)
126    FixedDate,
127    /// the default value is an offset in days relative to the current date
128    /// (e.g. `3` or `-1`)
129    DateOffset,
130}
131
132/// Possible values contain a value and a label
133#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub struct PossibleValue {
136    /// label for the value in a select box
137    pub label: String,
138    /// actual value
139    pub value: String,
140}
141
142/// a type for custom fields to use as an API return type
143///
144/// alternatively you can use your own type limited to the fields you need
145#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
146#[expect(
147    clippy::struct_excessive_bools,
148    reason = "field set mirrors the Redmine REST representation"
149)]
150pub struct CustomFieldDefinition {
151    /// numeric id
152    pub id: u64,
153    /// display name
154    pub name: String,
155    /// description
156    pub description: Option<String>,
157    /// is the field editable
158    pub editable: bool,
159    /// type of Redmine object this field is customizing
160    pub customized_type: CustomizedType,
161    /// data type of the field
162    pub field_format: FieldFormat,
163    /// a regular expression to constrain possible string values
164    pub regexp: Option<String>,
165    /// a minimum length for the field
166    pub min_length: Option<usize>,
167    /// a maximum length for the field
168    pub max_length: Option<usize>,
169    /// is this field required when creating/updating an object of the customized type
170    pub is_required: Option<bool>,
171    /// can this field be used as a filter
172    pub is_filter: Option<bool>,
173    /// will this field be indexed for the search
174    pub searchable: bool,
175    /// can this field be added more than once
176    pub multiple: bool,
177    /// default value for the field
178    ///
179    /// for date fields with a `default_value_mode` of
180    /// [`DefaultValueMode::DateOffset`] this is the raw offset in days
181    /// (e.g. `"3"`), not a date
182    pub default_value: Option<String>,
183    /// how the default value of a date field is interpreted
184    /// (only date fields, Redmine 7.0 and later)
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub default_value_mode: Option<DefaultValueMode>,
187    /// visibility of the custom field
188    pub visible: bool,
189    /// which roles can see the custom field
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub roles: Option<Vec<RoleEssentials>>,
192    /// limit possible values to an explicit list of values
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub possible_values: Option<Vec<PossibleValue>>,
195    /// this field is useable in these trackers
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub trackers: Option<Vec<TrackerEssentials>>,
198    /// this field is useable in these projects (None means all projects)
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub projects: Option<Vec<ProjectEssentials>>,
201    /// is the custom field for all projects
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub is_for_all: Option<bool>,
204    /// position of the custom field in the list
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub position: Option<u64>,
207    /// url pattern for the custom field
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub url_pattern: Option<String>,
210    /// text formatting for the custom field
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub text_formatting: Option<String>,
213    /// edit tag style for the custom field
214    #[serde(default, skip_serializing_if = "Option::is_none")]
215    pub edit_tag_style: Option<EditTagStyle>,
216    /// user role for the custom field
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub user_role: Option<RoleFilter>,
219    /// version status for the custom field
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub version_status: Option<VersionStatusFilter>,
222    /// extensions allowed for the custom field
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub extensions_allowed: Option<String>,
225    /// full width layout for the custom field
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub full_width_layout: Option<bool>,
228    /// thousands delimiter for the custom field
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub thousands_delimiter: Option<bool>,
231    /// ratio interval for the custom field
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub ratio_interval: Option<f32>,
234}
235
236/// a type for custom field essentials with values used in other Redmine
237/// objects (e.g. issues)
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct CustomFieldEssentialsWithValue {
240    /// numeric id
241    pub id: u64,
242    /// display name
243    pub name: String,
244    /// if this is true the value is serialized as an array
245    pub multiple: Option<bool>,
246    /// value
247    pub value: Option<Vec<String>>,
248}
249
250/// a type used to list all the custom field ids and names
251#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
252pub struct CustomFieldName {
253    /// numeric id
254    pub id: u64,
255    /// display name
256    pub name: String,
257}
258
259impl serde::Serialize for CustomFieldEssentialsWithValue {
260    #[expect(
261        clippy::arithmetic_side_effects,
262        reason = "field count is bounded by the four optional fields below"
263    )]
264    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
265    where
266        S: serde::Serializer,
267    {
268        use serde::ser::SerializeStruct as _;
269        let mut len = 2;
270        if self.multiple.is_some() {
271            len += 1;
272        };
273        if self.value.is_some() {
274            len += 1;
275        }
276        let mut state = serializer.serialize_struct("CustomFieldEssentialsWithValue", len)?;
277        state.serialize_field("id", &self.id)?;
278        state.serialize_field("name", &self.name)?;
279        if let Some(ref multiple) = self.multiple {
280            state.serialize_field("multiple", &multiple)?;
281            if let Some(ref value) = self.value {
282                state.serialize_field("value", &value)?;
283            } else {
284                let s: Option<Vec<String>> = None;
285                state.serialize_field("value", &s)?;
286            }
287        } else if let Some(ref value) = self.value {
288            match value.as_slice() {
289                [] => {
290                    let s: Option<String> = None;
291                    state.serialize_field("value", &s)?;
292                }
293                [s] => {
294                    state.serialize_field("value", &s)?;
295                }
296                values => {
297                    return Err(serde::ser::Error::custom(format!(
298                        "CustomFieldEssentialsWithValue multiple was set to false but value contained more than one value: {values:?}"
299                    )));
300                }
301            }
302        } else {
303            let s: Option<String> = None;
304            state.serialize_field("value", &s)?;
305        }
306        state.end()
307    }
308}
309
310impl<'de> serde::Deserialize<'de> for CustomFieldEssentialsWithValue {
311    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
312    where
313        D: serde::Deserializer<'de>,
314    {
315        /// the fields in the CustomFieldEssentialsWithValue type
316        #[derive(serde::Deserialize)]
317        #[serde(field_identifier, rename_all = "lowercase")]
318        enum Field {
319            /// the id field
320            Id,
321            /// the name field
322            Name,
323            /// the multiple field
324            Multiple,
325            /// the value field
326            Value,
327        }
328
329        /// visitor to deserialize CustomFieldEssentialsWithValue
330        struct CustomFieldVisitor;
331
332        impl<'de> serde::de::Visitor<'de> for CustomFieldVisitor {
333            type Value = CustomFieldEssentialsWithValue;
334
335            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
336                formatter.write_str("struct CustomFieldEssentialsWithValue")
337            }
338
339            fn visit_map<V>(self, mut map: V) -> Result<CustomFieldEssentialsWithValue, V::Error>
340            where
341                V: serde::de::MapAccess<'de>,
342            {
343                let mut id = None;
344                let mut name = None;
345                let mut multiple = None;
346                let mut string_value: Option<String> = None;
347                let mut vec_string_value: Option<Vec<String>> = None;
348                while let Some(key) = map.next_key()? {
349                    match key {
350                        Field::Id => {
351                            if id.is_some() {
352                                return Err(serde::de::Error::duplicate_field("id"));
353                            }
354                            id = Some(map.next_value()?);
355                        }
356                        Field::Name => {
357                            if name.is_some() {
358                                return Err(serde::de::Error::duplicate_field("name"));
359                            }
360                            name = Some(map.next_value()?);
361                        }
362                        Field::Multiple => {
363                            if multiple.is_some() {
364                                return Err(serde::de::Error::duplicate_field("multiple"));
365                            }
366                            multiple = Some(map.next_value()?);
367                        }
368                        Field::Value => {
369                            if string_value.is_some() {
370                                return Err(serde::de::Error::duplicate_field("value"));
371                            }
372                            if vec_string_value.is_some() {
373                                return Err(serde::de::Error::duplicate_field("value"));
374                            }
375                            if multiple == Some(true) {
376                                vec_string_value = Some(map.next_value()?);
377                            } else {
378                                string_value = map.next_value()?;
379                            }
380                        }
381                    }
382                }
383                let id = id.ok_or_else(|| serde::de::Error::missing_field("id"))?;
384                let name = name.ok_or_else(|| serde::de::Error::missing_field("name"))?;
385                match (multiple, string_value, vec_string_value) {
386                    (None, None, None) => Ok(CustomFieldEssentialsWithValue {
387                        id,
388                        name,
389                        multiple: None,
390                        value: None,
391                    }),
392                    (None, Some(s), None) => Ok(CustomFieldEssentialsWithValue {
393                        id,
394                        name,
395                        multiple: None,
396                        value: Some(vec![s]),
397                    }),
398                    (Some(true), None, Some(v)) => Ok(CustomFieldEssentialsWithValue {
399                        id,
400                        name,
401                        multiple: Some(true),
402                        value: Some(v),
403                    }),
404                    _ => Err(serde::de::Error::custom(
405                        "invalid combination of multiple and value",
406                    )),
407                }
408            }
409        }
410
411        /// list of fields of CustomFieldEssentialsWithValue to pass to deserialize_struct
412        const FIELDS: &[&str] = &["id", "name", "multiple", "value"];
413        deserializer.deserialize_struct(
414            "CustomFieldEssentialsWithValue",
415            FIELDS,
416            CustomFieldVisitor,
417        )
418    }
419}
420
421/// The endpoint for all custom fields
422#[derive(Debug, Clone, Builder)]
423#[builder(setter(strip_option))]
424#[expect(
425    clippy::empty_structs_with_brackets,
426    reason = "derive_builder requires named-field syntax"
427)]
428pub struct ListCustomFields {}
429
430impl ReturnsJsonResponse for ListCustomFields {}
431impl NoPagination for ListCustomFields {}
432
433impl ListCustomFields {
434    /// Create a builder for the endpoint.
435    #[must_use]
436    pub fn builder() -> ListCustomFieldsBuilder {
437        ListCustomFieldsBuilder::default()
438    }
439}
440
441impl Endpoint for ListCustomFields {
442    fn method(&self) -> Method {
443        Method::GET
444    }
445
446    fn endpoint(&self) -> Cow<'static, str> {
447        "custom_fields.json".into()
448    }
449}
450
451/// a custom field
452#[derive(Debug, Clone, Serialize, serde::Deserialize)]
453pub struct CustomField<'a> {
454    /// the custom field's id
455    pub id: u64,
456    /// is usually present in contexts where it is returned by Redmine but can be omitted when it is sent by the client
457    pub name: Option<Cow<'a, str>>,
458    /// the custom field's value
459    pub value: Cow<'a, str>,
460}
461
462/// helper struct for outer layers with a custom_fields field holding the inner data
463#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
464pub struct CustomFieldsWrapper<T> {
465    /// to parse JSON with custom_fields key
466    pub custom_fields: Vec<T>,
467}
468
469#[cfg(test)]
470mod test {
471    use super::*;
472    use pretty_assertions::assert_eq;
473    use std::error::Error;
474    use tracing_test::traced_test;
475
476    #[traced_test]
477    #[test]
478    fn test_list_custom_fields_no_pagination() -> Result<(), Box<dyn Error>> {
479        crate::api::test_helpers::setup()?;
480        let redmine = crate::api::Redmine::from_env(
481            reqwest::blocking::Client::builder()
482                .tls_backend_rustls()
483                .build()?,
484        )?;
485        let endpoint = ListCustomFields::builder().build()?;
486        redmine.json_response_body::<_, CustomFieldsWrapper<CustomFieldDefinition>>(&endpoint)?;
487        Ok(())
488    }
489
490    /// this tests if any of the results contain a field we are not deserializing
491    ///
492    /// this will only catch fields we missed if they are part of the response but
493    /// it is better than nothing
494    #[traced_test]
495    #[test]
496    fn test_completeness_custom_fields_type() -> Result<(), Box<dyn Error>> {
497        crate::api::test_helpers::setup()?;
498        let redmine = crate::api::Redmine::from_env(
499            reqwest::blocking::Client::builder()
500                .tls_backend_rustls()
501                .build()?,
502        )?;
503        let endpoint = ListCustomFields::builder().build()?;
504        let CustomFieldsWrapper {
505            custom_fields: values,
506        } = redmine.json_response_body::<_, CustomFieldsWrapper<serde_json::Value>>(&endpoint)?;
507        for value in values {
508            let o: CustomFieldDefinition = serde_json::from_value(value.clone())?;
509            let reserialized = serde_json::to_value(o)?;
510            assert_eq!(value, reserialized);
511        }
512        Ok(())
513    }
514}