aimcal-cli 0.12.1

AIM - Analyze. Interact. Manage Your Time, with calendar support
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
// SPDX-FileCopyrightText: 2025-2026 Zexin Yuan <aim@yzx9.xyz>
//
// SPDX-License-Identifier: Apache-2.0

use std::error::Error;

use aimcal_core::{
    Aim, DateTimeAnchor, Event, EventConditions, EventDraft, EventPatch, EventStatus, Id, Kind,
    LooseDateTime, Pager,
};
use clap::{ArgMatches, Command};
use colored::Colorize;

use crate::arg::CalendarArgs;
use crate::arg::{CommonArgs, EventArgs, EventOrTodoArgs};
use crate::event_formatter::{EventColumn, EventFormatter};
use crate::prompt::{DuplicateChoice, is_terminal, prompt_duplicate_choice, prompt_time};
use crate::tui;
use crate::util::{OutputFormat, parse_datetime, parse_datetime_range};

#[derive(Debug, Clone)]
pub struct CmdEventNew {
    pub calendar_id: Option<String>,
    pub description: Option<String>,
    pub end: Option<String>,
    pub start: Option<String>,
    pub status: Option<EventStatus>,
    pub summary: Option<String>,

    pub output_format: OutputFormat,
}

impl CmdEventNew {
    pub const NAME: &str = "new";

    pub fn command() -> Command {
        let (args, event_args) = args();
        Command::new(Self::NAME)
            .alias("add")
            .about("Add a new event")
            .arg(args.summary(true))
            .arg(CalendarArgs::new(true).calendar())
            .arg(event_args.start())
            .arg(event_args.end())
            .arg(args.description())
            .arg(event_args.status())
            .arg(CommonArgs::output_format())
    }

    pub fn from(matches: &ArgMatches) -> Self {
        Self {
            calendar_id: CalendarArgs::get_calendar(matches),
            description: EventOrTodoArgs::get_description(matches),
            start: EventArgs::get_start(matches),
            end: EventArgs::get_end(matches),
            status: EventArgs::get_status(matches),
            summary: EventOrTodoArgs::get_summary(matches),

            output_format: CommonArgs::get_output_format(matches),
        }
    }

    pub async fn run(self, aim: &mut Aim) -> Result<(), Box<dyn Error>> {
        tracing::debug!(?self, "adding new event...");

        let tui = self.tui();
        let now = aim.now();

        // Prepare a draft with the provided arguments
        let mut draft = aim.default_event_draft();

        match (self.start, self.end) {
            (Some(start), Some(end)) => {
                (draft.start, draft.end) = parse_datetime_range(&now, &start, &end)?;
            }
            (Some(start), None) => {
                draft.start = parse_datetime(&now, &start)?;
                draft.end = None;
            }
            (None, Some(end)) => {
                draft.start = None;
                draft.end = parse_datetime(&now, &end)?;
            }
            (None, None) => {}
        }

        if let Some(description) = self.description {
            draft.description = Some(description);
        }

        draft.calendar_id = self.calendar_id;

        if let Some(status) = self.status {
            draft.status = status;
        }

        if let Some(summary) = self.summary {
            draft.summary = summary;
        }

        // If TUI is needed, launch the TUI to edit the draft
        if tui {
            let Some(draft_tui) = tui::draft_event(aim, draft)? else {
                tracing::info!("user cancel the event creation");
                return Ok(());
            };
            draft = draft_tui;
        }

        // Create the event
        Self::new_event(aim, draft, self.output_format).await
    }

    pub async fn new_event(
        aim: &mut Aim,
        draft: EventDraft,
        output_format: OutputFormat,
    ) -> Result<(), Box<dyn Error>> {
        // Duplicate detection: check for existing events with same summary
        if !draft.summary.is_empty() && is_terminal() {
            let uid = match aim.find_latest_event_by_summary(&draft.summary).await? {
                Some(existing) => {
                    let existing_id = existing
                        .short_id()
                        .map_or_else(|| existing.uid().into_owned(), |id| id.get().to_string());
                    let choice = prompt_duplicate_choice("Event", &existing_id, &draft.summary)?;
                    match choice {
                        DuplicateChoice::UpdateExisting => Some(existing.uid().into_owned()),
                        DuplicateChoice::CreateNew => None,
                    }
                }
                None => None,
            };
            if let Some(uid) = uid {
                let event = aim.update_event(&Id::Uid(uid), draft.into()).await?;
                print_events(aim, &[event], output_format);
                return Ok(());
            }
        }

        let event = aim.new_event(draft).await?;
        print_events(aim, &[event], output_format);
        Ok(())
    }

