clickup 0.3.0

Cliente completo da API ClickUp com funcionalidades avançadas (smart search, fuzzy matching)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::client::ClickUpClient;
use crate::error::Result;
use serde::Deserialize;
use serde_json::Value;
/// Smart Assignee Finder: Busca inteligente de assignee (responsável) por nome
///
/// Estratégia:
/// 1. Recebe `responsavel_nome` do payload ChatGuru
/// 2. Busca em tarefas existentes pelo campo "assignees"
/// 3. Usa fuzzy matching para encontrar o usuário correto
/// 4. Retorna user_id do ClickUp para atribuir à tarefa
///
/// Exemplos de mapeamento:
/// - "William" → user_id do William
/// - "anne" → user_id da Anne
/// - "Gabriel Moreno" → user_id do Gabriel
use std::collections::HashMap;

const FUZZY_THRESHOLD: f64 = 0.70; // Reduzido de 0.85 para 0.70

#[derive(Debug, Clone)]
pub struct AssigneeSearchResult {
    pub user_id: String,
    pub username: String,
    pub email: Option<String>,
    pub confidence: f64,
    pub search_method: SearchMethod,
}

#[derive(Debug, Clone, PartialEq)]
pub enum SearchMethod {
    ExactMatch,      // Nome exato encontrado
    FuzzyMatch,      // Similaridade >= 0.85
    HistoricalMatch, // Encontrado em tarefas anteriores
    NotFound,        // Não encontrado
}

/// Deserializa ID que pode vir como string ou integer da API do ClickUp
fn deserialize_id_flexible<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{self, Deserialize};

    let value = Value::deserialize(deserializer)?;
    match value {
        Value::String(s) => Ok(s),
        Value::Number(n) => Ok(n.to_string()),
        _ => Err(de::Error::custom("id must be string or number")),
    }
}

/// Estrutura de usuário do ClickUp (assignee)
/// NOTA: id pode vir como integer ou string da API
#[derive(Debug, Deserialize, Clone)]
struct ClickUpUser {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    id: String,
    username: String,
    email: Option<String>,
    #[allow(dead_code)]
    #[serde(default)]
    color: Option<String>,
    #[allow(dead_code)]
    #[serde(default, rename = "profilePicture")]
    profile_picture: Option<String>,
}

/// Estrutura de resposta da API do ClickUp para team members
#[derive(Debug, Deserialize)]
struct ClickUpTeamResponse {
    team: ClickUpTeamData,
}

#[derive(Debug, Deserialize)]
struct ClickUpTeamData {
    members: Vec<ClickUpMember>,
}

#[derive(Debug, Deserialize)]
struct ClickUpMember {
    user: ClickUpUser,
}

/// Estrutura de resposta da API do ClickUp para tasks
#[derive(Debug, Deserialize)]
struct ClickUpTasksResponse {
    tasks: Vec<ClickUpTask>,
}

#[derive(Debug, Deserialize)]
struct ClickUpTask {
    #[serde(deserialize_with = "deserialize_id_flexible")]
    #[allow(dead_code)]
    id: String,
    assignees: Vec<ClickUpUser>,
}

pub struct SmartAssigneeFinder {
    client: ClickUpClient,
    workspace_id: String,
    cache: HashMap<String, AssigneeSearchResult>,
}

impl SmartAssigneeFinder {
    /// Criar novo finder
    pub fn new(client: ClickUpClient, workspace_id: String) -> Self {
        Self {
            client,
            workspace_id,
            cache: HashMap::new(),
        }
    }

    /// Criar novo finder a partir de API token (conveniência)
    pub fn from_token(api_token: String, workspace_id: String) -> Result<Self> {
        let client = ClickUpClient::new(api_token)?;
        Ok(Self::new(client, workspace_id))
    }

