tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
#[allow(clippy::wildcard_imports)]
use super::*;

/// The dimension the Time tab's summary breaks down by (WP05 T026).
///
/// The words are the CLI's own `--by` vocabulary (`all` is the explicit spelling of
/// "no breakdown"), and each dimension's rows are the shared
/// [`crate::time_tracking::aggregate::TimeTotal`]s [`TimeSnapshot::by_issue`] and
/// friends return — this enum chooses a dimension, it never groups anything itself.
///
/// [`TimeSnapshot::by_issue`]: crate::time_tracking::aggregate::TimeSnapshot::by_issue
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum TimeBreakdown {
    /// The scope's one ungrouped total.
    #[default]
    All,
    /// One total per issue the snapshot holds.
    Issue,
    /// One total per identity that recorded work.
    Assignee,
    /// One total per calendar date.
    Date,
}

impl TimeBreakdown {
    /// The dimensions in cycle order.
    pub const ALL: [Self; 4] = [Self::All, Self::Issue, Self::Assignee, Self::Date];

    /// The dimension's name, as `tix time total --by` spells it.
    pub const fn label(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Issue => "issue",
            Self::Assignee => "assignee",
            Self::Date => "date",
        }
    }

    /// The next dimension in cycle order, wrapping.
    pub fn next(self) -> Self {
        let index = Self::ALL
            .iter()
            .position(|dimension| *dimension == self)
            .unwrap_or(0);
        Self::ALL[(index + 1) % Self::ALL.len()]
    }
}

/// The `F7` Stats page's **Time tab** session state (WP05 T026).
///
/// Holds the tab's **one** read — the shared
/// [`crate::time_tracking::aggregate::TimeSnapshot`] — rather than re-reading every
/// issue per frame, exactly as the portfolio tabs cache their projections; the
/// snapshot is rebuilt when the tab is opened and after every mutation, never during
/// a render.
///
/// Nothing here is a total of its own. [`Self::total`] and [`Self::groups`] call the
/// shared calculation, the filter is the shared `TimeFilter` (its validation is that
/// type's own `problems`), and the entry rows are the snapshot's own index — so the
/// tab, the CLI and the pane cannot disagree about a figure (C-005, C-006, NFR-003).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatsTimeState {
    /// The current entries and retained time History over the project's active issues.
    pub snapshot: crate::time_tracking::aggregate::TimeSnapshot,
    /// The scope the reader is looking through: issue, assignee, period, or none.
    pub filter: crate::time_tracking::filters::TimeFilter,
    /// The dimension the summary breaks down by.
    pub breakdown: TimeBreakdown,
    /// Whether the audit view is on (the `h` toggle) — the CLI's `--audit`.
    pub audit: bool,
    /// Which entry row the mutations act on, as an index into [`Self::rows`].
    pub cursor: usize,
}

impl StatsTimeState {
    /// A fresh tab over `snapshot`, with the empty filter, no breakdown and no audit.
    pub fn new(snapshot: crate::time_tracking::aggregate::TimeSnapshot) -> Self {
        Self {
            snapshot,
            filter: crate::time_tracking::filters::TimeFilter::new(),
            breakdown: TimeBreakdown::All,
            audit: false,
            cursor: 0,
        }
    }

    /// The filter the tab evaluates: the reader's scope, with the deleted context
    /// asked for when the audit view is on — the CLI's `--audit`, which is the same
    /// request (`deleted_count` is `Some` only when it was asked for).
    pub fn scope(&self) -> crate::time_tracking::filters::TimeFilter {
        if self.audit {
            self.filter.clone().including_deleted()
        } else {
            self.filter.clone()
        }
    }

    /// The entry rows the cursor walks: the snapshot's current entries the filter
    /// selects, in the snapshot's own deterministic order (issue, then the entry's
    /// display order).
    pub fn rows(&self) -> Vec<&crate::time_tracking::aggregate::IndexedEntry> {
        self.snapshot
            .entries()
            .iter()
            .filter(|indexed| self.filter.selects(indexed.issue, &indexed.entry))
            .collect()
    }

