padzapp 1.3.0

An ergonomic, context-aware scratch pad library with plain text storage
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use crate::commands::CmdResult;
use crate::error::Result;
use crate::index::{DisplayPad, PadSelector};
use crate::model::{Scope, TodoStatus};
use crate::store::{Bucket, DataStore};
use uuid::Uuid;

use super::helpers::{indexed_pads, resolve_selectors};

pub fn run<S: DataStore>(
    store: &mut S,
    scope: Scope,
    selectors: &[PadSelector],
) -> Result<CmdResult> {
    let resolved = resolve_selectors(store, scope, selectors, true)?;
    let mut result = CmdResult::default();

    let mut deleted_uuids: Vec<Uuid> = Vec::new();
    let mut processed_ids = std::collections::HashSet::new();

    for (_display_index, uuid) in resolved {
        if !processed_ids.insert(uuid) {
            continue; // Already processed (e.g., as a descendant of an earlier pad)
        }

        // Get the pad's parent before moving (parent stays in Active)
        let pad = store.get_pad(&uuid, scope, Bucket::Active)?;
        let parent_id = pad.metadata.parent_id;

        // Find descendants (children, grandchildren, etc.)
        let descendants = super::helpers::get_descendant_ids(store, scope, &[uuid])?;

        // Move pad + all descendants from Active to Deleted.
        // Filter out already-processed descendants: when both a parent and child
        // are in the delete set (e.g. delete --completed), the child may have
        // already been moved to Deleted in an earlier iteration, so re-moving
        // it from Active would fail with PadNotFound.
        let mut ids_to_move = vec![uuid];
        ids_to_move.extend(descendants.iter().filter(|id| !processed_ids.contains(id)));
        store.move_pads(&ids_to_move, scope, Bucket::Active, Bucket::Deleted)?;

        for id in &descendants {
            processed_ids.insert(*id);
        }

        // Propagate status change to parent (deleted child no longer affects parent status)
        crate::todos::propagate_status_change(store, scope, parent_id)?;

        deleted_uuids.push(uuid);
    }

    // Re-index to get the new deleted indexes
    let indexed = indexed_pads(store, scope)?;
    for uuid in deleted_uuids {
        if let Some(dp) = super::helpers::find_pad_by_uuid(&indexed, uuid, |_| true) {
            result.affected_pads.push(DisplayPad {
                pad: dp.pad.clone(),
                index: dp.index.clone(),
                matches: None,
                children: Vec::new(),
            });
        }
    }

    Ok(result)
}