    /// Busca inteligente de assignee por nome do responsável
    ///
    /// Fases:
    /// 1. Cache lookup (se já buscou antes)
    /// 2. Team members API com fuzzy matching
    /// 3. Historical search em tarefas anteriores (assignees)
    /// 4. Fallback (retorna None)
    pub async fn find_assignee_by_name(
        &mut self,
        responsavel_nome: &str,
    ) -> Result<Option<AssigneeSearchResult>> {
        let normalized_name = Self::normalize_name(responsavel_nome);

        tracing::info!(
            "🔍 SmartAssigneeFinder: Buscando assignee para '{}'",
            responsavel_nome
        );

        // 1. Cache lookup
        if let Some(cached) = self.cache.get(&normalized_name) {
            tracing::info!("✅ Encontrado em cache: user_id={}", cached.user_id);
            return Ok(Some(cached.clone()));
        }

        // 2. Team Members API Search
        match self.search_team_members(&normalized_name).await {
            Ok(Some(result)) => {
                self.cache.insert(normalized_name.clone(), result.clone());
                return Ok(Some(result));
            }
            Ok(None) => {
                tracing::info!(
                    "⚠️ Não encontrado via Team Members API, tentando busca histórica..."
                );
            }
            Err(e) => {
                tracing::warn!(
                    "⚠️ Erro na busca via Team Members API: {}, tentando busca histórica...",
                    e
                );
            }
        }

        // 3. Historical Search (tarefas anteriores com assignees)
        match self.search_historical_assignees(&normalized_name).await {
            Ok(Some(result)) => {
                self.cache.insert(normalized_name.clone(), result.clone());
                return Ok(Some(result));
            }
            Ok(None) => {
                tracing::warn!(
                    "⚠️ Responsável '{}' não encontrado (nem Team API, nem histórico)",
                    responsavel_nome
                );
            }
            Err(e) => {
                tracing::error!("❌ Erro na busca histórica de assignees: {}", e);
            }
        }

        // 4. Fallback
        Ok(None)
    }

    /// Fase 1: Buscar membros do time via API do ClickUp
    async fn search_team_members(
        &self,
        normalized_name: &str,
    ) -> Result<Option<AssigneeSearchResult>> {
        tracing::info!("👥 Buscando team members via API do ClickUp...");

        // GET /team/{workspace_id} (API v2)
        let endpoint = format!("/team/{}", self.workspace_id);
        let team_response: ClickUpTeamResponse = self.client.get_json(&endpoint).await?;

        tracing::info!(
            "👥 Total de membros encontrados: {}",
            team_response.team.members.len()
        );

        // Buscar melhor match usando fuzzy matching
        self.find_best_assignee_match(normalized_name, &team_response.team.members)
            .await
    }

    /// Encontrar melhor match de assignee usando fuzzy matching
    async fn find_best_assignee_match(
        &self,
        normalized_name: &str,
        members: &[ClickUpMember],
    ) -> Result<Option<AssigneeSearchResult>> {
        let mut best_match: Option<(ClickUpUser, f64, SearchMethod)> = None;

        for member in members {
            let user = &member.user;
            let normalized_username = Self::normalize_name(&user.username);

            // 1. Exact match no username
            if normalized_username == normalized_name {
                tracing::info!("✅ Match exato: '{}'", user.username);
                best_match = Some((user.clone(), 1.0, SearchMethod::ExactMatch));
                break;
            }

            // 2. Fuzzy match (Jaro-Winkler)
            let similarity = strsim::jaro_winkler(normalized_name, &normalized_username);

            tracing::debug!(
                "  Comparando: '{}' vs '{}' → score: {:.3}",
                normalized_name,
                normalized_username,
                similarity
            );

            if similarity >= FUZZY_THRESHOLD {
                if let Some((_, best_score, _)) = &best_match {
                    if similarity > *best_score {
                        best_match = Some((user.clone(), similarity, SearchMethod::FuzzyMatch));
                    }
                } else {
                    best_match = Some((user.clone(), similarity, SearchMethod::FuzzyMatch));
                }
            }
        }

        if let Some((user, score, method)) = best_match {
            Ok(Some(AssigneeSearchResult {
                user_id: user.id,
                username: user.username,
                email: user.email,
                confidence: score,
                search_method: method,
            }))
        } else {
            Ok(None)
        }
    }

