Skip to main content

mdvault_core/domain/behaviors/
task.rs

1//! Task note type behavior.
2//!
3//! Tasks have:
4//! - ID generated from project counter (TST-001) or inbox (INB-001)
5//! - Project selector prompt
6//! - Logging to daily note
7//! - Output path: Projects/{project}/Tasks/{id}.md or Inbox/{id}.md
8
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use crate::types::TypeDefinition;
13
14use super::super::context::{CreationContext, FieldPrompt, PromptContext, PromptType};
15use super::super::traits::{
16    DomainError, DomainResult, NoteBehavior, NoteIdentity, NoteLifecycle, NotePrompts,
17};
18
19/// Behavior implementation for task notes.
20pub struct TaskBehavior {
21    typedef: Option<Arc<TypeDefinition>>,
22}
23
24impl TaskBehavior {
25    /// Create a new TaskBehavior, optionally wrapping a Lua typedef override.
26    pub fn new(typedef: Option<Arc<TypeDefinition>>) -> Self {
27        Self { typedef }
28    }
29}
30
31impl NoteIdentity for TaskBehavior {
32    fn generate_id(&self, ctx: &CreationContext) -> DomainResult<Option<String>> {
33        // ID generation is handled in before_create after project is known
34        // Return existing ID if already set
35        if let Some(ref id) = ctx.core_metadata.task_id {
36            return Ok(Some(id.clone()));
37        }
38        Ok(None)
39    }
40
41    fn output_path(&self, ctx: &CreationContext) -> DomainResult<PathBuf> {
42        // Check Lua typedef for output template first
43        if let Some(ref td) = self.typedef
44            && let Some(ref output) = td.output
45        {
46            return super::render_output_template(output, ctx);
47        }
48
49        // Default path
50        let task_id = ctx
51            .core_metadata
52            .task_id
53            .as_ref()
54            .ok_or_else(|| DomainError::PathResolution("task-id not set".into()))?;
55
56        let project = ctx.get_var("project").unwrap_or("inbox");
57
58        if project == "inbox" {
59            Ok(ctx.config.vault_root.join(format!("Inbox/{}.md", task_id)))
60        } else {
61            Ok(ctx
62                .config
63                .vault_root
64                .join(format!("Projects/{}/Tasks/{}.md", project, task_id)))
65        }
66    }
67
68    fn core_fields(&self) -> Vec<&'static str> {
69        vec!["type", "title", "task-id", "project"]
70    }
71}
72
73impl NoteLifecycle for TaskBehavior {
74    fn before_create(&self, ctx: &mut CreationContext) -> DomainResult<()> {
75        let project = ctx
76            .get_var("project")
77            .map(|s| s.to_string())
78            .unwrap_or_else(|| "inbox".into());
79
80        // Generate task ID based on project
81        let (task_id, project) = if project == "inbox" {
82            (generate_inbox_task_id(&ctx.config.vault_root)?, project)
83        } else {
84            // Get project counter and canonical slug
85            let (project_id, counter, slug) = get_project_info(ctx.config, &project)?;
86            (format!("{}-{:03}", project_id, counter + 1), slug)
87        };
88
89        // Set core metadata
90        ctx.core_metadata.task_id = Some(task_id.clone());
91        ctx.core_metadata.project =
92            if project == "inbox" { None } else { Some(project.clone()) };
93        ctx.set_var("task-id", &task_id);
94        if project != "inbox" {
95            ctx.set_var("project", &project);
96        }
97
98        Ok(())
99    }
100
101    fn after_create(&self, ctx: &CreationContext, _content: &str) -> DomainResult<()> {
102        let project = ctx.get_var("project").unwrap_or("inbox");
103
104        // Increment project counter if not inbox
105        if project != "inbox" {
106            increment_project_counter(ctx.config, project)?;
107        }
108
109        // Log to daily note
110        if let Some(ref output_path) = ctx.output_path {
111            let task_id = ctx.core_metadata.task_id.as_deref().unwrap_or("");
112            if let Err(e) = super::super::services::DailyLogService::log_creation(
113                ctx.config,
114                "task",
115                &ctx.title,
116                task_id,
117                output_path,
118            ) {
119                // Log warning but don't fail the creation
120                tracing::warn!("Failed to log to daily note: {}", e);
121            }
122        }
123
124        // Log to project note
125        if project != "inbox"
126            && let Ok(project_file) = find_project_file(ctx.config, project)
127        {
128            let task_id = ctx.core_metadata.task_id.as_deref().unwrap_or("");
129            let message = format!("Created task [[{}]]: {}", task_id, ctx.title);
130            if let Err(e) = super::super::services::ProjectLogService::log_entry(
131                &project_file,
132                &message,
133            ) {
134                tracing::warn!("Failed to log to project note: {}", e);
135            }
136        }
137
138        // TODO: Run Lua on_create hook if defined (requires VaultContext)
139
140        Ok(())
141    }
142}
143
144impl NotePrompts for TaskBehavior {
145    fn type_prompts(&self, ctx: &PromptContext) -> Vec<FieldPrompt> {
146        let mut prompts = vec![];
147
148        // Project selector (if not provided)
149        if !ctx.provided_vars.contains_key("project") && !ctx.batch_mode {
150            prompts.push(FieldPrompt {
151                field_name: "project".into(),
152                prompt_text: "Select project for this task".into(),
153                prompt_type: PromptType::ProjectSelector,
154                required: false, // Can be inbox
155                default_value: Some("inbox".into()),
156            });
157        }
158
159        prompts
160    }
161}
162
163impl NoteBehavior for TaskBehavior {
164    fn type_name(&self) -> &'static str {
165        "task"
166    }
167}
168
169// --- Helper functions (to be moved/refactored) ---
170
171use crate::config::types::ResolvedConfig;
172use std::fs;
173
174/// Generate an inbox task ID by scanning the Inbox directory.
175fn generate_inbox_task_id(vault_root: &std::path::Path) -> DomainResult<String> {
176    let inbox_dir = vault_root.join("Inbox");
177
178    let mut max_num = 0u32;
179
180    if inbox_dir.exists() {
181        for entry in fs::read_dir(&inbox_dir).map_err(DomainError::Io)? {
182            let entry = entry.map_err(DomainError::Io)?;
183            let name = entry.file_name();
184            let name_str = name.to_string_lossy();
185
186            // Parse INB-XXX.md pattern
187            if let Some(stem) = name_str.strip_suffix(".md")
188                && let Some(num_str) = stem.strip_prefix("INB-")
189                && let Ok(num) = num_str.parse::<u32>()
190            {
191                max_num = max_num.max(num);
192            }
193        }
194    }
195
196    Ok(format!("INB-{:03}", max_num + 1))
197}
198
199/// Get project info (project-id, task_counter, canonical slug) from project file.
200fn get_project_info(
201    config: &ResolvedConfig,
202    project: &str,
203) -> DomainResult<(String, u32, String)> {
204    let project_file = find_project_file(config, project)?;
205    let slug = extract_project_slug(&project_file, &config.vault_root);
206
207    let content = fs::read_to_string(&project_file).map_err(DomainError::Io)?;
208
209    // Parse frontmatter
210    let parsed = crate::frontmatter::parse(&content).map_err(|e| {
211        DomainError::Other(format!("Failed to parse project frontmatter: {}", e))
212    })?;
213
214    let fields = parsed.frontmatter.map(|fm| fm.fields).unwrap_or_default();
215
216    let project_id = fields
217        .get("project-id")
218        .and_then(|v| v.as_str())
219        .map(|s| s.to_string())
220        .unwrap_or_else(|| project.to_uppercase());
221
222    let counter = fields
223        .get("task_counter")
224        .and_then(|v| v.as_u64())
225        .map(|n| n as u32)
226        .unwrap_or(0);
227
228    Ok((project_id, counter, slug))
229}
230
231/// Find the project file by project name/ID/title.
232///
233/// Searches in the following order:
234/// 1. Direct path patterns (fast path)
235/// 2. File named {project}.md in any Projects subfolder
236/// 3. Any project file with matching project-id or title in frontmatter
237fn find_project_file(config: &ResolvedConfig, project: &str) -> DomainResult<PathBuf> {
238    // Try common patterns first (fast path)
239    let patterns = [
240        format!("Projects/{}/{}.md", project, project),
241        format!("Projects/{}.md", project),
242        format!("projects/{}/{}.md", project.to_lowercase(), project.to_lowercase()),
243    ];
244
245    for pattern in &patterns {
246        let path = config.vault_root.join(pattern);
247        if path.exists() {
248            return Ok(path);
249        }
250    }
251
252    let projects_dir = config.vault_root.join("Projects");
253    if !projects_dir.exists() {
254        return Err(DomainError::Other(format!(
255            "Project file not found for: {}",
256            project
257        )));
258    }
259
260    // Search for project file by name in any Projects subfolder
261    // Handles structures like: Projects/my-project-folder/MDV.md
262    if let Ok(entries) = fs::read_dir(&projects_dir) {
263        for entry in entries.flatten() {
264            if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
265                // Look for {project}.md in this folder
266                let candidate = entry.path().join(format!("{}.md", project));
267                if candidate.exists() {
268                    return Ok(candidate);
269                }
270            }
271        }
272    }
273
274    // Search by frontmatter project-id or title
275    // Handles structures where file is named differently (e.g., markdownvault-development.md with project-id: MDV)
276    // Also resolves by human-readable title (e.g., "SEB Account" matches title field)
277    if let Ok(entries) = fs::read_dir(&projects_dir) {
278        for entry in entries.flatten() {
279            let path = entry.path();
280            if path.is_dir() {
281                // Look for any .md file in this folder
282                if let Ok(files) = fs::read_dir(&path) {
283                    for file_entry in files.flatten() {
284                        let file_path = file_entry.path();
285                        if file_matches_project(&file_path, project) {
286                            return Ok(file_path);
287                        }
288                    }
289                }
290            } else if file_matches_project(&path, project) {
291                return Ok(path);
292            }
293        }
294    }
295
296    Err(DomainError::Other(format!("Project file not found for: {}", project)))
297}
298
299/// Check if a file matches a project by project-id (exact) or title (case-insensitive).
300fn file_matches_project(path: &Path, project: &str) -> bool {
301    if path.extension().map(|e| e == "md").unwrap_or(false)
302        && let Ok(content) = fs::read_to_string(path)
303        && let Ok(parsed) = crate::frontmatter::parse(&content)
304        && let Some(fm) = parsed.frontmatter
305    {
306        // Check project-id (exact match)
307        if let Some(pid) = fm.fields.get("project-id")
308            && pid.as_str() == Some(project)
309        {
310            return true;
311        }
312        // Check title (case-insensitive)
313        if let Some(title) = fm.fields.get("title")
314            && title.as_str().map(|s| s.eq_ignore_ascii_case(project)).unwrap_or(false)
315        {
316            return true;
317        }
318    }
319    false
320}
321
322/// Extract the canonical project directory slug from a resolved project file path.
323///
324/// Given `Projects/seb-account/seb-account.md`, returns `"seb-account"`.
325/// Given `Projects/seb-account.md`, returns `"seb-account"`.
326fn extract_project_slug(project_file: &Path, vault_root: &Path) -> String {
327    let rel = project_file.strip_prefix(vault_root).unwrap_or(project_file);
328    // Projects/seb-account/seb-account.md → parent dir name = "seb-account"
329    // Projects/seb-account.md → file stem = "seb-account"
330    if let Some(parent) = rel.parent()
331        && let Some(dir_name) = parent.file_name()
332    {
333        let name = dir_name.to_string_lossy();
334        if !name.eq_ignore_ascii_case("projects") {
335            return name.to_string();
336        }
337    }
338    project_file.file_stem().unwrap_or_default().to_string_lossy().to_string()
339}
340
341/// Increment the task_counter in a project file.
342fn increment_project_counter(config: &ResolvedConfig, project: &str) -> DomainResult<()> {
343    let project_file = find_project_file(config, project)?;
344
345    let content = fs::read_to_string(&project_file).map_err(DomainError::Io)?;
346
347    // Parse frontmatter
348    let parsed = crate::frontmatter::parse(&content).map_err(|e| {
349        DomainError::Other(format!("Failed to parse project frontmatter: {}", e))
350    })?;
351
352    let mut fields = parsed.frontmatter.map(|fm| fm.fields).unwrap_or_default();
353
354    let current = fields
355        .get("task_counter")
356        .and_then(|v| v.as_u64())
357        .map(|n| n as u32)
358        .unwrap_or(0);
359
360    fields.insert(
361        "task_counter".to_string(),
362        serde_yaml::Value::Number((current + 1).into()),
363    );
364
365    // Rebuild content with updated frontmatter
366    let yaml = serde_yaml::to_string(&fields).map_err(|e| {
367        DomainError::Other(format!("Failed to serialize frontmatter: {}", e))
368    })?;
369
370    let new_content = format!("---\n{}---\n{}", yaml, parsed.body);
371    fs::write(&project_file, new_content).map_err(DomainError::Io)?;
372
373    Ok(())
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use std::path::Path;
380
381    #[test]
382    fn test_file_matches_project_by_project_id() {
383        let dir = tempfile::tempdir().unwrap();
384        let path = dir.path().join("test-project.md");
385        fs::write(
386            &path,
387            "---\ntype: project\ntitle: Test Project\nproject-id: TST\ntask_counter: 0\n---\n",
388        )
389        .unwrap();
390
391        assert!(file_matches_project(&path, "TST"));
392        assert!(!file_matches_project(&path, "tst")); // project-id is exact match
393        assert!(!file_matches_project(&path, "NOPE"));
394    }
395
396    #[test]
397    fn test_file_matches_project_by_title() {
398        let dir = tempfile::tempdir().unwrap();
399        let path = dir.path().join("test-project.md");
400        fs::write(
401            &path,
402            "---\ntype: project\ntitle: SEB Account\nproject-id: SAE\ntask_counter: 0\n---\n",
403        )
404        .unwrap();
405
406        assert!(file_matches_project(&path, "SEB Account"));
407        assert!(file_matches_project(&path, "seb account")); // case-insensitive
408        assert!(file_matches_project(&path, "SEB ACCOUNT")); // case-insensitive
409        assert!(!file_matches_project(&path, "Other Project"));
410    }
411
412    #[test]
413    fn test_file_matches_project_no_match() {
414        let dir = tempfile::tempdir().unwrap();
415        let path = dir.path().join("test-project.md");
416        fs::write(&path, "---\ntype: project\ntitle: My Project\nproject-id: MPR\n---\n")
417            .unwrap();
418
419        assert!(!file_matches_project(&path, "Other"));
420        assert!(!file_matches_project(&path, ""));
421    }
422
423    #[test]
424    fn test_file_matches_project_non_md_file() {
425        let dir = tempfile::tempdir().unwrap();
426        let path = dir.path().join("readme.txt");
427        fs::write(&path, "---\ntitle: Test\nproject-id: TST\n---\n").unwrap();
428
429        assert!(!file_matches_project(&path, "TST"));
430    }
431
432    #[test]
433    fn test_extract_project_slug_subfolder() {
434        let vault_root = Path::new("/vault");
435        let project_file = Path::new("/vault/Projects/seb-account/seb-account.md");
436        assert_eq!(extract_project_slug(project_file, vault_root), "seb-account");
437    }
438
439    #[test]
440    fn test_extract_project_slug_flat() {
441        let vault_root = Path::new("/vault");
442        let project_file = Path::new("/vault/Projects/seb-account.md");
443        assert_eq!(extract_project_slug(project_file, vault_root), "seb-account");
444    }
445
446    #[test]
447    fn test_extract_project_slug_nested_deeply() {
448        // Edge case: Tasks subfolder shouldn't happen for project files, but test robustness
449        let vault_root = Path::new("/vault");
450        let project_file = Path::new("/vault/Projects/my-proj/my-proj.md");
451        assert_eq!(extract_project_slug(project_file, vault_root), "my-proj");
452    }
453
454    #[test]
455    fn test_find_project_file_by_title() {
456        let dir = tempfile::tempdir().unwrap();
457        let vault_root = dir.path();
458
459        // Create project structure: Projects/seb-account/seb-account.md
460        let project_dir = vault_root.join("Projects/seb-account");
461        fs::create_dir_all(&project_dir).unwrap();
462        let project_file = project_dir.join("seb-account.md");
463        fs::write(
464            &project_file,
465            "---\ntype: project\ntitle: SEB Account\nproject-id: SAE\ntask_counter: 3\n---\n",
466        )
467        .unwrap();
468
469        let config = ResolvedConfig {
470            vault_root: vault_root.to_path_buf(),
471            ..make_test_config(vault_root)
472        };
473
474        // Should resolve by slug (fast path)
475        let result = find_project_file(&config, "seb-account");
476        assert!(result.is_ok(), "Should resolve by slug");
477
478        // Should resolve by title
479        let result = find_project_file(&config, "SEB Account");
480        assert!(result.is_ok(), "Should resolve by title");
481        assert_eq!(result.unwrap(), project_file);
482
483        // Should resolve by title case-insensitively
484        let result = find_project_file(&config, "seb account");
485        assert!(result.is_ok(), "Should resolve by title case-insensitively");
486
487        // Should resolve by project-id
488        let result = find_project_file(&config, "SAE");
489        assert!(result.is_ok(), "Should resolve by project-id");
490
491        // Should fail for unknown
492        let result = find_project_file(&config, "Unknown Project");
493        assert!(result.is_err(), "Should fail for unknown project");
494    }
495
496    fn make_test_config(vault_root: &Path) -> ResolvedConfig {
497        ResolvedConfig {
498            active_profile: "test".into(),
499            vault_root: vault_root.to_path_buf(),
500            templates_dir: vault_root.join(".mdvault/templates"),
501            captures_dir: vault_root.join(".mdvault/captures"),
502            macros_dir: vault_root.join(".mdvault/macros"),
503            typedefs_dir: vault_root.join(".mdvault/typedefs"),
504            excluded_folders: vec![],
505            security: Default::default(),
506            logging: Default::default(),
507            activity: Default::default(),
508        }
509    }
510}