    /// The row the `e`/`x` mutations act on.
    pub fn selected(&self) -> Option<&crate::time_tracking::aggregate::IndexedEntry> {
        self.rows().get(self.cursor).copied()
    }

    /// Keep the cursor inside the rows (called after every refresh, so a deletion
    /// cannot leave it past the end).
    pub fn clamp(&mut self) {
        let len = self.rows().len();
        self.cursor = if len == 0 {
            0
        } else {
            self.cursor.min(len - 1)
        };
    }

    /// Move the cursor `delta` rows, clamped into the rows the filter selects.
    pub fn move_cursor(&mut self, delta: isize) {
        let last = self.rows().len().saturating_sub(1);
        let next = if delta.is_negative() {
            self.cursor.saturating_sub(delta.unsigned_abs())
        } else {
            self.cursor.saturating_add(delta as usize)
        };
        self.cursor = next.min(last);
    }

    /// The scope's total, from the shared calculation.
    pub fn total(&self) -> crate::time_tracking::aggregate::TimeTotal {
        self.snapshot.total(&self.scope())
    }

    /// The breakdown's groups, from the shared calculation. Empty for
    /// [`TimeBreakdown::All`], which is the scope's one ungrouped total already.
    pub fn groups(&self) -> Vec<crate::time_tracking::aggregate::TimeTotal> {
        let scope = self.scope();
        match self.breakdown {
            TimeBreakdown::All => Vec::new(),
            TimeBreakdown::Issue => self.snapshot.by_issue(&scope),
            TimeBreakdown::Assignee => self.snapshot.by_assignee(&scope),
            TimeBreakdown::Date => self.snapshot.by_date(&scope),
        }
    }

    /// The explicit audit view, from the shared calculation.
    pub fn audit_view(&self) -> crate::time_tracking::aggregate::TimeAudit {
        self.snapshot.audit(&self.scope())
    }
}

/// Which mutation a [`TimeForm`] is collecting (WP05 T025).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimeFormKind {
    /// Add an entry to the issue the form's `issue` selector names.
    Add,
    /// Correct the entry `entry_id` on issue `issue`, naming only the fields that
    /// were filled in.
    Edit {
        /// The issue the entry belongs to.
        issue: u32,
        /// The entry's stable id.
        entry_id: String,
    },
    /// Remove the entry `entry_id` from issue `issue`'s current projection.
    Delete {
        /// The issue the entry belongs to.
        issue: u32,
        /// The entry's stable id.
        entry_id: String,
    },
}

/// The time-entry form's state (WP05 T025).
///
/// The fields are the CLI's own arguments — the issue selector, the minutes, the
/// optional date, the author, the optional note, and the correction/deletion reason
/// — so one form adds, corrects and deletes rather than teaching three key paths.
///
/// Nothing here writes. On submit the form builds the same
/// [`crate::time_tracking::service::TimeMutationRequest`] `tix time add/edit/delete`
/// builds and hands it to [`crate::time_tracking::service::apply`], the one seam that
/// resolves the issue, validates the intent, stages the projection and the event and
/// writes once. A refusal leaves the form open with the service's own message in
/// [`Self::error`], so a refused submission cannot look like a silent one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeForm {
    /// Which mutation this form will ask for.
    pub kind: TimeFormKind,
    /// The issue selector (`Add` only; edits and deletes already name their issue).
    pub issue: String,
    /// The duration in whole minutes.
    pub minutes: String,
    /// The optional calendar date, `YYYY-MM-DD`.
    pub date: String,
    /// Who did the work. Blank keeps the configured identity.
    pub author: String,
    /// Optional free text.
    pub note: String,
    /// Why: required for a correction and a deletion, refused by the service when
    /// blank, exactly as the CLI's `--reason` is.
    pub reason: String,
    /// Whether the deletion was confirmed (`Delete` only; toggled with `space`).
    pub confirm: bool,
    /// Which field the cursor is in.
    pub field: usize,
    /// The last refusal, rendered in the form so the reader fixes the field rather
    /// than losing what they typed.
    pub error: Option<String>,
}

