todoist-cache-rs 0.2.0

Local cache for Todoist data
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
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Filter evaluation against cached items.
//!
//! This module provides the [`FilterEvaluator`] for evaluating parsed filter expressions
//! against Todoist items from the cache.
//!
//! # Example
//!
//! ```
//! use todoist_cache_rs::filter::{FilterParser, FilterEvaluator, FilterContext};
//! use todoist_api_rs::sync::{Item, Project, Section, Label};
//!
//! // Parse a filter
//! let filter = FilterParser::parse("today & p1").unwrap();
//!
//! // Create evaluation context
//! let context = FilterContext::new(
//!     &[],       // projects
//!     &[],       // sections
//!     &[],       // labels
//! );
//!
//! // Create an item to test
//! let item = Item {
//!     id: "1".to_string(),
//!     project_id: "proj-1".to_string(),
//!     content: "Important task".to_string(),
//!     description: String::new(),
//!     priority: 4, // p1 in Todoist API (inverted)
//!     due: None,
//!     // ... other fields
//!     # user_id: None,
//!     # deadline: None,
//!     # parent_id: None,
//!     # child_order: 0,
//!     # section_id: None,
//!     # day_order: 0,
//!     # is_collapsed: false,
//!     # labels: vec![],
//!     # added_by_uid: None,
//!     # assigned_by_uid: None,
//!     # responsible_uid: None,
//!     # checked: false,
//!     # is_deleted: false,
//!     # added_at: None,
//!     # updated_at: None,
//!     # completed_at: None,
//!     # duration: None,
//! };
//!
//! // Evaluate the filter
//! let evaluator = FilterEvaluator::new(&filter, &context);
//! let matches = evaluator.matches(&item);
//! ```

use chrono::{Datelike, Local, NaiveDate};
use todoist_api_rs::sync::{Collaborator, Item, Label, Project, Section};

use super::ast::{AssignedTarget, Filter};

/// Context for filter evaluation.
///
/// Contains reference data needed to resolve project/section/label names to IDs
/// and to build hierarchies for `##project` (project with subprojects) filters.
#[derive(Debug, Clone)]
pub struct FilterContext<'a> {
    projects: &'a [Project],
    sections: &'a [Section],
    labels: &'a [Label],
    collaborators: &'a [Collaborator],
    current_user_id: Option<&'a str>,
}

impl<'a> FilterContext<'a> {
    /// Creates a new filter context.
    ///
    /// # Arguments
    ///
    /// * `projects` - All projects from the cache
    /// * `sections` - All sections from the cache
    /// * `labels` - All labels from the cache
    pub fn new(projects: &'a [Project], sections: &'a [Section], labels: &'a [Label]) -> Self {
        Self {
            projects,
            sections,
            labels,
            collaborators: &[],
            current_user_id: None,
        }
    }

    /// Sets collaborators and current user for assignment filter evaluation.
    pub fn with_assignment_context(
        mut self,
        collaborators: &'a [Collaborator],
        current_user_id: Option<&'a str>,
    ) -> Self {
        self.collaborators = collaborators;
        self.current_user_id = current_user_id;
        self
    }

    /// Finds a collaborator by name (case-insensitive substring match).
    fn find_collaborator_by_name(&self, name: &str) -> Option<&Collaborator> {
        let name_lower = name.to_lowercase();
        self.collaborators.iter().find(|c| {
            c.full_name
                .as_ref()
                .is_some_and(|n| n.to_lowercase().contains(&name_lower))
                || c.email
                    .as_ref()
                    .is_some_and(|e| e.to_lowercase().contains(&name_lower))
        })
    }

    /// Finds a project by name (case-insensitive).
    ///
    /// Only returns non-deleted projects.
    pub fn find_project_by_name(&self, name: &str) -> Option<&Project> {
        let name_lower = name.to_lowercase();
        self.projects
            .iter()
            .find(|p| !p.is_deleted && p.name.to_lowercase() == name_lower)
    }

    /// Gets all project IDs that match the given project name or are subprojects of it.
    /// Used for `##project` filters.
    pub fn get_project_ids_with_subprojects(&self, name: &str) -> Vec<&str> {
        let Some(root_project) = self.find_project_by_name(name) else {
            return vec![];
        };

        let mut ids = vec![root_project.id.as_str()];
        self.collect_subproject_ids(&root_project.id, &mut ids);
        ids
    }