    pub(crate) fn tui(&self) -> bool {
        Self::need_tui(&self.summary, &self.start)
    }

    /// Determine whether TUI is needed based on the provided arguments.
    #[expect(clippy::ref_option)]
    pub(crate) fn need_tui(summary: &Option<String>, start: &Option<String>) -> bool {
        summary.is_none() || start.is_none()
    }
}

#[derive(Debug, Clone)]
pub struct CmdEventEdit {
    pub id: Id,
    pub description: Option<String>,
    pub end: Option<String>,
    pub start: Option<String>,
    pub status: Option<EventStatus>,
    pub summary: Option<String>,

    pub output_format: OutputFormat,
}

impl CmdEventEdit {
    pub const NAME: &str = "edit";

    pub fn command() -> Command {
        let (args, event_args) = args();
        Command::new(Self::NAME)
            .about("Edit a event item")
            .arg(args.id())
            .arg(args.summary(false))
            .arg(event_args.start())
            .arg(event_args.end())
            .arg(args.description())
            .arg(event_args.status())
            .arg(CommonArgs::output_format())
    }

    pub fn from(matches: &ArgMatches) -> Self {
        Self {
            id: EventOrTodoArgs::get_id(matches),
            description: EventOrTodoArgs::get_description(matches),
            start: EventArgs::get_start(matches),
            end: EventArgs::get_end(matches),
            status: EventArgs::get_status(matches),
            summary: EventOrTodoArgs::get_summary(matches),

            output_format: CommonArgs::get_output_format(matches),
        }
    }

    pub fn new_tui(id: Id, output_format: OutputFormat) -> Self {
        Self {
            id,
            description: None,
            end: None,
            start: None,
            status: None,
            summary: None,

            output_format,
        }
    }

    pub async fn run(self, aim: &mut Aim) -> Result<(), Box<dyn Error>> {
        tracing::debug!(?self, "editing event...");
        let tui = self.tui();

        // Prepare the patch with the provided arguments
        let (start, end) = match (self.start, self.end) {
            (Some(start), Some(end)) => {
                let (a, b) = parse_datetime_range(&aim.now(), &start, &end)?;
                (Some(a), Some(b))
            }
            (Some(start), None) => (Some(parse_datetime(&aim.now(), &start)?), None),
            (None, Some(end)) => (None, Some(parse_datetime(&aim.now(), &end)?)),
            (None, None) => (None, None),
        };
        let mut patch = EventPatch {
            description: self.description.map(|d| (!d.is_empty()).then_some(d)),
            end,
            start,
            status: self.status,
            summary: self.summary,
        };

        // If TUI is needed, launch the TUI to edit the event
        if tui {
            let event = aim.get_event(&self.id).await?;
            patch = if let Some(data) = tui::patch_event(aim, &event, patch)? {
                data
            } else {
                tracing::info!("user cancel the event editing");
                return Ok(());
            }
        }

        // Update the event
        let event = aim.update_event(&self.id, patch).await?;
        print_events(aim, &[event], self.output_format);
        Ok(())
    }

    /// Determine whether TUI is needed based on the provided arguments.
    pub(crate) fn tui(&self) -> bool {
        self.description.is_none()
            && self.end.is_none()
            && self.start.is_none()
            && self.status.is_none()
            && self.summary.is_none()
    }
}

#[derive(Debug, Clone)]
pub struct CmdEventDelay {
    pub ids: Vec<Id>,
    pub time: Option<DateTimeAnchor>,
    pub output_format: OutputFormat,
}

impl CmdEventDelay {
    pub const NAME: &str = "delay";

