metis-docs-core 1.2.0

Core library for Flight Levels documentation management system
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
use crate::dal::database::{models::*, repository::DocumentRepository};
use crate::domain::documents::types::DocumentType;
use crate::Result;

/// Database service - handles all database CRUD operations
pub struct DatabaseService {
    repository: DocumentRepository,
}

impl DatabaseService {
    pub fn new(repository: DocumentRepository) -> Self {
        Self { repository }
    }

    /// Create a new document in the database
    pub fn create_document(&mut self, document: NewDocument) -> Result<Document> {
        self.repository.create_document(document)
    }

    /// Find a document by filepath
    pub fn find_by_filepath(&mut self, filepath: &str) -> Result<Option<Document>> {
        self.repository.find_by_filepath(filepath)
    }

    /// Find a document by ID
    pub fn find_by_id(&mut self, id: &str) -> Result<Option<Document>> {
        self.repository.find_by_id(id)
    }

    /// Find a document by short code
    pub fn find_by_short_code(&mut self, short_code: &str) -> Result<Option<Document>> {
        self.repository.find_by_short_code(short_code)
    }

    /// Update an existing document
    pub fn update_document(&mut self, filepath: &str, document: &Document) -> Result<Document> {
        self.repository.update_document(filepath, document)
    }

    /// Delete a document from the database
    pub fn delete_document(&mut self, filepath: &str) -> Result<bool> {
        self.repository.delete_document(filepath)
    }

    /// Search documents using full-text search
    pub fn search_documents(&mut self, query: &str) -> Result<Vec<Document>> {
        self.repository.search_documents(query)
    }

    /// Search non-archived documents using full-text search
    pub fn search_documents_unarchived(&mut self, query: &str) -> Result<Vec<Document>> {
        self.repository.search_documents_unarchived(query)
    }

    /// Get all documents of a specific type
    pub fn find_by_type(&mut self, doc_type: DocumentType) -> Result<Vec<Document>> {
        let type_str = doc_type.to_string();
        self.repository.find_by_type(&type_str)
    }

    /// Get documents with a specific tag
    pub fn find_by_tag(&mut self, tag: &str) -> Result<Vec<Document>> {
        self.repository.find_by_tag(tag)
    }

    /// Get all tags for a specific document
    pub fn get_tags_for_document(&mut self, doc_filepath: &str) -> Result<Vec<String>> {
        self.repository.get_tags_for_document(doc_filepath)
    }

    /// Get all children of a document
    pub fn find_children(&mut self, parent_id: &str) -> Result<Vec<Document>> {
        self.repository.find_children(parent_id)
    }

    /// Get the parent of a document
    pub fn find_parent(&mut self, child_id: &str) -> Result<Option<Document>> {
        self.repository.find_parent(child_id)
    }

    /// Create a parent-child relationship
    pub fn create_relationship(
        &mut self,
        parent_id: &str,
        child_id: &str,
        parent_filepath: &str,
        child_filepath: &str,
    ) -> Result<()> {
        let relationship = DocumentRelationship {
            parent_id: parent_id.to_string(),
            child_id: child_id.to_string(),
            parent_filepath: parent_filepath.to_string(),
            child_filepath: child_filepath.to_string(),
        };
        self.repository.create_relationship(relationship)
    }

    /// Check if a document exists by filepath
    pub fn document_exists(&mut self, filepath: &str) -> Result<bool> {
        Ok(self.repository.find_by_filepath(filepath)?.is_some())
    }

    /// Get document count by type
    pub fn count_by_type(&mut self, doc_type: DocumentType) -> Result<usize> {
        let docs = self.repository.find_by_type(&doc_type.to_string())?;
        Ok(docs.len())
    }

    /// Get all document IDs and their filepaths (useful for validation)
    pub fn get_all_id_filepath_pairs(&mut self) -> Result<Vec<(String, String)>> {
        // This would need a custom query in the repository
        // For now, we'll use find_by_type for each type
        let mut pairs = Vec::new();

        for doc_type in [
            DocumentType::Vision,
            DocumentType::Strategy,
            DocumentType::Initiative,
            DocumentType::Task,
            DocumentType::Adr,
        ] {
            let docs = self.repository.find_by_type(&doc_type.to_string())?;
            for doc in docs {
                pairs.push((doc.id, doc.filepath));
            }
        }

        Ok(pairs)
    }

    /// Get all documents belonging to a strategy
    pub fn find_by_strategy_id(&mut self, strategy_id: &str) -> Result<Vec<Document>> {
        self.repository.find_by_strategy_id(strategy_id)
    }