    /// Recursively collects all subproject IDs for a given parent project.
    fn collect_subproject_ids<'b>(&'b self, parent_id: &str, ids: &mut Vec<&'b str>) {
        for project in self.projects.iter() {
            if project.parent_id.as_deref() == Some(parent_id) && !project.is_deleted {
                ids.push(&project.id);
                self.collect_subproject_ids(&project.id, ids);
            }
        }
    }

    /// Finds a section by name (case-insensitive).
    ///
    /// Only returns non-deleted sections.
    pub fn find_section_by_name(&self, name: &str) -> Option<&Section> {
        let name_lower = name.to_lowercase();
        self.sections
            .iter()
            .find(|s| !s.is_deleted && s.name.to_lowercase() == name_lower)
    }

    /// Checks if a label name exists (case-insensitive).
    ///
    /// Only considers non-deleted labels.
    pub fn label_exists(&self, name: &str) -> bool {
        let name_lower = name.to_lowercase();
        self.labels
            .iter()
            .any(|l| !l.is_deleted && l.name.to_lowercase() == name_lower)
    }
}

/// Evaluates a parsed filter against items.
///
/// The evaluator takes a reference to a parsed [`Filter`] and a [`FilterContext`],
/// then can test whether items match the filter criteria.
#[derive(Debug)]
pub struct FilterEvaluator<'a> {
    filter: &'a Filter,
    context: &'a FilterContext<'a>,
}

impl<'a> FilterEvaluator<'a> {
    /// Creates a new filter evaluator.
    ///
    /// # Arguments
    ///
    /// * `filter` - The parsed filter to evaluate
    /// * `context` - The context containing projects, sections, and labels
    pub fn new(filter: &'a Filter, context: &'a FilterContext<'a>) -> Self {
        Self { filter, context }
    }

    /// Returns true if the item matches the filter.
    pub fn matches(&self, item: &Item) -> bool {
        self.evaluate_filter(self.filter, item)
    }

