Skip to main content

clickupc_core/client/
field.rs

1//! Custom fields: list per list, set / clear on a task, and conversion of
2//! human input (option names, dates, numbers) into API values.
3
4use serde::Deserialize;
5use serde_json::{json, Value};
6
7use super::{ClickUpClient, Query};
8use crate::{
9    error::{ClickUpError, Result},
10    model::CustomField,
11    resolve::suggest,
12    task_ref::TaskRef,
13};
14
15#[derive(Deserialize)]
16struct FieldsResp {
17    #[serde(default)]
18    fields: Vec<CustomField>,
19}
20
21/// A value ready for Set Custom Field Value.
22#[derive(Debug, Clone, PartialEq)]
23pub struct FieldValue {
24    pub value: Value,
25    pub value_options: Option<Value>,
26}
27
28impl ClickUpClient {
29    /// `GET /v2/list/{id}/field`
30    pub async fn list_fields(&self, list_id: &str) -> Result<Vec<CustomField>> {
31        Ok(self
32            .get::<FieldsResp>(&format!("/v2/list/{list_id}/field"), &Query::new())
33            .await?
34            .fields)
35    }
36
37    /// `POST /v2/task/{id}/field/{field_id}`
38    pub async fn set_field(
39        &self,
40        task: &TaskRef,
41        field_id: &str,
42        value: &FieldValue,
43    ) -> Result<()> {
44        let mut body = json!({ "value": value.value });
45        if let Some(opts) = &value.value_options {
46            body["value_options"] = opts.clone();
47        }
48        self.post::<Value>(
49            &format!("/v2/task/{}/field/{field_id}", task.path_id()),
50            &self.task_query(task)?,
51            body,
52        )
53        .await?;
54        Ok(())
55    }
56
57    /// `DELETE /v2/task/{id}/field/{field_id}`
58    pub async fn clear_field(&self, task: &TaskRef, field_id: &str) -> Result<()> {
59        self.delete(
60            &format!("/v2/task/{}/field/{field_id}", task.path_id()),
61            &self.task_query(task)?,
62        )
63        .await?;
64        Ok(())
65    }
66}
67
68fn option_id(field: &CustomField, input: &str) -> Result<String> {
69    let options = field.options();
70    let input = input.trim();
71    if let Some(o) = options
72        .iter()
73        .find(|o| o.id == input || o.name.eq_ignore_ascii_case(input))
74    {
75        return Ok(o.id.clone());
76    }
77    let names: Vec<String> = options.iter().map(|o| o.name.clone()).collect();
78    let mut suggestions = suggest(input, &names);
79    if suggestions.is_empty() {
80        suggestions = names;
81    }
82    Err(ClickUpError::resolve("option", input, suggestions))
83}
84
85fn parse_bool(raw: &str) -> Result<bool> {
86    match raw.trim().to_ascii_lowercase().as_str() {
87        "true" | "yes" | "y" | "1" | "on" | "checked" | "x" => Ok(true),
88        "false" | "no" | "n" | "0" | "off" | "unchecked" | "" => Ok(false),
89        other => Err(ClickUpError::Invalid(format!(
90            "'{other}' is not a checkbox value (use true/false)"
91        ))),
92    }
93}
94
95fn parse_number(raw: &str) -> Result<Value> {
96    let cleaned: String = raw
97        .trim()
98        .chars()
99        .filter(|c| c.is_ascii_digit() || matches!(c, '.' | '-'))
100        .collect();
101    let n: f64 = cleaned
102        .parse()
103        .map_err(|_| ClickUpError::Invalid(format!("'{raw}' is not a number")))?;
104    Ok(if n.fract() == 0.0 && n.abs() < 1e15 {
105        json!(n as i64)
106    } else {
107        json!(n)
108    })
109}
110
111/// Convert human input to an API value for every type that doesn't need a
112/// network lookup. `users` / `tasks` take already-resolved ids via
113/// [`relation_value`].
114pub fn convert_field_value(field: &CustomField, raw: &str, tz: Option<&str>) -> Result<FieldValue> {
115    let plain = |v: Value| FieldValue {
116        value: v,
117        value_options: None,
118    };
119    let raw_t = raw.trim();
120    Ok(match field.kind.as_str() {
121        "drop_down" => plain(json!(option_id(field, raw_t)?)),
122        "labels" => {
123            let ids = raw_t
124                .split(',')
125                .map(str::trim)
126                .filter(|s| !s.is_empty())
127                .map(|s| option_id(field, s))
128                .collect::<Result<Vec<_>>>()?;
129            plain(json!(ids))
130        }
131        "date" => {
132            let ms = crate::time::parse_when(raw_t, tz)?;
133            let has_time = crate::time::format_ms(ms, tz).contains(':');
134            FieldValue {
135                value: json!(ms),
136                value_options: has_time.then(|| json!({ "time": true })),
137            }
138        }
139        "number" | "currency" | "emoji" => plain(parse_number(raw_t)?),
140        "checkbox" => plain(json!(parse_bool(raw_t)?)),
141        "manual_progress" => plain(json!({ "current": parse_number(raw_t)? })),
142        "button" => plain(json!(true)),
143        "users" | "tasks" | "list_relationship" => {
144            return Err(ClickUpError::Invalid(format!(
145                "field '{}' ({}) needs resolved ids; use relation_value",
146                field.name, field.kind
147            )))
148        }
149        "formula" | "automatic_progress" | "rollup" => {
150            return Err(ClickUpError::Invalid(format!(
151                "field '{}' is computed by ClickUp ({}) and cannot be set",
152                field.name, field.kind
153            )))
154        }
155        "location" => {
156            return Err(ClickUpError::Invalid(
157                "location fields are not supported yet; use `clickupc api`".into(),
158            ))
159        }
160        // text, short_text, url, email, phone, and anything new.
161        _ => plain(json!(raw_t)),
162    })
163}
164
165/// `{ "add": [...], "rem": [...] }` for people / task relationship fields.
166pub fn relation_value(add: Vec<Value>, rem: Vec<Value>) -> FieldValue {
167    FieldValue {
168        value: json!({ "add": add, "rem": rem }),
169        value_options: None,
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn field(kind: &str, config: Value) -> CustomField {
178        CustomField {
179            id: "f".into(),
180            name: "F".into(),
181            kind: kind.into(),
182            type_config: config,
183            required: None,
184            value: None,
185        }
186    }
187
188    fn opts() -> Value {
189        json!({ "options": [
190            { "id": "u-low", "name": "Low", "orderindex": 0 },
191            { "id": "u-high", "name": "High", "orderindex": 1 }
192        ]})
193    }
194
195    fn conv(kind: &str, cfg: Value, raw: &str) -> Result<FieldValue> {
196        convert_field_value(&field(kind, cfg), raw, Some("UTC"))
197    }
198
199    #[test]
200    fn dropdown_by_name_or_id() {
201        assert_eq!(
202            conv("drop_down", opts(), "high").unwrap().value,
203            json!("u-high")
204        );
205        assert_eq!(
206            conv("drop_down", opts(), "u-low").unwrap().value,
207            json!("u-low")
208        );
209        match conv("drop_down", opts(), "Hgh") {
210            Err(ClickUpError::Resolve { suggestions, .. }) => {
211                assert_eq!(suggestions, vec!["High".to_string()])
212            }
213            other => panic!("{other:?}"),
214        }
215        match conv("drop_down", opts(), "zzz") {
216            Err(ClickUpError::Resolve { suggestions, .. }) => assert_eq!(suggestions.len(), 2),
217            other => panic!("{other:?}"),
218        }
219    }
220
221    #[test]
222    fn labels() {
223        let cfg =
224            json!({ "options": [{ "id": "a", "label": "API" }, { "id": "b", "label": "UI" }] });
225        assert_eq!(
226            conv("labels", cfg, "api, UI").unwrap().value,
227            json!(["a", "b"])
228        );
229    }
230
231    #[test]
232    fn dates() {
233        let v = conv("date", Value::Null, "2026-10-20").unwrap();
234        assert_eq!(v.value, json!(1_792_454_400_000i64));
235        assert_eq!(v.value_options, None);
236        let v = conv("date", Value::Null, "2026-10-20 14:00").unwrap();
237        assert_eq!(v.value_options, Some(json!({ "time": true })));
238    }
239
240    #[test]
241    fn numbers_money_checkbox_progress() {
242        assert_eq!(conv("number", Value::Null, "3").unwrap().value, json!(3));
243        assert_eq!(
244            conv("number", Value::Null, "2.5").unwrap().value,
245            json!(2.5)
246        );
247        assert_eq!(
248            conv("currency", Value::Null, "$1,200").unwrap().value,
249            json!(1200)
250        );
251        assert_eq!(conv("emoji", Value::Null, "4").unwrap().value, json!(4));
252        assert!(conv("number", Value::Null, "abc").is_err());
253        assert_eq!(
254            conv("checkbox", Value::Null, "yes").unwrap().value,
255            json!(true)
256        );
257        assert_eq!(
258            conv("checkbox", Value::Null, "false").unwrap().value,
259            json!(false)
260        );
261        assert!(conv("checkbox", Value::Null, "maybe").is_err());
262        assert_eq!(
263            conv("manual_progress", Value::Null, "40").unwrap().value,
264            json!({ "current": 40 })
265        );
266    }
267
268    #[test]
269    fn text_like_and_unsupported() {
270        for kind in ["text", "short_text", "url", "email", "phone"] {
271            assert_eq!(conv(kind, Value::Null, " hi ").unwrap().value, json!("hi"));
272        }
273        assert!(conv("formula", Value::Null, "1").is_err());
274        assert!(conv("users", Value::Null, "me").is_err());
275        assert_eq!(
276            relation_value(vec![json!(1)], vec![]).value,
277            json!({ "add": [1], "rem": [] })
278        );
279    }
280}