impl TimeForm {
    /// An add form, with the issue selector pre-filled from the tab's filter when it
    /// names one issue (the common case: filter to an issue, then add to it).
    pub fn add(default_issue: String) -> Self {
        Self {
            kind: TimeFormKind::Add,
            issue: default_issue,
            minutes: String::new(),
            date: String::new(),
            author: crate::storage::actor_identity(),
            note: String::new(),
            reason: String::new(),
            confirm: false,
            field: 0,
            error: None,
        }
    }

    /// An edit form for one entry of one issue, pre-filled with the entry's **current**
    /// values so the reader corrects a value rather than retyping it. Blank means
    /// "leave this field alone" on submit, which is the same patch semantics the CLI's
    /// optional flags have.
    pub fn edit(issue: u32, entry: &crate::time_tracking::TimeEntry) -> Self {
        Self {
            kind: TimeFormKind::Edit {
                issue,
                entry_id: entry.id.clone(),
            },
            issue: issue.to_string(),
            minutes: entry.minutes().map(|m| m.to_string()).unwrap_or_default(),
            date: entry.date.clone().unwrap_or_default(),
            author: entry.author.clone(),
            note: entry.note.clone().unwrap_or_default(),
            reason: String::new(),
            confirm: false,
            field: 0,
            error: None,
        }
    }

    /// A delete form for one entry of one issue. It names the value it will remove in
    /// its own title, because the confirmation is about that value.
    pub fn delete(issue: u32, entry: &crate::time_tracking::TimeEntry) -> Self {
        Self {
            kind: TimeFormKind::Delete {
                issue,
                entry_id: entry.id.clone(),
            },
            issue: issue.to_string(),
            minutes: entry.minutes().map(|m| m.to_string()).unwrap_or_default(),
            date: entry.date.clone().unwrap_or_default(),
            author: entry.author.clone(),
            note: entry.note.clone().unwrap_or_default(),
            reason: String::new(),
            confirm: false,
            field: 0,
            error: None,
        }
    }

    /// How many fields `Tab` walks, by kind: the deletion's confirmation is one of
    /// them, so it is reachable from the keyboard like every other choice.
    pub const fn field_count(&self) -> usize {
        match self.kind {
            TimeFormKind::Add => 5,
            TimeFormKind::Edit { .. } => 5,
            TimeFormKind::Delete { .. } => 2,
        }
    }

    /// The field the cursor is in, by name, for the form's own footer and the tests.
    pub fn field_name(&self) -> &'static str {
        if self.is_add() {
            return match self.field {
                0 => "issue",
                1 => "minutes",
                2 => "date",
                3 => "author",
                _ => "note",
            };
        }
        if self.is_edit() {
            return match self.field {
                0 => "minutes",
                1 => "date",
                2 => "author",
                3 => "note",
                _ => "reason",
            };
        }
        if self.field == 0 { "reason" } else { "confirm" }
    }

    /// Whether this form asks for a create.
    pub const fn is_add(&self) -> bool {
        matches!(self.kind, TimeFormKind::Add)
    }

    /// Whether this form asks for a correction.
    pub const fn is_edit(&self) -> bool {
        matches!(self.kind, TimeFormKind::Edit { .. })
    }

    /// Whether this form asks for a deletion.
    pub const fn is_delete(&self) -> bool {
        matches!(self.kind, TimeFormKind::Delete { .. })
    }

    /// The form's title, naming the entry a correction or a deletion is about.
    pub fn title(&self) -> String {
        match &self.kind {
            TimeFormKind::Add => "Add a time entry".to_string(),
            TimeFormKind::Edit { issue, entry_id } => {
                format!("Correct {entry_id} on #{issue}")
            }
            TimeFormKind::Delete { issue, entry_id } => {
                format!("Delete {entry_id} from #{issue}")
            }
        }
    }

    /// The typed text of the field the cursor is in, or `None` for a field that is
    /// chosen rather than typed (a deletion's confirmation, which `space` toggles).
    /// A reason may therefore contain a space: only the confirm field swallows it.
    fn focused_text_mut(&mut self) -> Option<&mut String> {
        if self.is_add() {
            return Some(match self.field {
                0 => &mut self.issue,
                1 => &mut self.minutes,
                2 => &mut self.date,
                3 => &mut self.author,
                _ => &mut self.note,
            });
        }
        if self.is_edit() {
            return Some(match self.field {
                0 => &mut self.minutes,
                1 => &mut self.date,
                2 => &mut self.author,
                3 => &mut self.note,
                _ => &mut self.reason,
            });
        }
        // Delete: field 0 is the reason, field 1 is the confirmation.
        if self.field == 0 {
            Some(&mut self.reason)
        } else {
            None
        }
    }
}