    /// Get all documents belonging to an initiative
    pub fn find_by_initiative_id(&mut self, initiative_id: &str) -> Result<Vec<Document>> {
        self.repository.find_by_initiative_id(initiative_id)
    }

    /// Get all documents in a strategy hierarchy (strategy + its initiatives + their tasks)
    pub fn find_strategy_hierarchy(&mut self, strategy_id: &str) -> Result<Vec<Document>> {
        self.repository.find_strategy_hierarchy(strategy_id)
    }

    /// Get all documents in a strategy hierarchy by short code (strategy + its initiatives + their tasks)
    pub fn find_strategy_hierarchy_by_short_code(
        &mut self,
        strategy_short_code: &str,
    ) -> Result<Vec<Document>> {
        self.repository
            .find_strategy_hierarchy_by_short_code(strategy_short_code)
    }

    /// Get all documents in an initiative hierarchy (initiative + its tasks)
    pub fn find_initiative_hierarchy(&mut self, initiative_id: &str) -> Result<Vec<Document>> {
        self.repository.find_initiative_hierarchy(initiative_id)
    }

    /// Get all documents in an initiative hierarchy by short code (initiative + its tasks)
    pub fn find_initiative_hierarchy_by_short_code(
        &mut self,
        initiative_short_code: &str,
    ) -> Result<Vec<Document>> {
        self.repository
            .find_initiative_hierarchy_by_short_code(initiative_short_code)
    }

    /// Generate a short code for a document type (requires db_path)
    pub fn generate_short_code(&mut self, doc_type: &str) -> Result<String> {
        // Note: This requires the database path which is not stored in DatabaseService
        // Callers should use this method from a service that has access to db_path
        // For now, this is a placeholder that will be called from workspace-aware services
        self.repository.generate_short_code(doc_type, ":memory:")
    }

