rtimelogger 0.8.8

A simple cross-platform CLI tool to track working hours, lunch breaks, and calculate surplus time
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
use crate::config::Config;
use crate::core::logic::Core;
use crate::db::pool::DbPool;
use crate::db::queries::{
    insert_event, load_events_by_date, load_pair_by_index, recalc_pairs_for_date,
};
use crate::errors::{AppError, AppResult};
use crate::models::event::{Event, EventExtras};
use crate::models::event_type::EventType;
use crate::models::location::Location;
use crate::ui::messages::success;
use crate::utils::date::{is_national_holiday, is_weekend};
use chrono::{NaiveDate, NaiveTime, Timelike};
use rusqlite::params;

/// High-level business logic for the `add` command.
pub struct AddLogic;

fn upsert_event(conn: &rusqlite::Connection, ev: &Event) -> AppResult<()> {
    if ev.id == 0 {
        insert_event(conn, ev)?;
    } else {
        crate::db::queries::update_event(conn, ev)?;
    }
    Ok(())
}

fn build_event_cli(
    date: NaiveDate,
    time: NaiveTime,
    kind: EventType,
    location: Location,
    event_extras: EventExtras,
) -> Event {
    Event::new(0, date, time, kind, location, event_extras)
}

fn extras_cli(lunch: Option<i32>, work_gap: bool) -> EventExtras {
    EventExtras {
        lunch,
        work_gap,
        source: Some("cli".to_string()),
        meta: None,
        ..Default::default()
    }
}