/// Soft-deletes all active pads with `TodoStatus::Done`.
pub fn run_completed<S: DataStore>(store: &mut S, scope: Scope) -> Result<CmdResult> {
    let active_pads = store.list_pads(scope, Bucket::Active)?;
    let done_ids: Vec<Uuid> = active_pads
        .iter()
        .filter(|p| p.metadata.status == TodoStatus::Done)
        .map(|p| p.metadata.id)
        .collect();

    if done_ids.is_empty() {
        return Ok(CmdResult::default());
    }

    let selectors: Vec<PadSelector> = done_ids.iter().map(|id| PadSelector::Uuid(*id)).collect();

    run(store, scope, &selectors)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::{create, get};
    use crate::index::DisplayIndex;
    use crate::model::Scope;
    use crate::store::bucketed::BucketedStore;
    use crate::store::mem_backend::MemBackend;

    #[test]
    fn marks_pad_as_deleted() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );
        create::run(&mut store, Scope::Project, "Title".into(), "".into(), None).unwrap();
        run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();

        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
            &[],
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 1);
        assert!(matches!(
            deleted.listed_pads[0].index,
            DisplayIndex::Deleted(1)
        ));
    }

    #[test]
    fn delete_protected_pad_fails() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );
        create::run(
            &mut store,
            Scope::Project,
            "Protected".into(),
            "".into(),
            None,
        )
        .unwrap();

        // Manually protect the pad (since pin command logic isn't coupled yet or might not be updated yet)
        let pad_id = get::run(&store, Scope::Project, get::PadFilter::default(), &[])
            .unwrap()
            .listed_pads[0]
            .pad
            .metadata
            .id;

        let mut pad = store
            .get_pad(&pad_id, Scope::Project, Bucket::Active)
            .unwrap();
        pad.metadata.delete_protected = true;
        store
            .save_pad(&pad, Scope::Project, Bucket::Active)
            .unwrap();

        // Attempt delete
        let result = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        );

        assert!(result.is_err());
        match result {
            Err(crate::error::PadzError::Api(msg)) => {
                assert!(msg.contains("Pinned pads are delete protected"));
            }
            _ => panic!("Expected Api error"),
        }
    }

    #[test]
    fn delete_parent_with_pinned_child_succeeds() {
        // Deleting a parent should work even if it has a pinned child.
        // The pinned child is NOT deleted (soft delete is non-recursive per spec).
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        // Create parent
        create::run(&mut store, Scope::Project, "Parent".into(), "".into(), None).unwrap();

        // Create child inside parent
        create::run(
            &mut store,
            Scope::Project,
            "Child".into(),
            "".into(),
            Some(PadSelector::Path(vec![DisplayIndex::Regular(1)])),
        )
        .unwrap();

        // Pin the child (1.1)
        crate::commands::pinning::pin(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(1),
            ])],
        )
        .unwrap();

        // Delete the parent - should succeed (parent is not pinned)
        let result = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        );
        assert!(result.is_ok());

        // Verify parent is deleted
        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
            &[],
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 1);
        assert_eq!(deleted.listed_pads[0].pad.metadata.title, "Parent");

        // Child moves to Deleted bucket with parent — no dual pinned indexing in Deleted
        assert_eq!(deleted.listed_pads[0].children.len(), 1);
    }

    #[test]
    fn delete_nested_pad_via_path() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        // Create parent
        create::run(&mut store, Scope::Project, "Parent".into(), "".into(), None).unwrap();

        // Create child inside parent
        create::run(
            &mut store,
            Scope::Project,
            "Child".into(),
            "".into(),
            Some(PadSelector::Path(vec![DisplayIndex::Regular(1)])),
        )
        .unwrap();

        // Delete the child using path notation 1.1
        let result = run(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(1),
            ])],
        );
        assert!(result.is_ok());

        // Parent should still be active with no visible children
        let active = get::run(&store, Scope::Project, get::PadFilter::default(), &[]).unwrap();
        assert_eq!(active.listed_pads.len(), 1);
        assert_eq!(active.listed_pads[0].pad.metadata.title, "Parent");
        assert_eq!(active.listed_pads[0].children.len(), 0); // child is deleted
    }

    #[test]
    fn delete_completed_deletes_done_pads() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        // Create 3 pads
        create::run(
            &mut store,
            Scope::Project,
            "Planned".into(),
            "".into(),
            None,
        )
        .unwrap();
        create::run(
            &mut store,
            Scope::Project,
            "Done One".into(),
            "".into(),
            None,
        )
        .unwrap();
        create::run(
            &mut store,
            Scope::Project,
            "Done Two".into(),
            "".into(),
            None,
        )
        .unwrap();

        // Mark two as Done
        crate::commands::status::complete(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();
        crate::commands::status::complete(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(2)])],
        )
        .unwrap();

        // Delete completed
        let result = run_completed(&mut store, Scope::Project).unwrap();
        assert_eq!(result.affected_pads.len(), 2);

        // Only the Planned pad should remain active
        let active = get::run(&store, Scope::Project, get::PadFilter::default(), &[]).unwrap();
        assert_eq!(active.listed_pads.len(), 1);
        assert_eq!(active.listed_pads[0].pad.metadata.title, "Planned");

        // Two pads should be in Deleted
        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
            &[],
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 2);
    }

    #[test]
    fn delete_completed_with_no_done_pads_returns_empty() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        create::run(
            &mut store,
            Scope::Project,
            "Planned".into(),
            "".into(),
            None,
        )
        .unwrap();

        let result = run_completed(&mut store, Scope::Project).unwrap();
        assert!(result.affected_pads.is_empty());

        // Pad should still be active
        let active = get::run(&store, Scope::Project, get::PadFilter::default(), &[]).unwrap();
        assert_eq!(active.listed_pads.len(), 1);
    }

    #[test]
    fn delete_completed_skips_in_progress_pads() {
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        create::run(
            &mut store,
            Scope::Project,
            "In Progress".into(),
            "".into(),
            None,
        )
        .unwrap();
        create::run(&mut store, Scope::Project, "Done".into(), "".into(), None).unwrap();

        // Mark one as InProgress
        let pads = store.list_pads(Scope::Project, Bucket::Active).unwrap();
        let mut ip_pad = pads
            .iter()
            .find(|p| p.metadata.title == "In Progress")
            .unwrap()
            .clone();
        ip_pad.metadata.status = TodoStatus::InProgress;
        store
            .save_pad(&ip_pad, Scope::Project, Bucket::Active)
            .unwrap();

        // Mark one as Done
        crate::commands::status::complete(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();

        let result = run_completed(&mut store, Scope::Project).unwrap();
        assert_eq!(result.affected_pads.len(), 1);

        // InProgress pad should still be active
        let active = get::run(&store, Scope::Project, get::PadFilter::default(), &[]).unwrap();
        assert_eq!(active.listed_pads.len(), 1);
        assert_eq!(active.listed_pads[0].pad.metadata.title, "In Progress");
    }

    #[test]
    fn delete_completed_with_done_parent_and_done_child() {
        // Regression test: when both a parent and its child are Done,
        // delete_completed must not fail regardless of processing order.
        // The child UUID may be iterated before the parent (HashMap order),
        // causing the child to be moved first; when the parent is processed,
        // get_descendant_ids still finds the child (now in Deleted bucket)
        // and must not try to re-move it from Active.
        let mut store = BucketedStore::new(
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
            MemBackend::new(),
        );

        // Create parent
        create::run(&mut store, Scope::Project, "Parent".into(), "".into(), None).unwrap();

        // Create child inside parent
        create::run(
            &mut store,
            Scope::Project,
            "Child".into(),
            "".into(),
            Some(PadSelector::Path(vec![DisplayIndex::Regular(1)])),
        )
        .unwrap();

        // Mark both as Done
        crate::commands::status::complete(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![DisplayIndex::Regular(1)])],
        )
        .unwrap();
        crate::commands::status::complete(
            &mut store,
            Scope::Project,
            &[PadSelector::Path(vec![
                DisplayIndex::Regular(1),
                DisplayIndex::Regular(1),
            ])],
        )
        .unwrap();

        // Also test the worst-case ordering directly: child UUID before parent UUID
        let active_pads = store.list_pads(Scope::Project, Bucket::Active).unwrap();
        let child_pad = active_pads
            .iter()
            .find(|p| p.metadata.title == "Child")
            .unwrap();
        let parent_pad = active_pads
            .iter()
            .find(|p| p.metadata.title == "Parent")
            .unwrap();

        // Force child-first ordering to guarantee the bug scenario
        let selectors = vec![
            PadSelector::Uuid(child_pad.metadata.id),
            PadSelector::Uuid(parent_pad.metadata.id),
        ];
        let result = run(&mut store, Scope::Project, &selectors).unwrap();

        // Both should be deleted
        assert!(!result.affected_pads.is_empty());

        let active = get::run(&store, Scope::Project, get::PadFilter::default(), &[]).unwrap();
        assert_eq!(active.listed_pads.len(), 0);

        let deleted = get::run(
            &store,
            Scope::Project,
            get::PadFilter {
                status: get::PadStatusFilter::Deleted,
                ..Default::default()
            },
            &[],
        )
        .unwrap();
        assert_eq!(deleted.listed_pads.len(), 1); // parent with child nested
        assert_eq!(deleted.listed_pads[0].children.len(), 1);
    }
}