/// The Time tab's filter editor (WP05 T026).
///
/// Edits the **same** [`crate::time_tracking::filters::TimeFilter`] the CLI's
/// `--issue/--assignee/--from/--to` builds and normalizes it through that type's own
/// `problems`, so an unreadable bound is refused by the shared DTO — with its message
/// and its remedy — rather than by a second filter grammar here. Nothing writes: a
/// filter is read-only session state, and applying one only replaces the scope the tab
/// is looking through.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TimeFilterForm {
    /// The issue criterion, as typed (`184`).
    pub issue: String,
    /// The assignee criterion, as typed.
    pub assignee: String,
    /// The inclusive lower period bound, `YYYY-MM-DD`.
    pub from: String,
    /// The inclusive upper period bound, `YYYY-MM-DD`.
    pub to: String,
    /// Which field the cursor is in.
    pub field: usize,
    /// The last refusal from the shared filter validator, with its remedy.
    pub error: Option<String>,
}

impl TimeFilterForm {
    /// An editor pre-filled from the filter in force, so the reader edits rather than
    /// retypes the scope.
    pub fn from_filter(filter: &crate::time_tracking::filters::TimeFilter) -> Self {
        Self {
            issue: filter
                .issue
                .map(|number| number.to_string())
                .unwrap_or_default(),
            assignee: filter.assignee.clone().unwrap_or_default(),
            from: filter.date_from.clone().unwrap_or_default(),
            to: filter.date_to.clone().unwrap_or_default(),
            field: 0,
            error: None,
        }
    }

    /// The fields `Tab` walks.
    pub const FIELD_COUNT: usize = 4;

    /// The field the cursor is in, by name.
    pub fn field_name(&self) -> &'static str {
        match self.field {
            0 => "issue",
            1 => "assignee",
            2 => "from",
            _ => "to",
        }
    }

    /// The text of the focused field.
    fn focused_text_mut(&mut self) -> &mut String {
        match self.field {
            0 => &mut self.issue,
            1 => &mut self.assignee,
            2 => &mut self.from,
            _ => &mut self.to,
        }
    }

    /// The filter this form describes, normalized through the shared type.
    ///
    /// The bounds and the identity go through [`TimeFilter::problems`], so the refusal
    /// is the shared DTO's own (message and remedy); the only refusal raised here is
    /// the issue criterion's *shape*, which the shared type does not have a variant for
    /// because the CLI receives it as a number from `clap` — a TUI text field has to
    /// say so itself.
    ///
    /// [`TimeFilter::problems`]: crate::time_tracking::filters::TimeFilter::problems
    pub fn to_filter(
        &self,
    ) -> std::result::Result<crate::time_tracking::filters::TimeFilter, String> {
        let mut filter = crate::time_tracking::filters::TimeFilter::new();
        let issue = self.issue.trim();
        if !issue.is_empty() {
            let number: u32 = issue.parse().map_err(|_| {
                format!(
                    "the issue criterion {issue:?} is not an issue number; write it as digits \
                     (e.g. `184`), or leave it empty for every issue"
                )
            })?;
            filter = filter.for_issue(number);
        }
        let assignee = self.assignee.trim();
        if !assignee.is_empty() {
            filter = filter.for_assignee(assignee);
        }
        let from = self.from.trim();
        let to = self.to.trim();
        if !from.is_empty() {
            filter = filter.since(from);
        }
        if !to.is_empty() {
            filter = filter.until(to);
        }
        match filter.problems().into_iter().next() {
            Some(problem) => Err(format!(
                "{} ({}): {} — {}",
                problem.kind(),
                problem.field(),
                problem.message(),
                problem.remedy()
            )),
            None => Ok(filter),
        }
    }
}

