Skip to main content

clickupc_core/client/
time.rs

1//! Time entries (`/v2/team/{id}/time_entries…`).
2
3use serde_json::{json, Value};
4
5use super::{ClickUpClient, Query};
6use crate::{error::Result, model::TimeEntry, task_ref::TaskRef};
7
8#[derive(Debug, Clone, Default)]
9pub struct TimeQuery {
10    pub start: Option<i64>,
11    pub end: Option<i64>,
12    /// User ids; workspace owners/admins only.
13    pub assignees: Vec<String>,
14    pub space_id: Option<String>,
15    pub folder_id: Option<String>,
16    pub list_id: Option<String>,
17    pub task: Option<TaskRef>,
18    pub billable: Option<bool>,
19}
20
21#[derive(Debug, Clone, Default)]
22pub struct NewTimeEntry {
23    pub task: Option<TaskRef>,
24    pub start: i64,
25    pub duration: i64,
26    pub description: Option<String>,
27    pub billable: Option<bool>,
28}
29
30fn data<T: serde::de::DeserializeOwned>(v: Value) -> Result<T> {
31    let inner = match v {
32        Value::Object(mut m) if m.contains_key("data") => m.remove("data").unwrap_or(Value::Null),
33        other => other,
34    };
35    Ok(serde_json::from_value(inner)?)
36}
37
38impl ClickUpClient {
39    fn time_path(&self, suffix: &str) -> Result<String> {
40        Ok(format!(
41            "/v2/team/{}/time_entries{suffix}",
42            self.workspace_id()?
43        ))
44    }
45
46    /// `GET /v2/team/{id}/time_entries` — defaults to the last 30 days for
47    /// the authenticated user.
48    pub async fn time_entries(&self, query: &TimeQuery) -> Result<Vec<TimeEntry>> {
49        let mut q = Query::new()
50            .push_opt("start_date", query.start)
51            .push_opt("end_date", query.end)
52            .push_opt("space_id", query.space_id.as_ref())
53            .push_opt("folder_id", query.folder_id.as_ref())
54            .push_opt("list_id", query.list_id.as_ref())
55            .push_opt("is_billable", query.billable)
56            .push("include_location_names", "true");
57        if !query.assignees.is_empty() {
58            q = q.push("assignee", query.assignees.join(","));
59        }
60        if let Some(t) = &query.task {
61            q = q.push("task_id", t.path_id()).extend(self.task_query(t)?);
62        }
63        let v: Value = self.get(&self.time_path("")?, &q).await?;
64        data(v)
65    }
66
67    /// `POST /v2/team/{id}/time_entries`
68    pub async fn add_time_entry(&self, entry: &NewTimeEntry) -> Result<TimeEntry> {
69        let mut body = json!({ "start": entry.start, "duration": entry.duration });
70        if let Some(d) = &entry.description {
71            body["description"] = json!(d);
72        }
73        if let Some(b) = entry.billable {
74            body["billable"] = json!(b);
75        }
76        let mut q = Query::new();
77        if let Some(t) = &entry.task {
78            body["tid"] = json!(t.path_id());
79            q = self.task_query(t)?;
80        }
81        let v: Value = self.post(&self.time_path("")?, &q, body).await?;
82        data(v)
83    }
84
85    /// `POST /v2/team/{id}/time_entries/start`
86    pub async fn start_timer(
87        &self,
88        task: Option<&TaskRef>,
89        description: Option<&str>,
90    ) -> Result<TimeEntry> {
91        let mut body = json!({});
92        if let Some(d) = description {
93            body["description"] = json!(d);
94        }
95        let mut q = Query::new();
96        if let Some(t) = task {
97            body["tid"] = json!(t.path_id());
98            q = self.task_query(t)?;
99        }
100        let v: Value = self.post(&self.time_path("/start")?, &q, body).await?;
101        data(v)
102    }
103
104    /// `POST /v2/team/{id}/time_entries/stop`
105    pub async fn stop_timer(&self) -> Result<TimeEntry> {
106        let v: Value = self
107            .post(&self.time_path("/stop")?, &Query::new(), json!({}))
108            .await?;
109        data(v)
110    }
111
112    /// `GET /v2/team/{id}/time_entries/current` — `None` when no timer runs.
113    pub async fn current_timer(&self) -> Result<Option<TimeEntry>> {
114        let v: Value = self
115            .get(&self.time_path("/current")?, &Query::new())
116            .await?;
117        let entry: Option<Value> = data(v)?;
118        match entry {
119            Some(e) if e.get("id").is_some() => Ok(Some(serde_json::from_value(e)?)),
120            _ => Ok(None),
121        }
122    }
123
124    /// `DELETE /v2/team/{id}/time_entries/{entry}`
125    pub async fn delete_time_entry(&self, entry_id: &str) -> Result<()> {
126        self.delete(&self.time_path(&format!("/{entry_id}"))?, &Query::new())
127            .await?;
128        Ok(())
129    }
130}