    /// Filters a slice of items, returning only those that match.
    ///
    /// Pre-allocates the result vector with an estimated 10% match rate,
    /// which is typical for date-based and priority filters. The minimum
    /// capacity is 16 to handle small collections efficiently.
    pub fn filter_items<'b>(&self, items: &'b [Item]) -> Vec<&'b Item> {
        // Estimate 10% match rate as reasonable default for most filters.
        // Most filters (today, priority, project) match small subsets.
        let estimated_capacity = (items.len() / 10).max(16);
        let mut result = Vec::with_capacity(estimated_capacity);

        for item in items {
            if self.matches(item) {
                result.push(item);
            }
        }

        result
    }

    /// Evaluates a filter expression against an item.
    fn evaluate_filter(&self, filter: &Filter, item: &Item) -> bool {
        match filter {
            // Date filters
            Filter::Today => self.is_due_today(item),
            Filter::Tomorrow => self.is_due_tomorrow(item),
            Filter::Overdue => self.is_overdue(item),
            Filter::NoDate => self.has_no_date(item),
            Filter::Next7Days => self.is_due_within_7_days(item),
            Filter::SpecificDate { month, day } => self.is_due_on_specific_date(item, *month, *day),

            // Priority filters
            // Note: Todoist API uses inverted priority (4 = highest, 1 = lowest)
            // But the user-facing values are p1 = highest, p4 = lowest
            Filter::Priority1 => item.priority == 4,
            Filter::Priority2 => item.priority == 3,
            Filter::Priority3 => item.priority == 2,
            Filter::Priority4 => item.priority == 1,

            // Label filters
            Filter::Label(name) => self.has_label(item, name),
            Filter::NoLabels => self.has_no_labels(item),

            // Project filters
            Filter::Project(name) => self.in_project(item, name),
            Filter::ProjectWithSubprojects(name) => self.in_project_or_subproject(item, name),

            // Section filter
            Filter::Section(name) => self.in_section(item, name),

            // Assignment filters
            Filter::AssignedTo(target) => self.is_assigned_to(item, target),
            Filter::AssignedBy(target) => self.is_assigned_by(item, target),
            Filter::Assigned => item.responsible_uid.is_some(),
            Filter::NoAssignee => item.responsible_uid.is_none(),

            // Boolean operators
            Filter::And(left, right) => {
                self.evaluate_filter(left, item) && self.evaluate_filter(right, item)
            }
            Filter::Or(left, right) => {
                self.evaluate_filter(left, item) || self.evaluate_filter(right, item)
            }
            Filter::Not(inner) => !self.evaluate_filter(inner, item),
        }
    }

    /// Checks if the item is due today.
    fn is_due_today(&self, item: &Item) -> bool {
        let Some(due) = &item.due else {
            return false;
        };

        let today = Local::now().date_naive();
        self.parse_due_date(&due.date)
            .is_some_and(|due_date| due_date == today)
    }

    /// Checks if the item is due tomorrow.
    fn is_due_tomorrow(&self, item: &Item) -> bool {
        let Some(due) = &item.due else {
            return false;
        };

        let tomorrow = Local::now().date_naive() + chrono::Duration::days(1);
        self.parse_due_date(&due.date)
            .is_some_and(|due_date| due_date == tomorrow)
    }

    /// Checks if the item is overdue (due date is in the past).
    fn is_overdue(&self, item: &Item) -> bool {
        // Completed items are not overdue
        if item.checked {
            return false;
        }

        let Some(due) = &item.due else {
            return false;
        };

        let today = Local::now().date_naive();
        self.parse_due_date(&due.date)
            .is_some_and(|due_date| due_date < today)
    }

    /// Checks if the item has no due date.
    fn has_no_date(&self, item: &Item) -> bool {
        item.due.is_none()
    }

    /// Checks if the item is due within the next 7 days (including today).
    fn is_due_within_7_days(&self, item: &Item) -> bool {
        let Some(due) = &item.due else {
            return false;
        };

        let today = Local::now().date_naive();
        let end_date = today + chrono::Duration::days(7);

        self.parse_due_date(&due.date)
            .is_some_and(|due_date| due_date >= today && due_date < end_date)
    }

    /// Checks if the item is due on a specific month and day.
    /// The year is inferred: if the date has passed this year, it matches next year.
    fn is_due_on_specific_date(&self, item: &Item, month: u32, day: u32) -> bool {
        let Some(due) = &item.due else {
            return false;
        };

        self.parse_due_date(&due.date)
            .is_some_and(|due_date| due_date.month() == month && due_date.day() == day)
    }

    /// Parses a date string in YYYY-MM-DD format.
    fn parse_due_date(&self, date_str: &str) -> Option<NaiveDate> {
        NaiveDate::parse_from_str(date_str, "%Y-%m-%d").ok()
    }

    /// Checks if the item has the specified label (case-insensitive).
    fn has_label(&self, item: &Item, label_name: &str) -> bool {
        let label_lower = label_name.to_lowercase();
        item.labels.iter().any(|l| l.to_lowercase() == label_lower)
    }

    /// Checks if the item has no labels.
    fn has_no_labels(&self, item: &Item) -> bool {
        item.labels.is_empty()
    }

    /// Checks if the item is in the specified project (case-insensitive).
    fn in_project(&self, item: &Item, project_name: &str) -> bool {
        self.context
            .find_project_by_name(project_name)
            .is_some_and(|project| project.id == item.project_id)
    }

    /// Checks if the item is in the specified project or any of its subprojects.
    fn in_project_or_subproject(&self, item: &Item, project_name: &str) -> bool {
        let project_ids = self.context.get_project_ids_with_subprojects(project_name);
        project_ids.contains(&item.project_id.as_str())
    }

    /// Checks if the item is in the specified section (case-insensitive).
    fn in_section(&self, item: &Item, section_name: &str) -> bool {
        let Some(section_id) = &item.section_id else {
            return false;
        };

        self.context
            .find_section_by_name(section_name)
            .is_some_and(|section| &section.id == section_id)
    }

    /// Checks if the item is assigned to the specified target.
    fn is_assigned_to(&self, item: &Item, target: &AssignedTarget) -> bool {
        match target {
            AssignedTarget::Me => {
                let Some(current_uid) = self.context.current_user_id else {
                    return false;
                };
                item.responsible_uid.as_deref() == Some(current_uid)
            }
            AssignedTarget::Others => {
                let Some(current_uid) = self.context.current_user_id else {
                    return false;
                };
                item.responsible_uid
                    .as_ref()
                    .is_some_and(|uid| uid != current_uid)
            }
            AssignedTarget::User(name) => {
                let Some(collaborator) = self.context.find_collaborator_by_name(name) else {
                    return false;
                };
                item.responsible_uid.as_deref() == Some(collaborator.id.as_str())
            }
        }
    }

    /// Checks if the item was assigned by the specified target.
    fn is_assigned_by(&self, item: &Item, target: &AssignedTarget) -> bool {
        match target {
            AssignedTarget::Me => {
                let Some(current_uid) = self.context.current_user_id else {
                    return false;
                };
                item.assigned_by_uid.as_deref() == Some(current_uid)
            }
            AssignedTarget::Others => {
                let Some(current_uid) = self.context.current_user_id else {
                    return false;
                };
                item.assigned_by_uid
                    .as_ref()
                    .is_some_and(|uid| uid != current_uid)
            }
            AssignedTarget::User(name) => {
                let Some(collaborator) = self.context.find_collaborator_by_name(name) else {
                    return false;
                };
                item.assigned_by_uid.as_deref() == Some(collaborator.id.as_str())
            }
        }
    }
}

#[cfg(test)]
#[path = "evaluator_tests.rs"]
mod tests;