impl App {
    /// The Time tab's keys (WP05 T025–T027): walk the entry rows, add, correct and
    /// delete through the shared service, edit the filter, cycle the breakdown,
    /// toggle the audit view.
    ///
    /// Every action key opens a form (or a view) and writes nothing; the only writing
    /// path is the form's `Enter`, which reaches
    /// [`crate::time_tracking::service::apply`].
    pub(in crate::app) fn handle_time_tab_key(&mut self, key: KeyEvent) -> Result<Action> {
        if self.stats_time.is_none() {
            // A path that reached the Time tab without the `Tab` key (a click on the
            // strip) still reads before it acts.
            self.refresh_stats_time();
        }
        if let Some(state) = self.stats_time.as_mut() {
            state.clamp();
        }
        match key.code {
            KeyCode::Up | KeyCode::Char('k') => {
                if let Some(state) = self.stats_time.as_mut() {
                    state.move_cursor(-1);
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if let Some(state) = self.stats_time.as_mut() {
                    state.move_cursor(1);
                }
            }
            KeyCode::Enter => {
                // `Enter` opens the row's issue's detail, exactly as it does on the
                // Health tab: the page is a reader, and the pane it opens is where the
                // issue's own time block (and, from there, its health form) lives.
                if let Some((number, _)) = self.selected_time_entry() {
                    match self.store.get(IssueSelector::Number(number)) {
                        Ok(issue) => self.open_detail_root(issue)?,
                        Err(error) => self.status_msg = Some(error.to_string()),
                    }
                }
            }
            KeyCode::Char('a') => return self.open_time_add_form(),
            KeyCode::Char('e') => return self.open_time_edit_form(),
            KeyCode::Char('x') => return self.open_time_delete_form(),
            KeyCode::Char('f') => return self.open_time_filter_form(),
            KeyCode::Char('s') => {
                if let Some(state) = self.stats_time.as_mut() {
                    state.breakdown = state.breakdown.next();
                }
            }
            KeyCode::Char('h') => {
                if let Some(state) = self.stats_time.as_mut() {
                    state.audit = !state.audit;
                }
            }
            _ => {}
        }
        Ok(Action::None)
    }

    /// Take the Time tab's **one** read (WP05 T026).
    ///
    /// The same read `tix time total` performs — one
    /// [`TimeSnapshot`](crate::time_tracking::aggregate::TimeSnapshot) over the
    /// project's active issues — taken once per refresh rather than per frame, because
    /// a render must not read the disk (the rule the health document follows). The
    /// reader's filter, breakdown and audit toggle are session state and survive; only
    /// the data is replaced, and the entry cursor is clamped so a deletion cannot leave
    /// it past the end.
    pub(in crate::app) fn refresh_stats_time(&mut self) {
        let Ok(issues) = self.store.list() else {
            // A read that failed must not be reported as "nothing recorded": keep what
            // the tab already had, or leave it unread — which the tab says out loud.
            return;
        };
        let snapshot = crate::time_tracking::aggregate::TimeSnapshot::of(&issues);
        let mut state = match self.stats_time.take() {
            Some(previous) => {
                let mut state = StatsTimeState::new(snapshot);
                state.filter = previous.filter;
                state.breakdown = previous.breakdown;
                state.audit = previous.audit;
                state.cursor = previous.cursor;
                state
            }
            None => StatsTimeState::new(snapshot),
        };
        state.clamp();
        self.stats_time = Some(state);
    }

    /// The entry row the mutations act on, with its issue, cloned so the caller can
    /// borrow `self` mutably afterwards.
    pub(in crate::app) fn selected_time_entry(
        &self,
    ) -> Option<(u32, crate::time_tracking::TimeEntry)> {
        self.stats_time
            .as_ref()
            .and_then(|state| state.selected())
            .map(|indexed| (indexed.issue, indexed.entry.clone()))
    }

    /// Open the add form (WP05 T025). Its issue selector is pre-filled from the tab's
    /// filter when that names one issue, which is the common case: filter to an issue,
    /// then add to it.
    pub(in crate::app) fn open_time_add_form(&mut self) -> Result<Action> {
        let default_issue = self
            .stats_time
            .as_ref()
            .and_then(|state| state.filter.issue)
            .map(|number| number.to_string())
            .unwrap_or_default();
        self.time_return = Some(Mode::Stats);
        self.time_form = Some(TimeForm::add(default_issue));
        self.mode = Mode::TimeForm;
        Ok(Action::None)
    }

    /// Open the correction form for the selected entry.
    pub(in crate::app) fn open_time_edit_form(&mut self) -> Result<Action> {
        let Some((issue, entry)) = self.selected_time_entry() else {
            self.status_msg =
                Some("select a time entry first: `j`/`k` walk the tab's entry rows".into());
            return Ok(Action::None);
        };
        self.time_return = Some(Mode::Stats);
        self.time_form = Some(TimeForm::edit(issue, &entry));
        self.mode = Mode::TimeForm;
        Ok(Action::None)
    }

    /// Open the deletion form for the selected entry. It asks for a reason and a
    /// confirmation, exactly as `tix time delete --reason … --confirm` does.
    pub(in crate::app) fn open_time_delete_form(&mut self) -> Result<Action> {
        let Some((issue, entry)) = self.selected_time_entry() else {
            self.status_msg =
                Some("select a time entry first: `j`/`k` walk the tab's entry rows".into());
            return Ok(Action::None);
        };
        self.time_return = Some(Mode::Stats);
        self.time_form = Some(TimeForm::delete(issue, &entry));
        self.mode = Mode::TimeForm;
        Ok(Action::None)
    }

    /// Open the filter editor over the tab's current scope (WP05 T026).
    pub(in crate::app) fn open_time_filter_form(&mut self) -> Result<Action> {
        let filter = self
            .stats_time
            .as_ref()
            .map(|state| state.filter.clone())
            .unwrap_or_default();
        self.time_filter_form = Some(TimeFilterForm::from_filter(&filter));
        self.mode = Mode::TimeFilterForm;
        Ok(Action::None)
    }

    /// Show a refusal in the form that raised it, without closing the form.
    pub(in crate::app) fn time_form_error(&mut self, message: String) {
        if let Some(form) = self.time_form.as_mut() {
            form.error = Some(message.clone());
        }
        self.status_msg = Some(message);
    }

    /// The time form's keys: `Tab` walks the fields, `space` toggles the deletion's
    /// confirmation (only in the confirm field, so a reason may contain a space),
    /// `Enter` submits, `Esc` leaves without writing.
    pub(in crate::app) fn handle_time_form_key(&mut self, key: KeyEvent) -> Result<Action> {
        if !matches!(self.mode, Mode::TimeForm) {
            return Ok(Action::None);
        }
        match key.code {
            KeyCode::Esc => {
                self.time_form = None;
                self.mode = self.time_return.take().unwrap_or(Mode::Stats);
            }
            KeyCode::Tab => {
                if let Some(form) = self.time_form.as_mut() {
                    let count = form.field_count();
                    form.field = (form.field + 1) % count;
                }
            }
            KeyCode::BackTab => {
                if let Some(form) = self.time_form.as_mut() {
                    let count = form.field_count();
                    form.field = (form.field + count - 1) % count;
                }
            }
            KeyCode::Char(' ') => {
                if let Some(form) = self.time_form.as_mut() {
                    if form.is_delete() && form.field != 0 {
                        form.confirm = !form.confirm;
                    } else if let Some(text) = form.focused_text_mut() {
                        text.push(' ');
                    }
                }
            }
            KeyCode::Backspace => {
                if let Some(form) = self.time_form.as_mut()
                    && let Some(text) = form.focused_text_mut()
                {
                    text.pop();
                }
            }
            KeyCode::Enter => return self.submit_time_form(),
            KeyCode::Char(c) => {
                if let Some(form) = self.time_form.as_mut()
                    && let Some(text) = form.focused_text_mut()
                {
                    text.push(c);
                }
            }
            _ => {}
        }
        Ok(Action::None)
    }

    /// Submit the time form through the shared service (WP05 T025).
    ///
    /// The request is the service's own —
    /// [`TimeMutationRequest::create`](crate::time_tracking::service::TimeMutationRequest::create)
    /// and its siblings — and [`crate::time_tracking::service::apply`] is the one seam
    /// that validates, stages and writes. A refusal therefore writes nothing at all,
    /// and the form **stays open** carrying the service's own message (and, for a
    /// deletion, the remedy the CLI states), so a refused submission cannot look like a
    /// silent one and the reader keeps what they typed.
    pub(in crate::app) fn submit_time_form(&mut self) -> Result<Action> {
        let Some(form) = self.time_form.clone() else {
            self.mode = Mode::Stats;
            return Ok(Action::None);
        };
        let request = match Self::time_request(&form) {
            Ok(request) => request,
            Err(message) => {
                self.time_form_error(message);
                return Ok(Action::None);
            }
        };
        match crate::time_tracking::service::apply(&self.store, &request) {
            Ok(applied) => {
                self.time_form = None;
                self.mode = self.time_return.take().unwrap_or(Mode::Stats);
                // The write changed an issue, so both readers of it are re-derived: the
                // tab's snapshot (which no other refresh would notice) and the detail
                // pane, whose time block is built from the issue it holds.
                self.refresh_stats_time();
                self.refresh_detail()?;
                let verb = match form.kind {
                    TimeFormKind::Add => "added",
                    TimeFormKind::Edit { .. } => "corrected",
                    TimeFormKind::Delete { .. } => "deleted",
                };
                self.status_msg = Some(if applied.outcome.changed {
                    format!(
                        "time: {verb} {} on #{}",
                        applied.outcome.entry_id, applied.issue.number
                    )
                } else {
                    // The one no-op case: the edit named exactly what is recorded, so
                    // no event was appended and `updated` was not bumped.
                    format!(
                        "time: {} unchanged — the correction names the recorded value",
                        applied.outcome.entry_id
                    )
                });
                Ok(Action::None)
            }
            Err(error) => {
                self.time_form_error(error.to_string());
                Ok(Action::None)
            }
        }
    }

    /// The request a form describes, or the message to show when the form is not yet
    /// answerable — a duration that is not a whole number, or an add that names no
    /// issue. Everything else (a blank reason, an unknown entry, an unknown issue, a
    /// negative duration, an unreadable date) is left to the service, so the refusal
    /// has one owner and one wording.
    ///
    /// An associated function, not a method: nothing about the App decides the
    /// request, and a reader should be able to see that at the signature.
    pub(in crate::app) fn time_request(
        form: &TimeForm,
    ) -> std::result::Result<crate::time_tracking::service::TimeMutationRequest, String> {
        match &form.kind {
            TimeFormKind::Add => {
                let issue = form.issue.trim();
                if issue.is_empty() {
                    return Err(
                        "a time entry belongs to an issue: name one — its number (e.g. `184`) or \
                         its id"
                            .to_string(),
                    );
                }
                let minutes = feed_minutes(&form.minutes, "enter an integer at or above zero")?;
                let author = if form.author.trim().is_empty() {
                    crate::storage::actor_identity()
                } else {
                    form.author.trim().to_string()
                };
                let mut entry = crate::time_tracking::service::NewTimeEntry::new(minutes, author);
                if !form.date.trim().is_empty() {
                    entry = entry.on(form.date.trim());
                }
                if !form.note.trim().is_empty() {
                    entry = entry.with_note(form.note.trim());
                }
                Ok(crate::time_tracking::service::TimeMutationRequest::create(
                    issue, entry,
                ))
            }
            TimeFormKind::Edit { issue, entry_id } => {
                let mut change = crate::time_tracking::service::TimeEntryEdit::new();
                if !form.minutes.trim().is_empty() {
                    change = change.duration(feed_minutes(
                        &form.minutes,
                        "leave it empty to keep the recorded value",
                    )?);
                }
                if !form.date.trim().is_empty() {
                    change = change.date(form.date.trim());
                }
                if !form.author.trim().is_empty() {
                    change = change.author(form.author.trim());
                }
                if !form.note.trim().is_empty() {
                    change = change.note(form.note.trim());
                }
                Ok(crate::time_tracking::service::TimeMutationRequest::edit(
                    issue.to_string(),
                    entry_id.clone(),
                    change,
                    form.reason.trim().to_string(),
                ))
            }
            TimeFormKind::Delete { issue, entry_id } => {
                if !form.confirm {
                    return Err(
                        "deleting a time entry needs confirmation: it removes the entry from the \
                         issue's current entries, while its value and its event stay in History \
                         (the tab's `h` view reads them back) — press `space` in the confirm field"
                            .to_string(),
                    );
                }
                Ok(crate::time_tracking::service::TimeMutationRequest::delete(
                    issue.to_string(),
                    entry_id.clone(),
                    form.reason.trim().to_string(),
                ))
            }
        }
    }

    /// The filter editor's keys, read raw: `Tab` walks the fields, `Enter` applies,
    /// `Esc` leaves. All four fields are free text, so the letters are letters.
    pub(in crate::app) fn handle_time_filter_form_key(&mut self, key: KeyEvent) -> Result<Action> {
        if !matches!(self.mode, Mode::TimeFilterForm) {
            return Ok(Action::None);
        }
        match key.code {
            KeyCode::Esc => {
                self.time_filter_form = None;
                self.mode = Mode::Stats;
            }
            KeyCode::Tab => {
                if let Some(form) = self.time_filter_form.as_mut() {
                    form.field = (form.field + 1) % TimeFilterForm::FIELD_COUNT;
                }
            }
            KeyCode::BackTab => {
                if let Some(form) = self.time_filter_form.as_mut() {
                    form.field = (form.field + TimeFilterForm::FIELD_COUNT - 1)
                        % TimeFilterForm::FIELD_COUNT;
                }
            }
            KeyCode::Backspace => {
                if let Some(form) = self.time_filter_form.as_mut() {
                    form.focused_text_mut().pop();
                }
            }
            KeyCode::Enter => return self.submit_time_filter_form(),
            KeyCode::Char(c) => {
                if let Some(form) = self.time_filter_form.as_mut() {
                    form.focused_text_mut().push(c);
                }
            }
            _ => {}
        }
        Ok(Action::None)
    }

    /// Apply the filter editor (WP05 T026).
    ///
    /// Nothing is written: a filter is session state, and applying one only replaces
    /// the scope the tab reads through. An unreadable scope is refused by the shared
    /// [`TimeFilter`](crate::time_tracking::filters::TimeFilter)'s own validator, whose
    /// message **and remedy** the form shows while staying open.
    pub(in crate::app) fn submit_time_filter_form(&mut self) -> Result<Action> {
        let Some(form) = self.time_filter_form.clone() else {
            self.mode = Mode::Stats;
            return Ok(Action::None);
        };
        match form.to_filter() {
            Ok(filter) => {
                self.time_filter_form = None;
                self.mode = Mode::Stats;
                if let Some(state) = self.stats_time.as_mut() {
                    state.filter = filter.clone();
                    // The rows the cursor indexed may be gone or different, so the
                    // cursor resets to the first of the new scope.
                    state.cursor = 0;
                    state.clamp();
                }
                self.status_msg = Some(format!("time: scope {}", filter.describe()));
                Ok(Action::None)
            }
            Err(message) => {
                // The refusal is the shared validator's own sentence, remedy and all;
                // the form keeps it so the reader can fix the field.
                if let Some(open) = self.time_filter_form.as_mut() {
                    open.error = Some(message.clone());
                }
                self.status_msg = Some(message);
                Ok(Action::None)
            }
        }
    }
}