    /// Set counter if the current value is lower than the provided value
    /// This is a placeholder - actual implementation needs db_path
    pub fn set_counter_if_lower(&mut self, _doc_type: &str, _min_value: u32) -> Result<bool> {
        // This method needs access to ConfigurationRepository which requires db_path
        // For collision resolution, we'll handle this differently
        Ok(true)
    }
}

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

    fn setup_service() -> DatabaseService {
        let db = Database::new(":memory:").expect("Failed to create test database");
        DatabaseService::new(db.into_repository())
    }

    fn create_test_document() -> NewDocument {
        NewDocument {
            filepath: "/test/doc.md".to_string(),
            id: "test-doc-1".to_string(),
            title: "Test Document".to_string(),
            document_type: "vision".to_string(),
            created_at: 1609459200.0,
            updated_at: 1609459200.0,
            archived: false,
            exit_criteria_met: false,
            file_hash: "abc123".to_string(),
            frontmatter_json: "{}".to_string(),
            content: Some("Test content".to_string()),
            phase: "draft".to_string(),
            strategy_id: None,
            initiative_id: None,
            short_code: "TEST-V-0601".to_string(),
        }
    }

    fn create_test_document_with_lineage(
        id: &str,
        doc_type: &str,
        filepath: &str,
        strategy_id: Option<String>,
        initiative_id: Option<String>,
    ) -> NewDocument {
        NewDocument {
            filepath: filepath.to_string(),
            id: id.to_string(),
            title: format!("Test {}", doc_type),
            document_type: doc_type.to_string(),
            created_at: 1609459200.0,
            updated_at: 1609459200.0,
            archived: false,
            exit_criteria_met: false,
            file_hash: "abc123".to_string(),
            frontmatter_json: "{}".to_string(),
            content: Some("Test content".to_string()),
            phase: "draft".to_string(),
            strategy_id,
            initiative_id,
            short_code: format!(
                "TEST-{}-{:04}",
                doc_type.chars().next().unwrap().to_uppercase(),
                match doc_type {
                    "vision" => 701,
                    "strategy" => 702,
                    "initiative" => 703,
                    "task" => 704,
                    "adr" => 705,
                    _ => 799,
                }
            ),
        }
    }

    #[test]
    fn test_database_service_crud() {
        let mut service = setup_service();

        // Create
        let new_doc = create_test_document();
        let created = service.create_document(new_doc).expect("Failed to create");
        assert_eq!(created.id, "test-doc-1");

        // Read
        let found = service
            .find_by_id("test-doc-1")
            .expect("Failed to find")
            .expect("Document not found");
        assert_eq!(found.filepath, "/test/doc.md");

        // Update
        let mut updated_doc = found.clone();
        updated_doc.title = "Updated Title".to_string();
        let updated = service
            .update_document("/test/doc.md", &updated_doc)
            .expect("Failed to update");
        assert_eq!(updated.title, "Updated Title");

        // Delete
        let deleted = service
            .delete_document("/test/doc.md")
            .expect("Failed to delete");
        assert!(deleted);

        // Verify deleted
        assert!(!service
            .document_exists("/test/doc.md")
            .expect("Failed to check existence"));
    }

    #[test]
    fn test_database_service_relationships() {
        let mut service = setup_service();

        // Create parent and child documents
        let parent = NewDocument {
            id: "parent-1".to_string(),
            filepath: "/parent.md".to_string(),
            document_type: "strategy".to_string(),
            short_code: "TEST-S-0601".to_string(),
            ..create_test_document()
        };

        let child = NewDocument {
            id: "child-1".to_string(),
            filepath: "/child.md".to_string(),
            document_type: "initiative".to_string(),
            short_code: "TEST-I-0601".to_string(),
            ..create_test_document()
        };

        service
            .create_document(parent)
            .expect("Failed to create parent");
        service
            .create_document(child)
            .expect("Failed to create child");

        // Create relationship
        service
            .create_relationship("parent-1", "child-1", "/parent.md", "/child.md")
            .expect("Failed to create relationship");

        // Test find children
        let children = service
            .find_children("parent-1")
            .expect("Failed to find children");
        assert_eq!(children.len(), 1);
        assert_eq!(children[0].id, "child-1");

        // Test find parent
        let parent = service
            .find_parent("child-1")
            .expect("Failed to find parent")
            .expect("Parent not found");
        assert_eq!(parent.id, "parent-1");
    }

    #[test]
    fn test_lineage_queries() {
        let mut service = setup_service();

        // Create strategy
        let strategy = create_test_document_with_lineage(
            "strategy-1",
            "strategy",
            "/strategies/strategy-1/strategy.md",
            None,
            None,
        );
        service
            .create_document(strategy)
            .expect("Failed to create strategy");

        // Create initiative under strategy
        let initiative = create_test_document_with_lineage(
            "initiative-1",
            "initiative",
            "/strategies/strategy-1/initiatives/initiative-1/initiative.md",
            Some("strategy-1".to_string()),
            None,
        );
        service
            .create_document(initiative)
            .expect("Failed to create initiative");

        // Create tasks under initiative
        let mut task1 = create_test_document_with_lineage(
            "task-1",
            "task",
            "/strategies/strategy-1/initiatives/initiative-1/tasks/task-1.md",
            Some("strategy-1".to_string()),
            Some("initiative-1".to_string()),
        );
        task1.short_code = "TEST-T-0704".to_string();

        let mut task2 = create_test_document_with_lineage(
            "task-2",
            "task",
            "/strategies/strategy-1/initiatives/initiative-1/tasks/task-2.md",
            Some("strategy-1".to_string()),
            Some("initiative-1".to_string()),
        );
        task2.short_code = "TEST-T-0705".to_string();
        service
            .create_document(task1)
            .expect("Failed to create task1");
        service
            .create_document(task2)
            .expect("Failed to create task2");

        // Test find by strategy ID
        let strategy_docs = service
            .find_by_strategy_id("strategy-1")
            .expect("Failed to find by strategy");
        assert_eq!(strategy_docs.len(), 3); // initiative + 2 tasks

        // Test find by initiative ID
        let initiative_docs = service
            .find_by_initiative_id("initiative-1")
            .expect("Failed to find by initiative");
        assert_eq!(initiative_docs.len(), 2); // 2 tasks

        // Test strategy hierarchy (should include strategy itself + its children)
        let strategy_hierarchy = service
            .find_strategy_hierarchy("strategy-1")
            .expect("Failed to find strategy hierarchy");
        assert_eq!(strategy_hierarchy.len(), 4); // strategy + initiative + 2 tasks

        // Test initiative hierarchy (should include initiative itself + its tasks)
        let initiative_hierarchy = service
            .find_initiative_hierarchy("initiative-1")
            .expect("Failed to find initiative hierarchy");
        assert_eq!(initiative_hierarchy.len(), 3); // initiative + 2 tasks

        // Verify document types in strategy hierarchy
        let doc_types: Vec<&str> = strategy_hierarchy
            .iter()
            .map(|d| d.document_type.as_str())
            .collect();
        assert!(doc_types.contains(&"strategy"));
        assert!(doc_types.contains(&"initiative"));
        assert!(doc_types.iter().filter(|&&t| t == "task").count() == 2);
    }
}