1use std::{
6 collections::BTreeMap,
7 path::PathBuf,
8 sync::Mutex,
9 time::{SystemTime, UNIX_EPOCH},
10};
11
12use serde::{de::DeserializeOwned, Deserialize, Serialize};
13use serde_json::{json, Value};
14
15use crate::{
16 client::{convert_field_value, relation_value, ClickUpClient, FieldValue},
17 config::ClickUpConfig,
18 error::{ClickUpError, Result},
19 model::{CustomField, List, User},
20 task_ref::TaskRef,
21};
22
23pub const CACHE_TTL_SECS: i64 = 3600;
24
25pub fn suggest(input: &str, candidates: &[String]) -> Vec<String> {
27 let needle = input.to_lowercase();
28 let mut scored: Vec<(f64, &String)> = candidates
29 .iter()
30 .map(|c| (strsim::jaro_winkler(&needle, &c.to_lowercase()), c))
31 .filter(|(s, _)| *s >= 0.8)
32 .collect();
33 scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
34 let mut out: Vec<String> = Vec::new();
35 for (_, c) in scored {
36 if !out.contains(c) {
37 out.push(c.clone());
38 }
39 if out.len() == 3 {
40 break;
41 }
42 }
43 out
44}
45
46#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
47pub struct HList {
48 pub id: String,
49 pub name: String,
50}
51
52#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
53pub struct HFolder {
54 pub id: String,
55 pub name: String,
56 pub lists: Vec<HList>,
57}
58
59#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
60pub struct HSpace {
61 pub id: String,
62 pub name: String,
63 pub folders: Vec<HFolder>,
64 pub lists: Vec<HList>,
66}
67
68#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
69pub struct Hierarchy {
70 pub spaces: Vec<HSpace>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
74pub struct ListRef {
75 pub id: String,
76 pub name: String,
77 pub space: Option<String>,
78 pub folder: Option<String>,
79}
80
81impl ListRef {
82 pub fn path(&self) -> String {
84 [
85 self.space.as_deref(),
86 self.folder.as_deref(),
87 Some(&self.name),
88 ]
89 .into_iter()
90 .flatten()
91 .collect::<Vec<_>>()
92 .join("/")
93 }
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
97pub struct SpaceRef {
98 pub id: String,
99 pub name: String,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
103pub struct FolderRef {
104 pub id: String,
105 pub name: String,
106 pub space: String,
107}
108
109impl Hierarchy {
110 pub fn lists(&self) -> Vec<ListRef> {
111 let mut out = Vec::new();
112 for s in &self.spaces {
113 for f in &s.folders {
114 for l in &f.lists {
115 out.push(ListRef {
116 id: l.id.clone(),
117 name: l.name.clone(),
118 space: Some(s.name.clone()),
119 folder: Some(f.name.clone()),
120 });
121 }
122 }
123 for l in &s.lists {
124 out.push(ListRef {
125 id: l.id.clone(),
126 name: l.name.clone(),
127 space: Some(s.name.clone()),
128 folder: None,
129 });
130 }
131 }
132 out
133 }
134
135 pub fn folders(&self) -> Vec<FolderRef> {
136 self.spaces
137 .iter()
138 .flat_map(|s| {
139 s.folders.iter().map(|f| FolderRef {
140 id: f.id.clone(),
141 name: f.name.clone(),
142 space: s.name.clone(),
143 })
144 })
145 .collect()
146 }
147}
148
149fn now_secs() -> i64 {
150 SystemTime::now()
151 .duration_since(UNIX_EPOCH)
152 .map(|d| d.as_secs() as i64)
153 .unwrap_or_default()
154}
155
156#[derive(Serialize, Deserialize)]
157struct Cached<T> {
158 fetched_at: i64,
159 data: T,
160}
161
162#[derive(Debug, Clone)]
164pub struct Cache {
165 dir: PathBuf,
166}
167
168impl Cache {
169 pub fn new(cache_dir: PathBuf, workspace_id: &str) -> Self {
170 Self {
171 dir: cache_dir.join(workspace_id),
172 }
173 }
174
175 pub fn dir(&self) -> &PathBuf {
176 &self.dir
177 }
178
179 fn load<T: DeserializeOwned>(&self, name: &str) -> Option<T> {
180 let text = std::fs::read_to_string(self.dir.join(name)).ok()?;
181 let c: Cached<T> = serde_json::from_str(&text).ok()?;
182 (now_secs() - c.fetched_at < CACHE_TTL_SECS).then_some(c.data)
183 }
184
185 fn save<T: Serialize>(&self, name: &str, data: &T) {
186 let path = self.dir.join(name);
187 if let Some(parent) = path.parent() {
188 let _ = std::fs::create_dir_all(parent);
189 }
190 let payload = Cached {
191 fetched_at: now_secs(),
192 data,
193 };
194 if let Ok(text) = serde_json::to_string(&payload) {
195 let _ = std::fs::write(path, text);
197 }
198 }
199
200 pub fn clear(&self) -> Result<()> {
201 if self.dir.exists() {
202 std::fs::remove_dir_all(&self.dir)?;
203 }
204 Ok(())
205 }
206}
207
208pub struct Resolver<'a> {
209 client: &'a ClickUpClient,
210 cache: Cache,
211 aliases: BTreeMap<String, String>,
212 refresh: bool,
213 hierarchy: Mutex<Option<(Hierarchy, bool)>>,
214}
215
216fn not_found(kind: &'static str, input: &str, names: &[String]) -> ClickUpError {
217 ClickUpError::resolve(kind, input, suggest(input, names))
218}
219
220fn unique<T: Clone>(
222 kind: &'static str,
223 input: &str,
224 items: &[T],
225 label: impl Fn(&T) -> String,
226 pred: impl Fn(&T) -> bool,
227) -> Result<Option<T>> {
228 let hits: Vec<&T> = items.iter().filter(|i| pred(i)).collect();
229 match hits.as_slice() {
230 [] => Ok(None),
231 [one] => Ok(Some((*one).clone())),
232 many => Err(ClickUpError::Resolve {
233 kind,
234 input: format!("{input}' is ambiguous; matches: '{}", {
235 many.iter()
236 .map(|i| label(i))
237 .collect::<Vec<_>>()
238 .join("', '")
239 }),
240 suggestions: vec![],
241 }),
242 }
243}
244
245impl<'a> Resolver<'a> {
246 pub fn new(client: &'a ClickUpClient, cfg: &ClickUpConfig) -> Result<Self> {
247 Ok(Self {
248 client,
249 cache: Cache::new(cfg.cache_dir.clone(), client.workspace_id()?),
250 aliases: cfg.aliases.clone(),
251 refresh: false,
252 hierarchy: Mutex::new(None),
253 })
254 }
255
256 pub fn with_refresh(mut self, refresh: bool) -> Self {
258 self.refresh = refresh;
259 self
260 }
261
262 pub fn client(&self) -> &ClickUpClient {
263 self.client
264 }
265
266 pub fn cache(&self) -> &Cache {
267 &self.cache
268 }
269
270 pub async fn hierarchy(&self, refresh: bool) -> Result<Hierarchy> {
272 Ok(self.hierarchy_with_origin(refresh).await?.0)
273 }
274
275 async fn hierarchy_with_origin(&self, refresh: bool) -> Result<(Hierarchy, bool)> {
277 let refresh = refresh || self.refresh;
278 if !refresh {
279 if let Some(h) = self.hierarchy.lock().expect("hierarchy lock").clone() {
280 return Ok(h);
281 }
282 if let Some(h) = self.cache.load::<Hierarchy>("hierarchy.json") {
283 *self.hierarchy.lock().expect("hierarchy lock") = Some((h.clone(), false));
284 return Ok((h, false));
285 }
286 }
287 let mut tree = Hierarchy::default();
288 for space in self.client.spaces(false).await? {
289 let folders = self.client.folders(&space.id, false).await?;
290 let lists = self.client.folderless_lists(&space.id, false).await?;
291 let to_h = |l: List| HList {
292 id: l.id,
293 name: l.name,
294 };
295 tree.spaces.push(HSpace {
296 id: space.id,
297 name: space.name,
298 folders: folders
299 .into_iter()
300 .map(|f| HFolder {
301 id: f.id,
302 name: f.name,
303 lists: f.lists.into_iter().map(to_h).collect(),
304 })
305 .collect(),
306 lists: lists.into_iter().map(to_h).collect(),
307 });
308 }
309 self.cache.save("hierarchy.json", &tree);
310 *self.hierarchy.lock().expect("hierarchy lock") = Some((tree.clone(), true));
311 Ok((tree, true))
312 }
313
314 fn cached_tree(&self) -> Option<Hierarchy> {
316 if let Some((h, _)) = self.hierarchy.lock().expect("hierarchy lock").clone() {
317 return Some(h);
318 }
319 if self.refresh {
320 return None;
321 }
322 self.cache.load::<Hierarchy>("hierarchy.json")
323 }
324
325 async fn with_tree<T>(
327 &self,
328 find: impl Fn(&Hierarchy) -> Result<Option<T>>,
329 ) -> Result<(Option<T>, Hierarchy)> {
330 let (tree, fresh) = self.hierarchy_with_origin(false).await?;
331 if let Some(hit) = find(&tree)? {
332 return Ok((Some(hit), tree));
333 }
334 if fresh {
335 return Ok((None, tree));
336 }
337 let (tree, _) = self.hierarchy_with_origin(true).await?;
338 Ok((find(&tree)?, tree))
339 }
340
341 pub async fn list(&self, input: &str) -> Result<ListRef> {
343 let input = input.trim();
344 let target = self
345 .aliases
346 .iter()
347 .find(|(k, _)| k.eq_ignore_ascii_case(input))
348 .map(|(_, v)| v.as_str())
349 .unwrap_or(input);
350 let is_id = target.chars().all(|c| c.is_ascii_digit()) && !target.is_empty();
351 if is_id {
352 return Ok(self
355 .cached_tree()
356 .and_then(|h| h.lists().into_iter().find(|l| l.id == target))
357 .unwrap_or_else(|| ListRef {
358 id: target.to_string(),
359 name: target.to_string(),
360 space: None,
361 folder: None,
362 }));
363 }
364 let lower = target.to_lowercase();
365 let (hit, tree) = self
366 .with_tree(|h| {
367 let lists = h.lists();
368 if target.contains('/') {
369 return unique("list", target, &lists, ListRef::path, |l| {
370 let p = l.path().to_lowercase();
371 p == lower || p.ends_with(&format!("/{lower}"))
372 });
373 }
374 unique("list", target, &lists, ListRef::path, |l| {
375 l.name.to_lowercase() == lower
376 })
377 })
378 .await?;
379 if let Some(l) = hit {
380 return Ok(l);
381 }
382 let lists = tree.lists();
383 let mut names: Vec<String> = lists.iter().map(|l| l.name.clone()).collect();
384 names.extend(lists.iter().map(ListRef::path));
385 Err(not_found("list", input, &names))
386 }
387
388 pub async fn space(&self, input: &str) -> Result<SpaceRef> {
389 let input = input.trim();
390 let lower = input.to_lowercase();
391 let (hit, tree) = self
392 .with_tree(|h| {
393 let spaces: Vec<SpaceRef> = h
394 .spaces
395 .iter()
396 .map(|s| SpaceRef {
397 id: s.id.clone(),
398 name: s.name.clone(),
399 })
400 .collect();
401 unique(
402 "space",
403 input,
404 &spaces,
405 |s| s.name.clone(),
406 |s| s.id == input || s.name.to_lowercase() == lower,
407 )
408 })
409 .await?;
410 hit.ok_or_else(|| {
411 let names: Vec<String> = tree.spaces.iter().map(|s| s.name.clone()).collect();
412 not_found("space", input, &names)
413 })
414 }
415
416 pub async fn folder(&self, input: &str) -> Result<FolderRef> {
418 let input = input.trim();
419 let lower = input.to_lowercase();
420 let label = |f: &FolderRef| format!("{}/{}", f.space, f.name);
421 let (hit, tree) = self
422 .with_tree(|h| {
423 unique("folder", input, &h.folders(), label, |f| {
424 f.id == input
425 || f.name.to_lowercase() == lower
426 || label(f).to_lowercase() == lower
427 })
428 })
429 .await?;
430 hit.ok_or_else(|| {
431 let names: Vec<String> = tree.folders().iter().map(|f| f.name.clone()).collect();
432 not_found("folder", input, &names)
433 })
434 }
435
436 pub async fn list_detail(&self, list_id: &str) -> Result<List> {
438 let name = format!("lists/{list_id}.json");
439 if !self.refresh {
440 if let Some(l) = self.cache.load::<List>(&name) {
441 return Ok(l);
442 }
443 }
444 let l = self.client.list(list_id).await?;
445 self.cache.save(&name, &l);
446 Ok(l)
447 }
448
449 pub async fn status(&self, list_id: &str, input: &str) -> Result<String> {
451 let mut list = self.list_detail(list_id).await?;
452 let find = |l: &List| {
453 l.statuses
454 .iter()
455 .find(|s| s.status.eq_ignore_ascii_case(input.trim()))
456 .map(|s| s.status.clone())
457 };
458 if let Some(s) = find(&list) {
459 return Ok(s);
460 }
461 if !self.refresh {
462 list = self.client.list(list_id).await?;
463 self.cache.save(&format!("lists/{list_id}.json"), &list);
464 if let Some(s) = find(&list) {
465 return Ok(s);
466 }
467 }
468 let names: Vec<String> = list.statuses.iter().map(|s| s.status.clone()).collect();
469 let mut suggestions = suggest(input, &names);
470 if suggestions.is_empty() {
471 suggestions = names;
472 }
473 Err(ClickUpError::resolve("status", input, suggestions))
474 }
475
476 pub async fn members(&self) -> Result<Vec<User>> {
477 if !self.refresh {
478 if let Some(m) = self.cache.load::<Vec<User>>("members.json") {
479 return Ok(m);
480 }
481 }
482 let m = self.client.workspace_members().await?;
483 self.cache.save("members.json", &m);
484 Ok(m)
485 }
486
487 pub async fn member(&self, input: &str) -> Result<User> {
489 let input = input.trim();
490 if input.eq_ignore_ascii_case("me") {
491 return self.client.user().await;
492 }
493 let lower = input.to_lowercase();
494 let members = self.members().await?;
495 let label = |u: &User| match &u.email {
496 Some(e) => format!("{} <{e}>", u.display()),
497 None => u.display(),
498 };
499 let exact = |u: &User| {
500 u.id == input
501 || u.email
502 .as_deref()
503 .is_some_and(|e| e.eq_ignore_ascii_case(input))
504 || u.username
505 .as_deref()
506 .is_some_and(|n| n.to_lowercase() == lower)
507 };
508 if let Some(u) = unique("member", input, &members, label, exact)? {
509 return Ok(u);
510 }
511 let partial = |u: &User| {
512 u.username
513 .as_deref()
514 .is_some_and(|n| n.to_lowercase().contains(&lower))
515 || u.email
516 .as_deref()
517 .is_some_and(|e| e.to_lowercase().contains(&lower))
518 };
519 if let Some(u) = unique("member", input, &members, label, partial)? {
520 return Ok(u);
521 }
522 if input.chars().all(|c| c.is_ascii_digit()) && !input.is_empty() {
523 return Ok(User {
524 id: input.to_string(),
525 ..Default::default()
526 });
527 }
528 let names: Vec<String> = members.iter().filter_map(|u| u.username.clone()).collect();
529 Err(not_found("member", input, &names))
530 }
531
532 pub async fn member_id(&self, input: &str) -> Result<i64> {
534 let u = self.member(input).await?;
535 u.id.parse()
536 .map_err(|_| ClickUpError::Invalid(format!("member '{input}' has a non-numeric id")))
537 }
538
539 pub async fn fields(&self, list_id: &str) -> Result<Vec<CustomField>> {
540 let name = format!("fields/{list_id}.json");
541 if !self.refresh {
542 if let Some(f) = self.cache.load::<Vec<CustomField>>(&name) {
543 return Ok(f);
544 }
545 }
546 let f = self.client.list_fields(list_id).await?;
547 self.cache.save(&name, &f);
548 Ok(f)
549 }
550
551 pub async fn field(&self, list_id: &str, input: &str) -> Result<CustomField> {
553 let input = input.trim();
554 let find = |fields: &[CustomField]| {
555 fields
556 .iter()
557 .find(|f| f.id == input || f.name.eq_ignore_ascii_case(input))
558 .cloned()
559 };
560 let fields = self.fields(list_id).await?;
561 if let Some(f) = find(&fields) {
562 return Ok(f);
563 }
564 let fields = self.client.list_fields(list_id).await?;
565 self.cache.save(&format!("fields/{list_id}.json"), &fields);
566 find(&fields).ok_or_else(|| {
567 let names: Vec<String> = fields.iter().map(|f| f.name.clone()).collect();
568 let mut suggestions = suggest(input, &names);
569 if suggestions.is_empty() {
570 suggestions = names;
571 }
572 ClickUpError::resolve("field", input, suggestions)
573 })
574 }
575
576 pub async fn field_value(&self, field: &CustomField, raw: &str) -> Result<FieldValue> {
579 match field.kind.as_str() {
580 "users" | "tasks" | "list_relationship" => {
581 let (mut add, mut rem) = (Vec::new(), Vec::new());
582 for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
583 let (target, bucket) = match item.strip_prefix('-') {
584 Some(rest) => (rest.trim(), &mut rem),
585 None => (item, &mut add),
586 };
587 let id = if field.kind == "users" {
588 json!(self.member_id(target).await?)
589 } else {
590 let r: TaskRef = target.parse()?;
591 json!(self.client.task_id(&r).await?)
592 };
593 bucket.push(id);
594 }
595 Ok(relation_value(add, rem))
596 }
597 _ => convert_field_value(field, raw, self.client.timezone()),
598 }
599 }
600
601 pub async fn task_type(&self, input: &str) -> Result<i64> {
603 let input = input.trim();
604 match input.to_ascii_lowercase().as_str() {
605 "task" => return Ok(0),
606 "milestone" => return Ok(1),
607 _ => {}
608 }
609 if let Ok(n) = input.parse() {
610 return Ok(n);
611 }
612 let types = self.client.custom_task_types().await?;
613 let name_of = |t: &Value| {
614 t.get("name")
615 .and_then(Value::as_str)
616 .unwrap_or_default()
617 .to_string()
618 };
619 if let Some(t) = types
620 .iter()
621 .find(|t| name_of(t).eq_ignore_ascii_case(input))
622 {
623 if let Some(id) = t.get("id").and_then(Value::as_i64) {
624 return Ok(id);
625 }
626 }
627 let names: Vec<String> = types.iter().map(name_of).collect();
628 Err(not_found("task type", input, &names))
629 }
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 #[test]
637 fn suggestions_are_ranked_and_capped() {
638 let names: Vec<String> = ["Sprint 12", "Sprint 13", "Backlog", "Sprint 1", "Bugs"]
639 .iter()
640 .map(|s| s.to_string())
641 .collect();
642 let s = suggest("sprnt 12", &names);
643 assert_eq!(s.first().map(String::as_str), Some("Sprint 12"));
644 assert!(s.len() <= 3);
645 assert!(suggest("zzzz", &names).is_empty());
646 }
647
648 #[test]
649 fn list_paths() {
650 let l = ListRef {
651 id: "1".into(),
652 name: "Sprint".into(),
653 space: Some("Eng".into()),
654 folder: Some("Q4".into()),
655 };
656 assert_eq!(l.path(), "Eng/Q4/Sprint");
657 }
658}