fn normalize_notes(notes: Option<String>) -> Option<String> {
    notes.and_then(|s| {
        let trimmed = s.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

fn set_notes(slot: &mut Option<Event>, notes: &Option<String>) {
    if let Some(e) = slot.as_mut() {
        e.notes = notes.clone();
    }
}

fn last_pair_index(conn: &rusqlite::Connection, date: &NaiveDate) -> AppResult<usize> {
    let max_pair: Option<i64> = conn.query_row(
        "SELECT MAX(pair) FROM events WHERE date = ?1 AND pair > 0",
        params![date.to_string()],
        |row| row.get(0),
    )?;

    match max_pair {
        Some(v) if v > 0 => Ok(v as usize),
        _ => Err(AppError::InvalidArgs(format!(
            "Cannot infer --pair for {}: no editable pair found.",
            date
        ))),
    }
}

fn upsert_event_time(
    slot: &mut Option<Event>,
    date: NaiveDate,
    time: NaiveTime,
    kind: EventType,
    location: Location,
    extras: EventExtras,
) {
    let e = slot.get_or_insert_with(|| build_event_cli(date, time, kind, location, extras));
    e.time = time;
}

impl AddLogic {
    #[allow(clippy::too_many_arguments)]
    pub fn apply(
        cfg: &Config,
        pool: &mut DbPool,
        date: NaiveDate,
        position: Location,
        start: Option<NaiveTime>,
        lunch: Option<i32>,
        work_gap: Option<bool>,
        end: Option<NaiveTime>,
        edit_mode: bool,
        edit_pair: Option<usize>,
        to: Option<NaiveDate>,
        pos: Option<String>,
        notes: Option<String>,
    ) -> AppResult<()> {
        let notes = normalize_notes(notes);

        // ------------------------------------------------
        // Resolve final position (only if --pos is provided)
        // ------------------------------------------------
        let pos_final = match &pos {
            Some(code) => Location::from_code(code).ok_or_else(|| {
                AppError::InvalidPosition(format!(
                    "Invalid location code '{}'. Use a valid code such as 'O', 'R', 'H', 'N', 'C', 'M', 'S'.\n",
                    code
                ))
            })?,
            None => position,
        };

        // ------------------------------------------------
        // Sanity: range args only allowed for SickLeave
        // ------------------------------------------------
        let range = match (date, to) {
            (f, Some(t)) => {
                if pos_final != Location::SickLeave {
                    return Err(AppError::InvalidArgs(
                        "--from/--to can only be used with --pos Malattia".into(),
                    ));
                }
                if f > t {
                    // se hai questa variante tipizzata, usa quella; altrimenti InvalidArgs
                    return Err(AppError::InvalidDateRange { from: f, to: t });
                }
                Some((f, t))
            }
            (_null, None) => None,
        };

        // ------------------------------------------------
        // 1️⃣ EDIT MODE
        // ------------------------------------------------
        if edit_mode {
            if range.is_some() {
                return Err(AppError::InvalidArgs(
                    "--from/--to cannot be used with --edit.".into(),
                ));
            }

            let pair_num = match edit_pair {
                Some(pair) => pair,
                None => last_pair_index(&pool.conn, &date)?,
            };

            let (mut ev_in, mut ev_out) = load_pair_by_index(&pool.conn, &date, pair_num)?;

            // POSITION (apply only if --pos explicitly provided)
            if pos.is_some() {
                if let Some(ref mut e) = ev_in {
                    e.location = pos_final;
                }
                if let Some(ref mut e) = ev_out {
                    e.location = pos_final;
                }
            }

            // IN time
            if let Some(start_time) = start {
                upsert_event_time(
                    &mut ev_in,
                    date,
                    start_time,
                    EventType::In,
                    pos_final,
                    extras_cli(lunch, false),
                );
            }

            // OUT time
            if let Some(end_time) = end {
                upsert_event_time(
                    &mut ev_out,
                    date,
                    end_time,
                    EventType::Out,
                    pos_final,
                    extras_cli(Some(0), false),
                );
            }

            // LUNCH (applies to OUT)
            if let Some(lunch_val) = lunch
                && let Some(ref mut e) = ev_out
            {
                e.lunch = Some(lunch_val);
            }

            // NOTES (apply to every event belonging to the pair)
            if notes.is_some() {
                set_notes(&mut ev_in, &notes);
                set_notes(&mut ev_out, &notes);
            }

            // WORK GAP (only if explicitly requested; requires OUT)
            if let Some(wg) = work_gap {
                if let Some(ref mut e) = ev_out {
                    e.work_gap = wg;
                } else {
                    return Err(AppError::InvalidArgs(
                        "Cannot modify --work-gap: pair has no OUT event.".into(),
                    ));
                }
            }

            // Save
            if let Some(ref e) = ev_in {
                upsert_event(&pool.conn, e)?;
            }
            if let Some(ref e) = ev_out {
                upsert_event(&pool.conn, e)?;
            }

            recalc_pairs_for_date(&pool.conn, &date)?;

            let (icon, msg) = match work_gap {
                Some(true) => ("🔗", "Work gap enabled"),
                Some(false) => ("✂️", "Work gap removed"),
                None => ("✏️", "Pair updated"),
            };

            success(format!("{} {} for pair {}.\n", icon, msg, pair_num));
            return Ok(());
        }

        // ------------------------------------------------
        // 2️⃣ INSERT MODE
        // ------------------------------------------------

        let lunch_val = lunch.unwrap_or(0);
        let wg = work_gap.unwrap_or(false);

        // --work-gap valid only with OUT present
        if wg && end.is_none() {
            return Err(AppError::InvalidArgs(
                "--work-gap can only be used when adding an OUT event.".into(),
            ));
        }

        // ------------------------------------------------
        // ✅ CASE: SickLeave marker day (like Holiday)
        // ------------------------------------------------
        if pos_final == Location::SickLeave {
            // Marker day: do not accept time/lunch/work-gap args
            if start.is_some() || end.is_some() || lunch.is_some() || work_gap.is_some() {
                return Err(AppError::InvalidArgs(
                    "For Sick Leave do not specify --in, --out, --lunch or --work-gap.".into(),
                ));
            }

            // Range: if omitted -> single-day (date,date)
            let (date, to_date) = match (date, to) {
                (f, Some(t)) => {
                    if f > t {
                        return Err(AppError::InvalidDateRange { from: f, to: t });
                    }
                    (f, t)
                }
                (_null, None) => (date, date),
            };

            // Sentinel time (00:00) like holiday
            let marker_time = NaiveTime::from_hms_opt(0, 0, 0)
                .ok_or_else(|| AppError::Other("Invalid Sick Leave time sentinel.".into()))?;

            let tx = pool.conn.transaction()?;

            let mut inserted = 0usize;
            let mut skipped_weekend = 0usize;
            let mut skipped_national = 0usize;
            let mut skipped_existing = 0usize;

            let mut day = date;
            while day <= to_date {
                // 1) weekend -> skip
                if is_weekend(day) {
                    skipped_weekend += 1;
                    day = day
                        .succ_opt()
                        .ok_or_else(|| AppError::Other("Invalid date increment.".into()))?;
                    continue;
                }

                // 2) national holiday -> skip
                if is_national_holiday(&tx, day)? {
                    skipped_national += 1;
                    day = day
                        .succ_opt()
                        .ok_or_else(|| AppError::Other("Invalid date increment.".into()))?;
                    continue;
                }

                // 3) already has events -> skip
                let day_str = day.to_string();
                let exists: i64 = tx.query_row(
                    "SELECT EXISTS(SELECT 1 FROM events WHERE date = ?1 LIMIT 1)",
                    rusqlite::params![day_str],
                    |r| r.get(0),
                )?;
                if exists == 1 {
                    skipped_existing += 1;
                    day = day
                        .succ_opt()
                        .ok_or_else(|| AppError::Other("Invalid date increment.".into()))?;
                    continue;
                }

                // 4) insert marker
                let mut ev = build_event_cli(
                    day,
                    marker_time, // 00:00
                    EventType::In,
                    Location::SickLeave,
                    extras_cli(Some(0), false),
                );
                ev.notes = notes.clone();

                insert_event(&tx, &ev)?;
                recalc_pairs_for_date(&tx, &day)?;
                inserted += 1;

                day = day
                    .succ_opt()
                    .ok_or_else(|| AppError::Other("Invalid date increment.".into()))?;
            }

            tx.commit()?;

            // output summary
            if to_date == date {
                if inserted == 1 {
                    success(format!("Added SICK LEAVE on {}.\n", date));
                } else {
                    success(format!(
                        "No Sick Leave inserted on {} (skipped: weekend={}, national_holiday={}, existing_events={}).\n",
                        date, skipped_weekend, skipped_national, skipped_existing
                    ));
                }
            } else {
                success(format!(
                    "SICK LEAVE range {}{}: inserted={}, skipped (weekend={}, national_holiday={}, existing_events={}).\n",
                    date, to_date, inserted, skipped_weekend, skipped_national, skipped_existing
                ));
            }
            return Ok(());
        }

        // ------------------------------------------------
        // Events for the single day (normal flow)
        // ------------------------------------------------
        let date_str = date.to_string();
        let events_today = load_events_by_date(pool, &date)?;
        let has_events = !events_today.is_empty();

        // ------------------------------------------------
        // ✅ CASE: Holiday / NationalHoliday marker day
        // ------------------------------------------------
        if pos_final == Location::Holiday || pos_final == Location::NationalHoliday {
            // Marker day: do not accept time/lunch/work-gap args
            if start.is_some()
                || end.is_some()
                || lunch.is_some()
                || work_gap.is_some()
                || range.is_some()
            {
                return Err(AppError::InvalidArgs(
                    "For holiday days do not specify --start, --end, --lunch, --work-gap, --from or --to.".into(),
                ));
            }

            if has_events {
                return Err(AppError::InvalidArgs(
                    "Cannot set a holiday marker on a date that already has events.".into(),
                ));
            }

            let holiday_time = NaiveTime::from_hms_opt(0, 0, 0)
                .ok_or_else(|| AppError::Other("Invalid holiday time sentinel.".into()))?;

            let mut ev_holiday = build_event_cli(
                date,
                holiday_time,
                EventType::In,
                pos_final,
                extras_cli(lunch, false),
            );
            ev_holiday.notes = notes.clone();

            insert_event(&pool.conn, &ev_holiday)?;
            recalc_pairs_for_date(&pool.conn, &date)?;

            success(match pos_final {
                Location::Holiday => format!("Added HOLIDAY on {}.\n", date_str),
                Location::NationalHoliday => format!("Added NATIONAL HOLIDAY on {}.\n", date_str),
                _ => unreachable!(),
            });
            return Ok(());
        }

        // CASE A: only lunch update
        if start.is_none() && end.is_none() && lunch.is_some() {
            if range.is_some() {
                return Err(AppError::InvalidArgs(
                    "--from/--to are not valid for lunch-only updates.".into(),
                ));
            }
            if !has_events {
                return Err(AppError::InvalidArgs(
                    "Cannot set lunch on a date with no events.".into(),
                ));
            }

            pool.conn.execute(
                r#"
            UPDATE events
            SET lunch_break = ?1
            WHERE id = (
                SELECT id FROM events
                WHERE date = ?2
                ORDER BY time DESC
                LIMIT 1
            )
            "#,
                params![lunch_val, &date_str],
            )?;

            success(format!(
                "Lunch updated to {} minutes for {}.\n",
                lunch_val, date_str
            ));
            return Ok(());
        }

        // CASE B: nothing to do
        if start.is_none() && end.is_none() {
            return Err(AppError::InvalidArgs(
                "Nothing to do: specify at least --start, --end, --lunch or use --edit --notes."
                    .into(),
            ));
        }

        // CASE C: IN only
        if let Some(start_time) = start
            && end.is_none()
        {
            if range.is_some() {
                return Err(AppError::InvalidArgs(
                    "--from/--to require --pos Malattia.".into(),
                ));
            }

            let mut ev_in = build_event_cli(
                date,
                start_time,
                EventType::In,
                pos_final,
                extras_cli(lunch, false),
            );
            ev_in.notes = notes.clone();

            insert_event(&pool.conn, &ev_in)?;
            recalc_pairs_for_date(&pool.conn, &date)?;

            let events_after = load_events_by_date(pool, &date)?;
            let summary = Core::build_daily_summary(&events_after, cfg);

            let tgt_time = start_time + chrono::Duration::minutes(summary.expected);

            let tgt_mins = (tgt_time.hour() as i64) * 60 + (tgt_time.minute() as i64);
            let tgt_str = crate::utils::time::format_minutes(tgt_mins);

            success(format!(
                "Added IN at {} on {}. TGT => {}\n",
                start_time, date_str, tgt_str
            ));
            return Ok(());
        }

        // CASE D: OUT only
        if start.is_none()
            && let Some(end_time) = end
        {
            if range.is_some() {
                return Err(AppError::InvalidArgs(
                    "--from/--to require --pos Malattia.".into(),
                ));
            }

            let last_in = events_today
                .iter()
                .rev()
                .find(|ev| ev.kind == EventType::In)
                .cloned()
                .ok_or_else(|| {
                    AppError::InvalidArgs("Cannot add OUT without a previous IN.".into())
                })?;

            if end_time <= last_in.time {
                return Err(AppError::InvalidArgs(
                    "OUT must be later than the previous IN.".into(),
                ));
            }

            // If --pos provided, use it; otherwise inherit last IN location
            let out_position = if pos.is_some() {
                pos_final
            } else {
                last_in.location
            };

            let mut ev_out = build_event_cli(
                date,
                end_time,
                EventType::Out,
                out_position,
                extras_cli(lunch, false),
            );

            if let Some(wg_explicit) = work_gap {
                ev_out.work_gap = wg_explicit;
            }
            ev_out.notes = notes.clone();

            insert_event(&pool.conn, &ev_out)?;
            recalc_pairs_for_date(&pool.conn, &date)?;

            success(format!(
                "Added OUT on {} ({}{}).\n",
                date_str, last_in.time, end_time
            ));
            return Ok(());
        }

        // CASE E: full pair
        if let (Some(start_time), Some(end_time)) = (start, end) {
            if range.is_some() {
                return Err(AppError::InvalidArgs(
                    "--from/--to require --pos Malattia.".into(),
                ));
            }

            if end_time <= start_time {
                return Err(AppError::InvalidArgs("END must be later than IN.".into()));
            }

            let mut ev_in = build_event_cli(
                date,
                start_time,
                EventType::In,
                pos_final,
                extras_cli(lunch, false),
            );
            ev_in.notes = notes.clone();

            let mut ev_out = build_event_cli(
                date,
                end_time,
                EventType::Out,
                pos_final,
                extras_cli(lunch, false),
            );

            if let Some(wg_explicit) = work_gap {
                ev_out.work_gap = wg_explicit;
            }
            ev_out.notes = notes.clone();

            insert_event(&pool.conn, &ev_in)?;
            insert_event(&pool.conn, &ev_out)?;
            recalc_pairs_for_date(&pool.conn, &date)?;

            success(format!(
                "Added IN/OUT pair on {}: {}{}.\n",
                date_str, start_time, end_time
            ));
            return Ok(());
        }

        Err(AppError::InvalidArgs(
            "Unhandled combination of parameters.".into(),
        ))
    }
}