    /// Fase 2: Buscar em tarefas anteriores pelos assignees
    async fn search_historical_assignees(
        &self,
        normalized_name: &str,
    ) -> Result<Option<AssigneeSearchResult>> {
        tracing::info!("🕐 Buscando assignees em tarefas históricas...");

        // GET /team/{workspace_id}/task with query params (API v2)
        let endpoint = format!(
            "/team/{}/task?archived=false&subtasks=false&include_closed=true",
            self.workspace_id
        );
        let tasks_response: ClickUpTasksResponse = self.client.get_json(&endpoint).await?;

        tracing::info!(
            "📋 Total de tarefas encontradas: {}",
            tasks_response.tasks.len()
        );

        // Buscar assignees que correspondem ao nome
        let mut all_assignees: Vec<ClickUpUser> = Vec::new();

        for task in tasks_response.tasks {
            for assignee in task.assignees {
                // Evitar duplicatas (mesmo user_id)
                if !all_assignees.iter().any(|a| a.id == assignee.id) {
                    all_assignees.push(assignee);
                }
            }
        }

        tracing::info!(
            "👥 Total de assignees únicos encontrados: {}",
            all_assignees.len()
        );

        // Buscar melhor match usando fuzzy matching
        let mut best_match: Option<(ClickUpUser, f64)> = None;

        for assignee in all_assignees {
            let normalized_username = Self::normalize_name(&assignee.username);

            let similarity = strsim::jaro_winkler(normalized_name, &normalized_username);

            if similarity >= FUZZY_THRESHOLD {
                if let Some((_, best_score)) = &best_match {
                    if similarity > *best_score {
                        best_match = Some((assignee, similarity));
                    }
                } else {
                    best_match = Some((assignee, similarity));
                }
            }
        }

        if let Some((user, score)) = best_match {
            tracing::info!(
                "✅ Match histórico encontrado: {} (user_id: {}, score: {:.2})",
                user.username,
                user.id,
                score
            );

            Ok(Some(AssigneeSearchResult {
                user_id: user.id,
                username: user.username,
                email: user.email,
                confidence: score,
                search_method: SearchMethod::HistoricalMatch,
            }))
        } else {
            tracing::warn!(
                "⚠️ Nenhum assignee histórico encontrado para '{}'",
                normalized_name
            );
            Ok(None)
        }
    }

    /// Normalizar nome: lowercase, remover acentos e pontuação
    pub fn normalize_name(name: &str) -> String {
        use deunicode::deunicode;

        deunicode(name)
            .to_lowercase()
            .chars()
            .filter(|c| c.is_alphanumeric() || c.is_whitespace())
            .collect::<String>()
            .split_whitespace()
            .collect::<Vec<&str>>()
            .join(" ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_name() {
        assert_eq!(SmartAssigneeFinder::normalize_name("William"), "william");
        assert_eq!(
            SmartAssigneeFinder::normalize_name("Anne Souza"),
            "anne souza"
        );
        assert_eq!(
            SmartAssigneeFinder::normalize_name("Gabriel Moreno"),
            "gabriel moreno"
        );
        assert_eq!(
            SmartAssigneeFinder::normalize_name("WILLIAM DUARTE"),
            "william duarte"
        );
        assert_eq!(SmartAssigneeFinder::normalize_name("  Anne  "), "anne");
    }

    #[test]
    fn test_fuzzy_matching_assignees() {
        let test_cases = vec![
            // (nome_original, nome_digitado, deve_dar_match)
            ("William", "william", true),
            ("William", "Wiliam", true), // Typo
            ("Anne", "anne", true),
            ("Anne", "Ann", true), // Abreviação
            ("Gabriel Moreno", "gabriel moreno", true),
            ("Gabriel Moreno", "gabriel", true), // Nome parcial
            ("William Duarte", "william duarte", true),
            ("Renata", "renata", true),
            ("Renata", "Renatta", true), // Typo
            ("William", "João", false),  // Nome diferente
        ];

        for (original, digitado, should_match) in test_cases {
            let original_norm = SmartAssigneeFinder::normalize_name(original);
            let digitado_norm = SmartAssigneeFinder::normalize_name(digitado);

            let similarity = strsim::jaro_winkler(&original_norm, &digitado_norm);
            let matches = similarity >= 0.85;

            println!(
                "Comparando '{}' vs '{}' → score: {:.3} (match: {})",
                original, digitado, similarity, matches
            );

            assert_eq!(
                matches, should_match,
                "Falha ao comparar '{}' vs '{}': score {:.3}",
                original, digitado, similarity
            );
        }
    }
}