    pub fn command() -> Command {
        let (args, _event_args) = args();
        Command::new(Self::NAME)
            .about("Delay an event's time by a specified time based on original start")
            .arg(args.ids())
            .arg(args.time("delay"))
            .arg(CommonArgs::output_format())
    }

    pub fn from(matches: &ArgMatches) -> Self {
        Self {
            ids: EventOrTodoArgs::get_ids(matches),
            time: EventOrTodoArgs::get_time(matches),
            output_format: CommonArgs::get_output_format(matches),
        }
    }

    pub async fn run(self, aim: &mut Aim) -> Result<(), Box<dyn Error>> {
        tracing::debug!(?self, "delaying event...");

        // Prompt for time if not provided
        let time = match self.time {
            Some(t) => t,
            None => prompt_time()?,
        };

        // Calculate new start and end based on original start and end if exists, otherwise based on now
        // TODO: move these logics to core crate, same for reschedule command
        let mut events = Vec::with_capacity(self.ids.len());
        for id in &self.ids {
            let event = aim.get_event(id).await?;
            let (start, end) = match (event.start(), event.end()) {
                (Some(start), end) => {
                    let s = time.clone().resolve_at(&start);
                    let e = end.map(|a| time.clone().resolve_at(&a));
                    (Some(s), e)
                }
                (None, Some(end)) => {
                    // TODO: should we set a start time with default duration? same for reschedule command
                    let e = time.clone().resolve_at(&end);
                    (None, Some(e))
                }
                (None, None) => {
                    let s = time
                        .clone()
                        .resolve_since_zoned(&aim.now())
                        .map_err(|e| format!("Failed to resolve since zoned: {e}"))?;
                    // TODO: should we set a end time with default duration? same for reschedule command
                    (Some(s), None)
                }
            };

            // Update the event
            let patch = EventPatch {
                start: Some(start),
                end: Some(end),
                ..Default::default()
            };

            let event = aim.update_event(id, patch).await?;
            events.push(event);
        }
        print_events(aim, &events, self.output_format);
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct CmdEventReschedule {
    pub ids: Vec<Id>,
    pub time: Option<DateTimeAnchor>,
    pub output_format: OutputFormat,
}

impl CmdEventReschedule {
    pub const NAME: &str = "reschedule";

    pub fn command() -> Command {
        let (args, _event_args) = args();
        Command::new(Self::NAME)
            .about("Reschedule event's due to a specified time based on now")
            .arg(args.ids())
            .arg(args.time("reschedule"))
            .arg(CommonArgs::output_format())
    }

    pub fn from(matches: &ArgMatches) -> Self {
        Self {
            ids: EventOrTodoArgs::get_ids(matches),
            time: EventOrTodoArgs::get_time(matches),
            output_format: CommonArgs::get_output_format(matches),
        }
    }

    pub async fn run(self, aim: &mut Aim) -> Result<(), Box<dyn Error>> {
        tracing::debug!(?self, "rescheduling event...");

        // Prompt for time if not provided
        let time = match self.time {
            Some(t) => t,
            None => prompt_time()?,
        };

        // Calculate new start and end based on original start and end if exists, otherwise based on now
        let mut events = Vec::with_capacity(self.ids.len());
        for id in &self.ids {
            let event = aim.get_event(id).await?;
            let (start, end) = match (event.start(), event.end()) {
                (Some(start), Some(end)) => {
                    use LooseDateTime::{DateOnly, Floating, Local};
                    let s = time
                        .clone()
                        .resolve_since_zoned(&aim.now())
                        .map_err(|e| format!("Failed to resolve since zoned: {e}"))?;
                    #[rustfmt::skip]
                    let e = match (start, end) {
                        (DateOnly(ds),  DateOnly(de))  => (s.date() + (de - ds)).into(),
                        (DateOnly(ds),  Floating(dte)) => (s.date() + (dte.date() - ds)).into(),
                        (DateOnly(ds),  Local(dte))    => (s.date() + (dte.date() - ds)).into(),
                        (Floating(dts), DateOnly(dte)) => s.clone() + (dte - dts.date()),
                        (Floating(dts), Floating(dte)) => s.clone() + (dte - dts),
                        (Floating(dts), Local(dte))    => s.clone() + (dte.datetime() - dts), // Treat zoned as civil datetime
                        (Local(dts),    DateOnly(de))  => s.clone() + (de - dts.date()),
                        (Local(dts),    Floating(dte)) => s.clone() + (dte - dts.datetime()), // Treat zoned as civil datetime
                        (Local(dts),    Local(dte))    => s.clone() + (dte - dts),
                    };
                    (Some(s), Some(e))
                }
                (_, None) => {
                    let s = time
                        .clone()
                        .resolve_since_zoned(&aim.now())
                        .map_err(|e| format!("Failed to resolve since zoned: {e}"))?;
                    (Some(s), None)
                }
                (None, Some(_)) => {
                    let e = time
                        .clone()
                        .resolve_since_zoned(&aim.now())
                        .map_err(|e| format!("Failed to resolve since zoned: {e}"))?;
                    (None, Some(e))
                }
            };

            // Update the event
            let patch = EventPatch {
                start: Some(start),
                end: Some(end),
                ..Default::default()
            };
            let event = aim.update_event(id, patch).await?;
            events.push(event);
        }
        print_events(aim, &events, self.output_format);
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct CmdEventList {
    pub conds: EventConditions,
    pub output_format: OutputFormat,
}

impl CmdEventList {
    pub const NAME: &str = "list";

    pub fn command() -> Command {
        Command::new(Self::NAME)
            .about("List events")
            .arg(CalendarArgs::new(true).calendar())
            .arg(CommonArgs::output_format())
    }

    pub fn from(matches: &ArgMatches) -> Self {
        Self {
            conds: EventConditions {
                startable: Some(DateTimeAnchor::today()),
                calendar_id: CalendarArgs::get_calendar(matches),
                ..Default::default()
            },
            output_format: CommonArgs::get_output_format(matches),
        }
    }

    pub async fn run(self, aim: &Aim) -> Result<(), Box<dyn Error>> {
        tracing::debug!(?self, "listing events...");
        Self::list(aim, &self.conds, self.output_format).await
    }

    /// List events with the given conditions and output format.
    #[expect(clippy::cast_possible_truncation)]
    pub async fn list(
        aim: &Aim,
        conds: &EventConditions,
        output_format: OutputFormat,
    ) -> Result<(), Box<dyn Error>> {
        const LIMIT: i64 = 128;

        let pager: Pager = (LIMIT, 0).into();
        let events = aim.list_events(conds, &pager).await?;
        if events.len() >= (LIMIT as usize) {
            let total = aim.count_events(conds).await?;
            if total > LIMIT {
                let prompt = format!("Displaying the {LIMIT}/{total} events");
                println!("{}", prompt.italic());
            }
        } else if events.is_empty() && output_format == OutputFormat::Table {
            println!("{}", "No events found".italic());
            return Ok(());
        }

        print_events(aim, &events, output_format);
        Ok(())
    }
}

const fn args() -> (EventOrTodoArgs, EventArgs) {
    (
        EventOrTodoArgs::new(Some(Kind::Event)),
        EventArgs::new(true),
    )
}

fn print_events(aim: &Aim, events: &[impl Event], output_format: OutputFormat) {
    use EventColumn::{DateTimeSpan, Id, ShortId, Summary, Uid};
    let columns = match output_format {
        OutputFormat::Table => vec![Id, DateTimeSpan, Summary],
        OutputFormat::Json => vec![Uid, ShortId, DateTimeSpan, Summary],
    };
    let formatter = EventFormatter::new(aim.now(), columns, output_format);
    println!("{}", formatter.format(events));
}

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

    #[test]
    fn parses_event_new_command() {
        let args = [
            "new",
            "Another summary",
            "--calendar",
            "work",
            "--description",
            "A description",
            "--start",
            "2025-01-01 12:00:00",
            "--end",
            "2025-01-01 14:00:00",
            "--status",
            "tentative",
            "--output-format",
            "json",
        ];
        let matches = CmdEventNew::command().try_get_matches_from(args).unwrap();
        let parsed = CmdEventNew::from(&matches);

        assert_eq!(parsed.description, Some("A description".to_string()));
        assert_eq!(parsed.calendar_id, Some("work".to_string()));
        assert_eq!(parsed.end, Some("2025-01-01 14:00:00".to_string()));
        assert_eq!(parsed.start, Some("2025-01-01 12:00:00".to_string()));
        assert_eq!(parsed.status, Some(EventStatus::Tentative));
        assert_eq!(parsed.summary, Some("Another summary".to_string()));

        assert!(!parsed.tui());
        assert_eq!(parsed.output_format, OutputFormat::Json);
    }

    #[test]
    fn parses_event_new_command_with_tui_mode() {
        let args = ["new"];
        let matches = CmdEventNew::command().try_get_matches_from(args).unwrap();
        let parsed = CmdEventNew::from(&matches);

        assert!(parsed.tui());
    }

    #[test]
    fn parses_event_edit_command() {
        let args = [
            "edit",
            "test_id",
            "--description",
            "A description",
            "--start",
            "2025-01-01 12:00:00",
            "--end",
            "2025-01-01 14:00:00",
            "--status",
            "tentative",
            "--summary",
            "Another summary",
            "--output-format",
            "json",
        ];
        let matches = CmdEventEdit::command().try_get_matches_from(args).unwrap();
        let parsed = CmdEventEdit::from(&matches);

        assert_eq!(parsed.id, Id::ShortIdOrUid("test_id".to_string()));
        assert_eq!(parsed.description, Some("A description".to_string()));
        assert_eq!(parsed.end, Some("2025-01-01 14:00:00".to_string()));
        assert_eq!(parsed.start, Some("2025-01-01 12:00:00".to_string()));
        assert_eq!(parsed.status, Some(EventStatus::Tentative));
        assert_eq!(parsed.summary, Some("Another summary".to_string()));

        assert!(!parsed.tui());
        assert_eq!(parsed.output_format, OutputFormat::Json);
    }

    #[test]
    fn parses_event_edit_command_with_tui_mode() {
        let cmd = CmdEventEdit::command();
        let matches = cmd.try_get_matches_from(["edit", "test_id"]).unwrap();
        let parsed = CmdEventEdit::from(&matches);

        assert!(parsed.tui());
        assert_eq!(parsed.id, Id::ShortIdOrUid("test_id".to_string()));
    }

    #[test]
    fn parses_event_delay_command() {
        let args = [
            "delay",
            "a",
            "b",
            "c",
            "--time",
            "1d",
            "--output-format",
            "json",
        ];
        let matches = CmdEventDelay::command().try_get_matches_from(args).unwrap();
        let parsed = CmdEventDelay::from(&matches);

        let expected_ids = vec![
            Id::ShortIdOrUid("a".to_string()),
            Id::ShortIdOrUid("b".to_string()),
            Id::ShortIdOrUid("c".to_string()),
        ];
        assert_eq!(parsed.ids, expected_ids);
        assert_eq!(parsed.time, Some(DateTimeAnchor::InDays(1)));
        assert_eq!(parsed.output_format, OutputFormat::Json);
    }

    #[test]
    fn parses_event_reschedule_command() {
        let args = [
            "reschedule",
            "a",
            "b",
            "c",
            "--time",
            "1d",
            "--output-format",
            "json",
        ];
        let matches = CmdEventReschedule::command()
            .try_get_matches_from(args)
            .unwrap();
        let parsed = CmdEventReschedule::from(&matches);

        let expected_ids = vec![
            Id::ShortIdOrUid("a".to_string()),
            Id::ShortIdOrUid("b".to_string()),
            Id::ShortIdOrUid("c".to_string()),
        ];
        assert_eq!(parsed.ids, expected_ids);
        assert_eq!(parsed.time, Some(DateTimeAnchor::InDays(1)));
        assert_eq!(parsed.output_format, OutputFormat::Json);
    }

    #[test]
    fn parses_event_list_command() {
        let args = ["list", "--calendar", "work", "--output-format", "json"];
        let matches = CmdEventList::command().try_get_matches_from(args).unwrap();
        let parsed = CmdEventList::from(&matches);

        assert_eq!(parsed.conds.calendar_id, Some("work".to_string()));
        assert_eq!(parsed.output_format, OutputFormat::Json);
    }
}