Skip to main content

clickupc_core/
ops.rs

1//! Operations that take human input (names, dates like `tomorrow`, option
2//! names) and turn them into API calls. Shared by the CLI and MCP server so
3//! both behave identically.
4
5use std::collections::BTreeMap;
6
7use serde::{Deserialize, Serialize};
8use serde_json::{json, Value};
9
10use crate::{
11    client::{CreateTask, FieldValue, MoveTask, UpdateTask},
12    error::{ClickUpError, Result},
13    filter::{parse_field_expr, FieldFilter, OrderBy, Range, TaskFilter},
14    model::{parse_priority, CustomField, Task, TimeEntry},
15    resolve::Resolver,
16    task_ref::TaskRef,
17    time::{format_ms, now_ms, parse_duration, parse_when},
18};
19
20/// Task search in human terms. Every name may also be an id.
21#[derive(Debug, Clone, Default, Deserialize, Serialize)]
22#[serde(default)]
23pub struct SearchInput {
24    pub lists: Vec<String>,
25    pub folders: Vec<String>,
26    pub spaces: Vec<String>,
27    pub statuses: Vec<String>,
28    pub include_closed: bool,
29    pub assignees: Vec<String>,
30    pub tags: Vec<String>,
31    pub due_before: Option<String>,
32    pub due_after: Option<String>,
33    pub overdue: bool,
34    pub created_before: Option<String>,
35    pub created_after: Option<String>,
36    pub updated_before: Option<String>,
37    pub updated_after: Option<String>,
38    pub done_before: Option<String>,
39    pub done_after: Option<String>,
40    /// `Name<op>value` expressions, e.g. `Severity=High`, `Points>=3`.
41    pub fields: Vec<String>,
42    pub task_types: Vec<String>,
43    pub parent: Option<String>,
44    pub subtasks: bool,
45    pub archived: Option<bool>,
46    pub order_by: Option<String>,
47    pub reverse: bool,
48    pub limit: Option<usize>,
49    pub include_markdown: bool,
50}
51
52fn when(input: &Option<String>, tz: Option<&str>) -> Result<Option<i64>> {
53    input.as_deref().map(|s| parse_when(s, tz)).transpose()
54}
55
56fn looks_like_uuid(s: &str) -> bool {
57    s.len() == 36 && s.chars().filter(|c| *c == '-').count() == 4
58}
59
60fn split_list(raw: &str) -> Vec<&str> {
61    raw.split(',')
62        .map(str::trim)
63        .filter(|s| !s.is_empty())
64        .collect()
65}
66
67async fn filter_scalar(r: &Resolver<'_>, field: &CustomField, raw: &str) -> Result<Value> {
68    let tz = r.client().timezone();
69    Ok(match field.kind.as_str() {
70        "users" => json!(r.member_id(raw).await?),
71        "drop_down" | "labels" | "date" | "number" | "currency" | "emoji" | "checkbox" => {
72            let probe = CustomField {
73                kind: if field.kind == "labels" {
74                    "drop_down".into()
75                } else {
76                    field.kind.clone()
77                },
78                ..field.clone()
79            };
80            crate::client::convert_field_value(&probe, raw, tz)?.value
81        }
82        _ => json!(raw),
83    })
84}
85
86async fn filter_value(
87    r: &Resolver<'_>,
88    field: &CustomField,
89    op: &str,
90    raw: Option<&str>,
91) -> Result<Value> {
92    let Some(raw) = raw else {
93        return Ok(Value::Null);
94    };
95    match op {
96        "RANGE" | "ANY" | "ALL" | "NOT ANY" | "NOT ALL" => {
97            let parts = split_list(raw);
98            if op == "RANGE" && parts.len() != 2 {
99                return Err(ClickUpError::Invalid(format!(
100                    "RANGE needs two values 'low,high', got '{raw}'"
101                )));
102            }
103            let mut out = Vec::new();
104            for p in parts {
105                out.push(filter_scalar(r, field, p).await?);
106            }
107            Ok(Value::Array(out))
108        }
109        _ => filter_scalar(r, field, raw).await,
110    }
111}
112
113/// Resolve names in `input` into a [`TaskFilter`].
114pub async fn build_filter(r: &Resolver<'_>, input: &SearchInput) -> Result<TaskFilter> {
115    let tz = r.client().timezone().map(str::to_string);
116    let tz = tz.as_deref();
117    let mut f = TaskFilter::default();
118    for l in &input.lists {
119        f.list_ids.push(r.list(l).await?.id);
120    }
121    for x in &input.folders {
122        f.folder_ids.push(r.folder(x).await?.id);
123    }
124    for x in &input.spaces {
125        f.space_ids.push(r.space(x).await?.id);
126    }
127    let single = f.single_list().map(str::to_string);
128    for s in &input.statuses {
129        f.statuses.push(match &single {
130            Some(list) => r.status(list, s).await?,
131            None => s.clone(),
132        });
133    }
134    f.include_closed = input.include_closed;
135    for a in &input.assignees {
136        f.assignees.push(r.member(a).await?.id);
137    }
138    f.tags = input.tags.clone();
139    f.due = Range {
140        gt: when(&input.due_after, tz)?,
141        lt: when(&input.due_before, tz)?,
142    };
143    if input.overdue {
144        f.due.lt = Some(f.due.lt.map_or(now_ms(), |lt| lt.min(now_ms())));
145    }
146    f.created = Range {
147        gt: when(&input.created_after, tz)?,
148        lt: when(&input.created_before, tz)?,
149    };
150    f.updated = Range {
151        gt: when(&input.updated_after, tz)?,
152        lt: when(&input.updated_before, tz)?,
153    };
154    f.done = Range {
155        gt: when(&input.done_after, tz)?,
156        lt: when(&input.done_before, tz)?,
157    };
158    for expr in &input.fields {
159        let (name, op, raw) = parse_field_expr(expr)?;
160        let field = if looks_like_uuid(&name) {
161            CustomField {
162                id: name.clone(),
163                name: name.clone(),
164                ..Default::default()
165            }
166        } else {
167            if f.list_ids.is_empty() {
168                return Err(ClickUpError::Invalid(format!(
169                    "field filter '{expr}' needs a list to resolve the field name (or pass the field id)"
170                )));
171            }
172            let mut found = None;
173            let mut last_err = None;
174            for list in &f.list_ids {
175                match r.field(list, &name).await {
176                    Ok(field) => {
177                        found = Some(field);
178                        break;
179                    }
180                    Err(e) => last_err = Some(e),
181                }
182            }
183            match (found, last_err) {
184                (Some(field), _) => field,
185                (None, Some(e)) => return Err(e),
186                (None, None) => unreachable!("list_ids is not empty"),
187            }
188        };
189        let value = filter_value(r, &field, &op, raw.as_deref()).await?;
190        f.custom_fields.push(FieldFilter {
191            field_id: field.id,
192            operator: op,
193            value,
194        });
195    }
196    for t in &input.task_types {
197        f.task_types.push(r.task_type(t).await?);
198    }
199    if let Some(p) = &input.parent {
200        let p: TaskRef = p.parse()?;
201        f.parent = Some(r.client().task_id(&p).await?);
202    }
203    f.subtasks = input.subtasks;
204    f.archived = input.archived;
205    f.order_by = input
206        .order_by
207        .as_deref()
208        .map(str::parse::<OrderBy>)
209        .transpose()?;
210    f.reverse = input.reverse;
211    f.limit = input.limit;
212    f.include_markdown = input.include_markdown;
213    Ok(f)
214}
215
216pub async fn search(r: &Resolver<'_>, input: &SearchInput) -> Result<Vec<Task>> {
217    let filter = build_filter(r, input).await?;
218    r.client().search_tasks(&filter).await
219}
220
221/// Fields shared by create and update. Strings are human input.
222#[derive(Debug, Clone, Default, Deserialize, Serialize)]
223#[serde(default)]
224pub struct TaskInput {
225    pub name: Option<String>,
226    /// Markdown.
227    pub description: Option<String>,
228    pub status: Option<String>,
229    /// urgent | high | normal | low | none
230    pub priority: Option<String>,
231    pub assignees: Vec<String>,
232    pub tags: Vec<String>,
233    /// Date input, or `none` to clear on update.
234    pub due: Option<String>,
235    pub start: Option<String>,
236    /// Duration like `2h`, or `none` to clear on update.
237    pub estimate: Option<String>,
238    pub points: Option<f64>,
239    pub parent: Option<String>,
240    pub task_type: Option<String>,
241    /// Custom field name or id → human value.
242    pub fields: BTreeMap<String, String>,
243    pub check_required: bool,
244}
245
246fn has_time(ms: i64, tz: Option<&str>) -> bool {
247    format_ms(ms, tz).contains(':')
248}
249
250fn is_none(s: &str) -> bool {
251    matches!(
252        s.trim().to_ascii_lowercase().as_str(),
253        "none" | "null" | "clear"
254    )
255}
256
257pub async fn build_create(
258    r: &Resolver<'_>,
259    list_id: &str,
260    input: &TaskInput,
261) -> Result<CreateTask> {
262    let tz = r.client().timezone().map(str::to_string);
263    let tz = tz.as_deref();
264    let name = input
265        .name
266        .clone()
267        .filter(|n| !n.trim().is_empty())
268        .ok_or_else(|| ClickUpError::Invalid("task name is required".into()))?;
269    let mut t = CreateTask {
270        name,
271        markdown_content: input.description.clone(),
272        tags: input.tags.clone(),
273        points: input.points,
274        check_required_custom_fields: input.check_required.then_some(true),
275        ..Default::default()
276    };
277    if let Some(s) = &input.status {
278        t.status = Some(r.status(list_id, s).await?);
279    }
280    if let Some(p) = &input.priority {
281        t.priority = parse_priority(p)?;
282    }
283    for a in &input.assignees {
284        t.assignees.push(r.member_id(a).await?);
285    }
286    if let Some(d) = &input.due {
287        let ms = parse_when(d, tz)?;
288        t.due_date = Some(ms);
289        t.due_date_time = Some(has_time(ms, tz));
290    }
291    if let Some(d) = &input.start {
292        let ms = parse_when(d, tz)?;
293        t.start_date = Some(ms);
294        t.start_date_time = Some(has_time(ms, tz));
295    }
296    if let Some(e) = &input.estimate {
297        t.time_estimate = Some(parse_duration(e)?);
298    }
299    if let Some(p) = &input.parent {
300        let p: TaskRef = p.parse()?;
301        t.parent = Some(r.client().task_id(&p).await?);
302    }
303    if let Some(tt) = &input.task_type {
304        t.custom_item_id = Some(r.task_type(tt).await?);
305    }
306    for (name, raw) in &input.fields {
307        let field = r.field(list_id, name).await?;
308        let v = r.field_value(&field, raw).await?;
309        t.custom_fields
310            .push(json!({ "id": field.id, "value": v.value }));
311    }
312    Ok(t)
313}
314
315pub async fn create_task(r: &Resolver<'_>, list: &str, input: &TaskInput) -> Result<Task> {
316    let list = r.list(list).await?;
317    let body = build_create(r, &list.id, input).await?;
318    r.client().create_task(&list.id, &body).await
319}
320
321/// Update in human terms; `assignees` in [`TaskInput`] is ignored here —
322/// use `assign` / `unassign`.
323#[derive(Debug, Clone, Default, Deserialize, Serialize)]
324#[serde(default)]
325pub struct UpdateInput {
326    #[serde(flatten)]
327    pub task: TaskInput,
328    pub assign: Vec<String>,
329    pub unassign: Vec<String>,
330    pub watch: Vec<String>,
331    pub unwatch: Vec<String>,
332    pub archived: Option<bool>,
333    pub clear_fields: Vec<String>,
334}
335
336#[derive(Debug, Clone)]
337pub struct UpdatePlan {
338    pub update: UpdateTask,
339    pub set_fields: Vec<(CustomField, FieldValue)>,
340    pub clear_fields: Vec<CustomField>,
341}
342
343#[derive(Debug, Clone, Serialize)]
344pub struct FieldResult {
345    pub field: String,
346    pub ok: bool,
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub error: Option<String>,
349}
350
351#[derive(Debug, Clone, Serialize)]
352pub struct UpdateOutcome {
353    pub task: Task,
354    pub fields: Vec<FieldResult>,
355}
356
357pub async fn build_update(
358    r: &Resolver<'_>,
359    task: &TaskRef,
360    input: &UpdateInput,
361) -> Result<UpdatePlan> {
362    let tz = r.client().timezone().map(str::to_string);
363    let tz = tz.as_deref();
364    let t = &input.task;
365    let needs_list = t.status.is_some() || !t.fields.is_empty() || !input.clear_fields.is_empty();
366    let list_id = if needs_list {
367        let current = r.client().get_task(task, false, false).await?;
368        Some(
369            current
370                .list
371                .map(|l| l.id)
372                .ok_or_else(|| ClickUpError::Invalid("task has no home list".into()))?,
373        )
374    } else {
375        None
376    };
377    let mut u = UpdateTask {
378        name: t.name.clone(),
379        markdown_content: t.description.clone(),
380        points: t.points,
381        archived: input.archived,
382        ..Default::default()
383    };
384    if let (Some(s), Some(list)) = (&t.status, &list_id) {
385        u.status = Some(r.status(list, s).await?);
386    }
387    if let Some(p) = &t.priority {
388        u.priority = Some(parse_priority(p)?);
389    }
390    if let Some(d) = &t.due {
391        if is_none(d) {
392            u.due_date = Some(None);
393        } else {
394            let ms = parse_when(d, tz)?;
395            u.due_date = Some(Some(ms));
396            u.due_date_time = Some(has_time(ms, tz));
397        }
398    }
399    if let Some(d) = &t.start {
400        if is_none(d) {
401            u.start_date = Some(None);
402        } else {
403            let ms = parse_when(d, tz)?;
404            u.start_date = Some(Some(ms));
405            u.start_date_time = Some(has_time(ms, tz));
406        }
407    }
408    if let Some(e) = &t.estimate {
409        u.time_estimate = Some(if is_none(e) {
410            None
411        } else {
412            Some(parse_duration(e)?)
413        });
414    }
415    if let Some(p) = &t.parent {
416        let p: TaskRef = p.parse()?;
417        u.parent = Some(r.client().task_id(&p).await?);
418    }
419    if let Some(tt) = &t.task_type {
420        u.custom_item_id = Some(r.task_type(tt).await?);
421    }
422    for m in &input.assign {
423        u.assignees_add.push(r.member_id(m).await?);
424    }
425    for m in &input.unassign {
426        u.assignees_rem.push(r.member_id(m).await?);
427    }
428    for m in &input.watch {
429        u.watchers_add.push(r.member_id(m).await?);
430    }
431    for m in &input.unwatch {
432        u.watchers_rem.push(r.member_id(m).await?);
433    }
434    let mut set_fields = Vec::new();
435    let mut clear_fields = Vec::new();
436    if let Some(list) = &list_id {
437        for (name, raw) in &t.fields {
438            let field = r.field(list, name).await?;
439            let v = r.field_value(&field, raw).await?;
440            set_fields.push((field, v));
441        }
442        for name in &input.clear_fields {
443            clear_fields.push(r.field(list, name).await?);
444        }
445    }
446    Ok(UpdatePlan {
447        update: u,
448        set_fields,
449        clear_fields,
450    })
451}
452
453/// PUT the task (if anything changed), then set / clear each custom field
454/// separately and report per-field results.
455pub async fn apply_update(
456    r: &Resolver<'_>,
457    task: &TaskRef,
458    plan: &UpdatePlan,
459) -> Result<UpdateOutcome> {
460    let c = r.client();
461    let mut updated = if plan.update.is_empty() {
462        None
463    } else {
464        Some(c.update_task(task, &plan.update).await?)
465    };
466    let mut fields = Vec::new();
467    for (field, value) in &plan.set_fields {
468        let res = c.set_field(task, &field.id, value).await;
469        fields.push(FieldResult {
470            field: field.name.clone(),
471            ok: res.is_ok(),
472            error: res.err().map(|e| e.to_string()),
473        });
474    }
475    for field in &plan.clear_fields {
476        let res = c.clear_field(task, &field.id).await;
477        fields.push(FieldResult {
478            field: field.name.clone(),
479            ok: res.is_ok(),
480            error: res.err().map(|e| e.to_string()),
481        });
482    }
483    if updated.is_none() || !fields.is_empty() {
484        updated = Some(c.get_task(task, false, false).await?);
485    }
486    Ok(UpdateOutcome {
487        task: updated.expect("set above"),
488        fields,
489    })
490}
491
492pub async fn update_task(
493    r: &Resolver<'_>,
494    task: &TaskRef,
495    input: &UpdateInput,
496) -> Result<UpdateOutcome> {
497    let plan = build_update(r, task, input).await?;
498    apply_update(r, task, &plan).await
499}
500
501/// Validate against the task's list, then set.
502pub async fn set_status(r: &Resolver<'_>, task: &TaskRef, status: &str) -> Result<Task> {
503    let current = r.client().get_task(task, false, false).await?;
504    let list = current
505        .list
506        .ok_or_else(|| ClickUpError::Invalid("task has no home list".into()))?;
507    let canonical = r.status(&list.id, status).await?;
508    r.client().set_status(task, &canonical).await
509}
510
511/// Move to a new home list. `status_map` maps old status name → new status
512/// name. When the current status doesn't exist in the target list and no
513/// mapping covers it, returns `Resolve { kind: "target status", .. }` whose
514/// suggestions are the target list's statuses.
515pub async fn move_task(
516    r: &Resolver<'_>,
517    task: &TaskRef,
518    list: &str,
519    status_map: &BTreeMap<String, String>,
520    move_fields: bool,
521) -> Result<Value> {
522    let c = r.client();
523    let current = c.get_task(task, false, false).await?;
524    let target = r.list(list).await?;
525    let target_list = r.list_detail(&target.id).await?;
526    let current_status = current.status.status.clone();
527    let exists = target_list
528        .statuses
529        .iter()
530        .any(|s| s.status.eq_ignore_ascii_case(&current_status));
531    let mut opts = MoveTask {
532        move_custom_fields: move_fields.then_some(true),
533        status_mappings: vec![],
534    };
535    let mapped = status_map
536        .iter()
537        .find(|(k, _)| k.eq_ignore_ascii_case(&current_status))
538        .map(|(_, v)| v.clone());
539    match (exists, mapped) {
540        (_, Some(new_name)) => {
541            let dest = target_list
542                .statuses
543                .iter()
544                .find(|s| s.status.eq_ignore_ascii_case(&new_name))
545                .ok_or_else(|| {
546                    ClickUpError::resolve(
547                        "target status",
548                        new_name.clone(),
549                        target_list
550                            .statuses
551                            .iter()
552                            .map(|s| s.status.clone())
553                            .collect(),
554                    )
555                })?;
556            let (Some(src_id), Some(dst_id)) = (current.status.id.clone(), dest.id.clone()) else {
557                return Err(ClickUpError::Invalid(
558                    "status ids missing in API response; cannot build a status mapping".into(),
559                ));
560            };
561            opts.status_mappings.push((src_id, dst_id));
562        }
563        (true, None) => {}
564        (false, None) => {
565            return Err(ClickUpError::resolve(
566                "target status",
567                current_status,
568                target_list
569                    .statuses
570                    .iter()
571                    .map(|s| s.status.clone())
572                    .collect(),
573            ))
574        }
575    }
576    c.move_task(task, &target.id, &opts).await?;
577    Ok(json!({ "task": current.id, "list": { "id": target.id, "name": target.name } }))
578}
579
580/// Compact task view used for LLM output and batch results.
581pub fn task_summary(t: &Task, tz: Option<&str>) -> Value {
582    json!({
583        "id": t.id,
584        "custom_id": t.custom_id,
585        "name": t.name,
586        "status": t.status.status,
587        "priority": t.priority_name(),
588        "assignees": t.assignees.iter().map(|u| json!({ "id": u.id, "username": u.username })).collect::<Vec<_>>(),
589        "due": t.due_date.map(|ms| json!({ "ms": ms, "iso": crate::time::to_iso(ms, tz) })),
590        "list": t.list.as_ref().map(|l| json!({ "id": l.id, "name": l.name })),
591        "url": t.url,
592    })
593}
594
595#[derive(Debug, Clone, Default, Serialize)]
596pub struct Standup {
597    pub user: String,
598    pub since: i64,
599    pub closed: Vec<Task>,
600    pub updated: Vec<Task>,
601    pub in_progress: Vec<Task>,
602    pub due_soon: Vec<Task>,
603    pub overdue: Vec<Task>,
604}
605
606const DAY_MS: i64 = 86_400_000;
607
608/// My tasks closed / updated since, in progress, due within 3 days, overdue.
609pub async fn standup(r: &Resolver<'_>, since: &str, user: Option<&str>) -> Result<Standup> {
610    let tz = r.client().timezone().map(str::to_string);
611    let since_ms = parse_when(since, tz.as_deref())?;
612    let me = r.member(user.unwrap_or("me")).await?;
613    let c = r.client();
614    let recent = c
615        .search_tasks(&TaskFilter {
616            assignees: vec![me.id.clone()],
617            include_closed: true,
618            updated: Range {
619                gt: Some(since_ms),
620                lt: None,
621            },
622            subtasks: true,
623            limit: Some(500),
624            ..Default::default()
625        })
626        .await?;
627    let open = c
628        .search_tasks(&TaskFilter {
629            assignees: vec![me.id.clone()],
630            subtasks: true,
631            limit: Some(500),
632            ..Default::default()
633        })
634        .await?;
635    let now = now_ms();
636    let mut out = Standup {
637        user: me.display(),
638        since: since_ms,
639        ..Default::default()
640    };
641    for t in recent {
642        if t.status.is_closed() || t.date_closed.is_some_and(|d| d >= since_ms) {
643            out.closed.push(t);
644        } else {
645            out.updated.push(t);
646        }
647    }
648    for t in open {
649        if t.status.is_closed() {
650            continue;
651        }
652        if t.due_date.is_some_and(|d| d < now) {
653            out.overdue.push(t.clone());
654        } else if t.due_date.is_some_and(|d| d <= now + 3 * DAY_MS) {
655            out.due_soon.push(t.clone());
656        }
657        if t.status.kind.as_deref() != Some("open") {
658            out.in_progress.push(t);
659        }
660    }
661    Ok(out)
662}
663
664#[derive(Debug, Clone, Default, Serialize)]
665pub struct ListSummary {
666    pub list: String,
667    pub total: usize,
668    pub overdue: usize,
669    pub by_status: BTreeMap<String, usize>,
670    pub by_assignee: BTreeMap<String, usize>,
671}
672
673pub async fn list_summary(r: &Resolver<'_>, list: &str) -> Result<ListSummary> {
674    let list = r.list(list).await?;
675    let tasks = r
676        .client()
677        .search_tasks(&TaskFilter {
678            list_ids: vec![list.id.clone()],
679            include_closed: true,
680            subtasks: true,
681            ..Default::default()
682        })
683        .await?;
684    let now = now_ms();
685    let mut s = ListSummary {
686        list: list.path(),
687        total: tasks.len(),
688        ..Default::default()
689    };
690    for t in &tasks {
691        *s.by_status.entry(t.status.status.clone()).or_default() += 1;
692        if t.assignees.is_empty() {
693            *s.by_assignee.entry("(unassigned)".into()).or_default() += 1;
694        }
695        for a in &t.assignees {
696            *s.by_assignee.entry(a.display()).or_default() += 1;
697        }
698        if !t.status.is_closed() && t.due_date.is_some_and(|d| d < now) {
699            s.overdue += 1;
700        }
701    }
702    Ok(s)
703}
704
705#[derive(Debug, Clone, Copy, PartialEq)]
706pub enum ReportBy {
707    Task,
708    List,
709    Day,
710}
711
712impl std::str::FromStr for ReportBy {
713    type Err = ClickUpError;
714    fn from_str(s: &str) -> Result<Self> {
715        match s.trim().to_ascii_lowercase().as_str() {
716            "task" => Ok(Self::Task),
717            "list" => Ok(Self::List),
718            "day" => Ok(Self::Day),
719            other => Err(ClickUpError::Invalid(format!(
720                "unknown grouping '{other}' (use task, list or day)"
721            ))),
722        }
723    }
724}
725
726/// Client-side aggregation of time entries → (group, total ms), largest first.
727pub fn time_report(entries: &[TimeEntry], by: ReportBy, tz: Option<&str>) -> Vec<(String, i64)> {
728    let now = now_ms();
729    let mut totals: BTreeMap<String, i64> = BTreeMap::new();
730    for e in entries {
731        let key = match by {
732            ReportBy::Task => match (e.task_id(), e.task_name()) {
733                (Some(id), Some(name)) => format!("{id} {name}"),
734                (Some(id), None) => id,
735                _ => "(no task)".into(),
736            },
737            ReportBy::List => e
738                .task_location
739                .as_ref()
740                .and_then(|l| l.get("list_name"))
741                .and_then(Value::as_str)
742                .unwrap_or("(no list)")
743                .to_string(),
744            ReportBy::Day => e
745                .start
746                .map(|ms| format_ms(ms, tz).chars().take(10).collect())
747                .unwrap_or_else(|| "(unknown)".into()),
748        };
749        *totals.entry(key).or_default() += e.effective_ms(now);
750    }
751    let mut out: Vec<(String, i64)> = totals.into_iter().collect();
752    out.sort_by_key(|a| std::cmp::Reverse(a.1));
753    out
754}
755
756/// One entry of a batch file / `clickup_task_batch` call.
757#[derive(Debug, Clone, Deserialize, Serialize)]
758#[serde(tag = "op", rename_all = "snake_case")]
759pub enum BatchOp {
760    Create {
761        list: String,
762        #[serde(flatten)]
763        task: TaskInput,
764    },
765    Update {
766        task: String,
767        #[serde(flatten)]
768        update: UpdateInput,
769    },
770    Status {
771        task: String,
772        status: String,
773    },
774    Comment {
775        task: String,
776        text: String,
777    },
778    Delete {
779        task: String,
780    },
781}
782
783impl BatchOp {
784    pub fn describe(&self) -> String {
785        match self {
786            Self::Create { list, task } => format!(
787                "create '{}' in {list}",
788                task.name.as_deref().unwrap_or_default()
789            ),
790            Self::Update { task, .. } => format!("update {task}"),
791            Self::Status { task, status } => format!("set {task} status to '{status}'"),
792            Self::Comment { task, .. } => format!("comment on {task}"),
793            Self::Delete { task } => format!("delete {task}"),
794        }
795    }
796
797    pub fn is_destructive(&self) -> bool {
798        matches!(self, Self::Delete { .. })
799    }
800}
801
802pub async fn run_batch_op(r: &Resolver<'_>, op: &BatchOp) -> Result<Value> {
803    let tz = r.client().timezone().map(str::to_string);
804    let tz = tz.as_deref();
805    match op {
806        BatchOp::Create { list, task } => {
807            let t = create_task(r, list, task).await?;
808            Ok(task_summary(&t, tz))
809        }
810        BatchOp::Update { task, update } => {
811            let out = update_task(r, &task.parse()?, update).await?;
812            Ok(json!({ "task": task_summary(&out.task, tz), "fields": out.fields }))
813        }
814        BatchOp::Status { task, status } => {
815            let t = set_status(r, &task.parse()?, status).await?;
816            Ok(task_summary(&t, tz))
817        }
818        BatchOp::Comment { task, text } => {
819            r.client()
820                .add_comment(&task.parse()?, text, None, false)
821                .await
822        }
823        BatchOp::Delete { task } => {
824            r.client().delete_task(&task.parse()?).await?;
825            Ok(json!({ "deleted": task }))
826        }
827    }
828}
829
830/// Changes applied to every task in a bulk update.
831#[derive(Debug, Clone, Default, Deserialize, Serialize)]
832#[serde(default)]
833pub struct BulkChanges {
834    pub status: Option<String>,
835    pub priority: Option<String>,
836    pub assignees_add: Vec<String>,
837    pub tags_add: Vec<String>,
838    pub due: Option<String>,
839}
840
841impl BulkChanges {
842    pub fn is_empty(&self) -> bool {
843        self.status.is_none()
844            && self.priority.is_none()
845            && self.assignees_add.is_empty()
846            && self.tags_add.is_empty()
847            && self.due.is_none()
848    }
849}
850
851/// Resolve names once, then apply to each task with bounded concurrency.
852/// Returns `(task, result)` in input order.
853pub async fn bulk_update(
854    r: &Resolver<'_>,
855    tasks: Vec<TaskRef>,
856    changes: &BulkChanges,
857    on_done: impl Fn() + Send + Sync,
858) -> Result<Vec<(String, Result<()>)>> {
859    let tz = r.client().timezone().map(str::to_string);
860    let mut u = UpdateTask {
861        // ponytail: status is sent as typed; per-list validation would cost a
862        // GET per task. ClickUp's error is reported per item instead.
863        status: changes.status.clone(),
864        ..Default::default()
865    };
866    if let Some(p) = &changes.priority {
867        u.priority = Some(parse_priority(p)?);
868    }
869    for m in &changes.assignees_add {
870        u.assignees_add.push(r.member_id(m).await?);
871    }
872    if let Some(d) = &changes.due {
873        if is_none(d) {
874            u.due_date = Some(None);
875        } else {
876            let ms = parse_when(d, tz.as_deref())?;
877            u.due_date = Some(Some(ms));
878            u.due_date_time = Some(has_time(ms, tz.as_deref()));
879        }
880    }
881    let c = r.client();
882    let u = &u;
883    let tags = &changes.tags_add;
884    let results = crate::bulk::run(
885        c.limiter(),
886        tasks,
887        |t| async move {
888            let res = async {
889                if !u.is_empty() {
890                    c.update_task(&t, u).await?;
891                }
892                for tag in tags {
893                    c.add_tag(&t, tag).await?;
894                }
895                Ok(())
896            }
897            .await;
898            (t.to_string(), res)
899        },
900        on_done,
901    )
902    .await;
903    Ok(results)
904}
905
906/// Create many tasks in one list with bounded concurrency.
907pub async fn bulk_create(
908    r: &Resolver<'_>,
909    list: &str,
910    tasks: Vec<TaskInput>,
911    on_done: impl Fn() + Send + Sync,
912) -> Result<Vec<Result<Task>>> {
913    let list = r.list(list).await?;
914    let mut bodies = Vec::new();
915    for t in &tasks {
916        bodies.push(build_create(r, &list.id, t).await);
917    }
918    let c = r.client();
919    let id = &list.id;
920    Ok(crate::bulk::run(
921        c.limiter(),
922        bodies,
923        |b| async move {
924            match b {
925                Ok(body) => c.create_task(id, &body).await,
926                Err(e) => Err(e),
927            }
928        },
929        on_done,
930    )
931    .await)
932}
933
934#[cfg(test)]
935mod tests {
936    use super::*;
937
938    #[test]
939    fn batch_ops_parse() {
940        let ops: Vec<BatchOp> = serde_json::from_value(json!([
941            { "op": "create", "list": "sprint", "name": "A", "priority": "high", "points": 3 },
942            { "op": "update", "task": "DEV-1", "assign": ["me"], "due": "none" },
943            { "op": "status", "task": "abc", "status": "done" },
944            { "op": "comment", "task": "abc", "text": "hi" },
945            { "op": "delete", "task": "abc" }
946        ]))
947        .unwrap();
948        assert_eq!(ops.len(), 5);
949        assert!(ops[4].is_destructive());
950        assert_eq!(ops[0].describe(), "create 'A' in sprint");
951        match &ops[1] {
952            BatchOp::Update { update, .. } => {
953                assert_eq!(update.assign, vec!["me"]);
954                assert_eq!(update.task.due.as_deref(), Some("none"));
955            }
956            other => panic!("{other:?}"),
957        }
958    }
959
960    #[test]
961    fn report_groups() {
962        let e = |task: &str, list: &str, start: i64, dur: i64| TimeEntry {
963            id: "x".into(),
964            task: Some(json!({ "id": task, "name": "T" })),
965            start: Some(start),
966            duration: Some(dur),
967            task_location: Some(json!({ "list_name": list })),
968            ..Default::default()
969        };
970        let entries = vec![
971            e("a", "L1", 0, 1000),
972            e("a", "L1", 86_400_000, 2000),
973            e("b", "L2", 0, 5000),
974        ];
975        assert_eq!(
976            time_report(&entries, ReportBy::Task, Some("UTC")),
977            vec![("b T".into(), 5000), ("a T".into(), 3000)]
978        );
979        assert_eq!(
980            time_report(&entries, ReportBy::List, Some("UTC"))[0],
981            ("L2".into(), 5000)
982        );
983        assert_eq!(time_report(&entries, ReportBy::Day, Some("UTC")).len(), 2);
984    }
985}