gitlab-time-report 1.3.0

Library to generate statistics and charts from GitLab time tracking data.
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
//! Contains functions to filter and group [`TimeLog`].

use crate::model::{Label, Milestone, TimeLog, TrackableItem, User};
use chrono::{Duration, Local, NaiveDate};
use std::collections::{BTreeMap, HashSet};

/// Groups a list of nodes by a given filter. Returns an Iterator over a `BTreeMap`.
/// # Parameter
/// - `nodes`: A collection of time log nodes. Can be any collection that can be turned into an iterator.
/// - `filter`: A function to group the nodes by, usually a closure. It takes a reference to a time
///   log and returns a reference to the item to group by.
///
/// The lifetime annotation `'a` means that the references to `T` and `TimeLog` must both live at
/// least as long as each other.
pub fn group_by_filter<'a, T, I, F>(
    nodes: I,
    filter: F,
) -> impl Iterator<Item = (&'a T, Vec<&'a TimeLog>)>
where
    T: Ord + 'a,
    I: IntoIterator<Item = &'a TimeLog>,
    F: Fn(&'a TimeLog) -> &'a T,
{
    let mut grouped = BTreeMap::<&'a T, Vec<&'a TimeLog>>::new();
    for node in nodes {
        let key = filter(node);
        grouped.entry(key).or_default().push(node);
    }
    grouped.into_iter()
}

/// Groups a slice of nodes by their user and returns a iterator over a `BTreeMap`.
/// # Example
/// ```
/// # use gitlab_time_report::model::{TimeLog, User};
/// # use gitlab_time_report::filters::group_by_user;
/// # use std::collections::BTreeMap;
/// let nodes = vec![
///     TimeLog { user: User { name: "user1".to_string(), username: "user1".to_string() }, ..Default::default() },
///     TimeLog { user: User { name: "user1".to_string(), username: "user1".to_string() }, ..Default::default() },
///     TimeLog { user: User { name: "user2".to_string(), username: "user2".to_string() }, ..Default::default() }
/// ];
/// let grouped_by_user = group_by_user(&nodes).collect::<BTreeMap<_, _>>();
/// assert_eq!(grouped_by_user.len(), 2);
/// assert_eq!(grouped_by_user.get(&User { name: "user1".to_string(), username: "user1".to_string() }).unwrap().len(), 2);
/// assert_eq!(grouped_by_user.get(&User { name: "user2".to_string(), username: "user2".to_string() }).unwrap().len(), 1);
/// ```
pub fn group_by_user<'a>(
    nodes: impl IntoIterator<Item = &'a TimeLog>,
) -> impl Iterator<Item = (&'a User, Vec<&'a TimeLog>)> {
    group_by_filter(nodes, |node| &node.user)
}

/// Filter the `TimeLog` by milestone and returns an iterator over `(Option<&Milestone>, Vec<&TimeLog>)`.
pub fn group_by_milestone<'a>(
    nodes: impl IntoIterator<Item = &'a TimeLog>,
) -> impl Iterator<Item = (Option<&'a Milestone>, Vec<&'a TimeLog>)> {
    group_by_filter(nodes, |node| &node.trackable_item.common.milestone)
        .map(|(milestone, nodes)| (milestone.as_ref(), nodes))
}

/// Group the `TimeLog` by type (Issue/MR) and return an iterator. Will return a `String` containing the type name.
/// Because `TrackableItemKind` is an enum where each variant carries data, it is not sensible to group directly on
/// this type, because if the data inside is different, it counts as a different element.
pub fn group_by_type<'a, 'b>(
    nodes: impl IntoIterator<Item = &'a TimeLog>,
) -> impl Iterator<Item = (String, Vec<&'a TimeLog>)> {
    let mut grouped = BTreeMap::<String, Vec<&'a TimeLog>>::new();
    for node in nodes {
        let key = node.trackable_item.kind.to_string();
        grouped.entry(key).or_default().push(node);
    }
    grouped.into_iter()
}

/// Group the `TimeLog` by trackable item (Issue/MR) and return an iterator.
pub fn group_by_trackable_item<'a>(
    time_logs: impl IntoIterator<Item = &'a TimeLog>,
) -> impl Iterator<Item = (&'a TrackableItem, Vec<&'a TimeLog>)> {
    group_by_filter(time_logs, |node| &node.trackable_item)
}

/// Group the `TimeLog`s by labels and return an iterator.
/// Note that items with multiple labels are included multiple times.
/// Items with no labels are included in the label `other_label`, if set.
/// # Parameters
/// - `selected_labels`: A list of labels that should be included in the result.
///   If this `Some`, only `TimeLog`s with at least one of the selected labels
///   are grouped under the corresponding label. If this is `None`, all labels are selected.
/// - `other_label`: The label used for items without any of the selected labels.
///   If this is `Some`, all items not in `selected_labels` are grouped under this label.
///   If this is `None`, all items not in `selected_labels` are ignored.
pub fn group_by_label<'a>(
    nodes: impl IntoIterator<Item = &'a TimeLog>,
    selected_labels: Option<&HashSet<String>>,
    other_label: Option<&'a Label>,
) -> impl Iterator<Item = (Option<&'a Label>, Vec<&'a TimeLog>)> {
    let mut label_map = BTreeMap::<Option<&Label>, Vec<&TimeLog>>::new();

    for time_log in nodes {
        let labels = &time_log.trackable_item.common.labels.labels;

        if labels.is_empty() {
            // TrackableItem has no labels
            // Add None entry if selected_labels is not set
            if selected_labels.is_none() {
                label_map.entry(None).or_default().push(time_log);
                continue;
            }

            // Add to the "Other" label if selected_labels is set
            if other_label.is_some() {
                label_map.entry(other_label).or_default().push(time_log);
            }
            continue;
        }

        let mut matched_any_selected_label = false;

        for label in labels {
            // True if selected_labels is None or if the label is in the selected_labels
            let should_include_label =
                selected_labels.is_none_or(|sel_labels| sel_labels.contains(&label.title));

            if should_include_label {
                label_map.entry(Some(label)).or_default().push(time_log);
                matched_any_selected_label = true;
            }
        }

        // When label is not under the selected one, add to the "Other" label
        if other_label.is_some() && !matched_any_selected_label {
            label_map.entry(other_label).or_default().push(time_log);
        }
    }
    label_map.into_iter()
}

/// Filter the `TimeLog` by date and return an iterator. The dates are both inclusive.
pub fn filter_by_date<'a>(
    nodes: impl IntoIterator<Item = &'a TimeLog>,
    start: NaiveDate,
    end: NaiveDate,
) -> impl Iterator<Item = &'a TimeLog> {
    nodes.into_iter().filter(move |node| {
        let spent_day = node.spent_at.with_timezone(&Local).date_naive();
        spent_day >= start && spent_day <= end
    })
}

/// Returns the time logs in the last X days. The number of days is specified as `Duration`.
/// 1 day is the current day, 2 days is today and yesterday.
pub fn filter_by_last_n_days<'a>(
    time_logs: impl IntoIterator<Item = &'a TimeLog>,
    days: Duration,
) -> impl Iterator<Item = &'a TimeLog> {
    let end: NaiveDate = Local::now().date_naive();
    let start: NaiveDate = end - days + Duration::days(1);
    filter_by_date(time_logs, start, end)
}

/// Returns the total time spent on the project.
#[must_use]
pub fn total_time_spent<'a>(time_logs: impl IntoIterator<Item = &'a TimeLog>) -> Duration {
    time_logs
        .into_iter()
        .map(|node| node.time_spent)
        .sum::<Duration>()
}

/// Returns the total time spent on the project by every user.
pub fn total_time_spent_by_user<'a>(
    time_logs: impl IntoIterator<Item = &'a TimeLog>,
) -> impl Iterator<Item = (&'a User, Duration)> {
    group_by_user(time_logs).map(|(user, timelogs)| (user, total_time_spent(timelogs)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{
        Issue, Labels, MergeRequest, TrackableItem, TrackableItemFields, TrackableItemKind,
    };

    const NUMBER_OF_LOGS: usize = 5;

    #[expect(clippy::too_many_lines)]
    fn get_timelogs() -> [TimeLog; NUMBER_OF_LOGS] {
        let user1 = User {
            name: "user1".to_string(),
            username: "user1".to_string(),
        };
        let user2 = User {
            name: "user2".to_string(),
            username: "user2".to_string(),
        };

        [
            TimeLog {
                spent_at: Local::now() - Duration::days(2),
                time_spent: Duration::seconds(3600),
                summary: None,
                user: user1.clone(),
                trackable_item: TrackableItem::default(),
            },
            TimeLog {
                spent_at: Local::now() - Duration::days(5),
                time_spent: Duration::seconds(7200),
                summary: Some("First entry".to_string()),
                user: user2.clone(),
                trackable_item: TrackableItem::default(),
            },
            TimeLog {
                spent_at: Local::now() - Duration::days(1),
                time_spent: Duration::seconds(3600),
                summary: Some("test".to_string()),
                user: user2.clone(),
                trackable_item: TrackableItem {
                    common: TrackableItemFields {
                        id: 1,
                        title: "Second Issue".to_string(),
                        milestone: Some(Milestone {
                            title: "End of Elaboration".to_string(),
                            ..Default::default()
                        }),
                        labels: Labels {
                            labels: vec![Label {
                                title: "Documentation".into(),
                            }],
                        },
                        time_estimate: Duration::seconds(7200),
                        ..Default::default()
                    },
                    kind: TrackableItemKind::Issue(Issue::default()),
                },
            },
            TimeLog {
                spent_at: Local::now(),
                time_spent: Duration::seconds(1800),
                summary: Some("test".to_string()),
                user: user1.clone(),
                trackable_item: TrackableItem {
                    common: TrackableItemFields {
                        title: "First MR".into(),
                        milestone: None,
                        labels: Labels {
                            labels: vec![
                                Label {
                                    title: "Documentation".into(),
                                },
                                Label {
                                    title: "Development".into(),
                                },
                            ],
                        },
                        time_estimate: Duration::seconds(1800),
                        ..Default::default()
                    },
                    kind: TrackableItemKind::MergeRequest(MergeRequest::default()),
                },
            },
            TimeLog {
                spent_at: Local::now(),
                time_spent: Duration::seconds(5400),
                summary: Some("Fix a big bug".to_string()),
                user: User {
                    name: "user3".to_string(),
                    username: "user3".to_string(),
                },
                trackable_item: TrackableItem {
                    common: TrackableItemFields {
                        id: 1,
                        title: "Second MR".into(),
                        labels: Labels {
                            labels: vec![
                                Label {
                                    title: "Bug".into(),
                                },
                                Label {
                                    title: "Development".into(),
                                },
                            ],
                        },
                        time_estimate: Duration::seconds(3600),
                        ..Default::default()
                    },
                    kind: TrackableItemKind::MergeRequest(MergeRequest::default()),
                },
            },
        ]
    }

    #[test]
    fn test_group_by_user() {
        const NUMBER_OF_USERS: usize = 3;
        const NUMBER_OF_USER1_LOGS: usize = 2;
        const NUMBER_OF_USER2_LOGS: usize = 2;
        const NUMBER_OF_USER3_LOGS: usize = 1;

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let output = group_by_user(&input).collect::<BTreeMap<_, _>>();
        let user1 = User {
            name: "user1".to_string(),
            username: "user1".to_string(),
        };
        let user2 = User {
            name: "user2".to_string(),
            username: "user2".to_string(),
        };
        let user3 = User {
            name: "user3".to_string(),
            username: "user3".to_string(),
        };

        assert_eq!(output.len(), NUMBER_OF_USERS);
        assert_eq!(output.get(&user1).unwrap().len(), NUMBER_OF_USER1_LOGS);
        assert_eq!(output.get(&user2).unwrap().len(), NUMBER_OF_USER2_LOGS);
        assert_eq!(output.get(&user3).unwrap().len(), NUMBER_OF_USER3_LOGS);
    }

    #[test]
    fn test_group_by_milestone() {
        const NUMBER_OF_MILESTONES: usize = 2;
        const NUMBER_OF_NONE: usize = 4;
        const NUMBER_OF_SOME: usize = 1;

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let milestone_none = None;
        let milestone_some = Some(&Milestone {
            title: "End of Elaboration".to_string(),
            ..Default::default()
        });

        let output = group_by_milestone(&input).collect::<BTreeMap<_, _>>();

        assert_eq!(output.len(), NUMBER_OF_MILESTONES);

        let output_none = output.get(&milestone_none).unwrap();
        let output_some = output.get(&milestone_some).unwrap();
        assert_eq!(output_none.len(), NUMBER_OF_NONE);
        assert_eq!(output_some.len(), NUMBER_OF_SOME);

        // Verify the correct timelogs are grouped
        assert!(output_none.contains(&&input[0]));
        assert!(output_none.contains(&&input[1]));
        assert!(output_some.contains(&&input[2]));
        assert!(output_none.contains(&&input[3]));
        assert!(output_none.contains(&&input[4]));
    }

    #[test]
    fn test_group_by_type() {
        const NUMBER_OF_TYPES: usize = 2;
        const NUMBER_OF_ISSUES: usize = 3;
        const NUMBER_OF_MERGE_REQUESTS: usize = 2;

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let output = group_by_type(&input).collect::<BTreeMap<_, _>>();

        assert_eq!(output.len(), NUMBER_OF_TYPES);
        assert_eq!(output.get("Issue").unwrap().len(), NUMBER_OF_ISSUES);
        assert_eq!(
            output.get("Merge Request").unwrap().len(),
            NUMBER_OF_MERGE_REQUESTS
        );
    }

    #[test]
    fn test_group_by_trackable_item() {
        const NUMBER_OF_ITEMS: usize = 4;
        const NUMBER_OF_ISSUE_0: usize = 2;
        const NUMBER_OF_ISSUE_1: usize = 1;
        const NUMBER_OF_MR_0: usize = 1;
        const NUMBER_OF_MR_1: usize = 1;

        let input = get_timelogs();
        let mut result = group_by_trackable_item(&input).collect::<BTreeMap<_, _>>();
        assert_eq!(result.len(), NUMBER_OF_ITEMS);

        let item_1 = result.pop_first().unwrap();
        assert_eq!(
            std::mem::discriminant(&item_1.0.kind),
            std::mem::discriminant(&TrackableItemKind::Issue(Issue::default()))
        );
        assert_eq!(item_1.0.common.id, 0);
        assert_eq!(item_1.1.len(), NUMBER_OF_ISSUE_0);

        let item_2 = result.pop_first().unwrap();
        assert_eq!(
            std::mem::discriminant(&item_2.0.kind),
            std::mem::discriminant(&TrackableItemKind::MergeRequest(MergeRequest::default()))
        );
        assert_eq!(item_2.0.common.id, 0);
        assert_eq!(item_2.1.len(), NUMBER_OF_MR_0);

        let item_3 = result.pop_first().unwrap();
        assert_eq!(
            std::mem::discriminant(&item_3.0.kind),
            std::mem::discriminant(&TrackableItemKind::Issue(Issue::default()))
        );
        assert_eq!(item_3.0.common.id, 1);
        assert_eq!(item_3.1.len(), NUMBER_OF_ISSUE_1);

        let item_4 = result.pop_first().unwrap();
        assert_eq!(
            std::mem::discriminant(&item_4.0.kind),
            std::mem::discriminant(&TrackableItemKind::MergeRequest(MergeRequest::default()))
        );
        assert_eq!(item_4.0.common.id, 1);
        assert_eq!(item_4.1.len(), NUMBER_OF_MR_1);
    }

    #[test]
    fn test_group_by_label_contains_selected_labels() {
        const NUMBER_OF_SELECTED_LABELS: usize = 2;

        let input = get_timelogs();

        let label_documentation = Some(&Label {
            title: "Documentation".to_string(),
        });
        let label_development = Some(&Label {
            title: "Development".to_string(),
        });
        let label_bug = Some(&Label {
            title: "Bug".to_string(),
        });
        let label_others = Some(&Label {
            title: "Others".to_string(),
        });

        #[expect(clippy::unnecessary_literal_unwrap)]
        let label_filter = HashSet::from([
            label_development.unwrap().title.clone(),
            label_documentation.unwrap().title.clone(),
        ]);
        assert_eq!(label_filter.len(), NUMBER_OF_SELECTED_LABELS);

        let result = group_by_label(&input, Some(&label_filter), None).collect::<BTreeMap<_, _>>();

        assert_eq!(result.len(), NUMBER_OF_SELECTED_LABELS);
        assert!(result.contains_key(&label_documentation));
        assert!(result.contains_key(&label_development));
        assert!(!result.contains_key(&label_bug));
        assert!(!result.contains_key(&label_others));
        assert!(!result.contains_key(&None));
    }

    #[test]
    fn test_group_by_label_contains_items_without_labels() {
        const NUMBER_OF_LABELS_INCLUDING_NO_LABEL: usize = 4;
        const NUMBER_OF_NO_LABEL: usize = 2;
        const TIME_SPENT_BY_NO_LABEL: Duration = Duration::seconds(10800);

        let time_logs = get_timelogs();
        let result = group_by_label(&time_logs, None, None).collect::<BTreeMap<_, _>>();

        assert_eq!(result.len(), NUMBER_OF_LABELS_INCLUDING_NO_LABEL);
        assert!(result.contains_key(&None));
        let no_label = result.get(&None).unwrap();
        assert_eq!(no_label.len(), NUMBER_OF_NO_LABEL);
        assert_eq!(
            no_label.iter().map(|t| t.time_spent).sum::<Duration>(),
            TIME_SPENT_BY_NO_LABEL
        );
    }

    #[test]
    fn test_group_by_label_none_selected_labels_contains_all_labels() {
        const NUMBER_OF_ALL_LABELS: usize = 3;

        let input = get_timelogs();

        let label_documentation = Some(&Label {
            title: "Documentation".to_string(),
        });
        let label_development = Some(&Label {
            title: "Development".to_string(),
        });
        let label_bug = Some(&Label {
            title: "Bug".to_string(),
        });
        let label_others = Some(&Label {
            title: "Others".to_string(),
        });

        let result = group_by_label(&input, None, None).collect::<BTreeMap<_, _>>();
        // All labels + 1 for No label
        assert_eq!(result.len(), NUMBER_OF_ALL_LABELS + 1);
        assert!(result.contains_key(&label_documentation));
        assert!(result.contains_key(&label_development));
        assert!(result.contains_key(&label_bug));
        assert!(result.contains_key(&None));
        assert!(!result.contains_key(&label_others));
    }

    #[test]
    fn test_group_by_label_with_other_label() {
        const NUMBER_OF_SELECTED_LABELS: usize = 2;
        const NUMBER_OF_DOCUMENTATION: usize = 2;
        const NUMBER_OF_DEVELOPMENT: usize = 2;
        const NUMBER_OF_OTHERS: usize = 2;

        const TIME_SPENT_BY_DOCUMENTATION: Duration = Duration::seconds(5400);
        const TIME_SPENT_BY_DEVELOPMENT: Duration = Duration::seconds(7200);
        const TIME_SPENT_BY_OTHERS: Duration = Duration::seconds(10800);

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let label_documentation = Some(&Label {
            title: "Documentation".to_string(),
        });
        let label_development = Some(&Label {
            title: "Development".to_string(),
        });
        let label_bug = Some(&Label {
            title: "Bug".to_string(),
        });
        let label_others = Label {
            title: "Others".to_string(),
        };

        #[expect(clippy::unnecessary_literal_unwrap)]
        let label_filter = HashSet::from([
            label_development.unwrap().title.clone(),
            label_documentation.unwrap().title.clone(),
        ]);
        assert_eq!(label_filter.len(), NUMBER_OF_SELECTED_LABELS);

        let result = group_by_label(&input, Some(&label_filter), Some(&label_others))
            .collect::<BTreeMap<_, _>>();

        // Selected labels + 1 for the "Other" label
        assert_eq!(result.len(), NUMBER_OF_SELECTED_LABELS + 1);

        // Check the contents of the labels
        let result_documentation = result.get(&label_documentation).unwrap();
        assert_eq!(result_documentation.len(), NUMBER_OF_DOCUMENTATION);
        assert_eq!(
            result_documentation
                .iter()
                .map(|t| t.time_spent)
                .sum::<Duration>(),
            TIME_SPENT_BY_DOCUMENTATION
        );

        let result_development = result.get(&label_development).unwrap();
        assert_eq!(result_development.len(), NUMBER_OF_DEVELOPMENT);
        assert_eq!(
            result_development
                .iter()
                .map(|t| t.time_spent)
                .sum::<Duration>(),
            TIME_SPENT_BY_DEVELOPMENT
        );

        let result_others = result.get(&Some(&label_others)).unwrap();
        assert_eq!(result_others.len(), NUMBER_OF_OTHERS);
        assert_eq!(
            result_others.iter().map(|t| t.time_spent).sum::<Duration>(),
            TIME_SPENT_BY_OTHERS
        );
        assert!(!result.contains_key(&label_bug));
    }

    #[test]
    fn test_group_by_label_without_other_label() {
        const NUMBER_OF_LABELS: usize = 3;
        const NUMBER_OF_DOCUMENTATION: usize = 2;
        const NUMBER_OF_DEVELOPMENT: usize = 2;
        const NUMBER_OF_BUGS: usize = 1;

        const TIME_SPENT_BY_DOCUMENTATION: Duration = Duration::seconds(5400);
        const TIME_SPENT_BY_DEVELOPMENT: Duration = Duration::seconds(7200);
        const TIME_SPENT_BY_BUGS: Duration = Duration::seconds(5400);

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let label_documentation = Some(&Label {
            title: "Documentation".to_string(),
        });
        let label_development = Some(&Label {
            title: "Development".to_string(),
        });
        let label_bug = Some(&Label {
            title: "Bug".to_string(),
        });

        #[expect(clippy::unnecessary_literal_unwrap)]
        let label_filter = HashSet::from([
            label_development.unwrap().title.clone(),
            label_documentation.unwrap().title.clone(),
            label_bug.unwrap().title.clone(),
        ]);

        let result = group_by_label(&input, Some(&label_filter), None).collect::<BTreeMap<_, _>>();
        assert_eq!(result.len(), NUMBER_OF_LABELS);

        // Check the contents of the labels
        let result_documentation = result.get(&label_documentation).unwrap();
        assert_eq!(result_documentation.len(), NUMBER_OF_DOCUMENTATION);
        assert_eq!(
            result_documentation
                .iter()
                .map(|t| t.time_spent)
                .sum::<Duration>(),
            TIME_SPENT_BY_DOCUMENTATION
        );

        let result_development = result.get(&label_development).unwrap();
        assert_eq!(result_development.len(), NUMBER_OF_DEVELOPMENT);
        assert_eq!(
            result_development
                .iter()
                .map(|t| t.time_spent)
                .sum::<Duration>(),
            TIME_SPENT_BY_DEVELOPMENT
        );

        let result_bug = result.get(&label_bug).unwrap();
        assert_eq!(result_bug.len(), NUMBER_OF_BUGS);
        assert_eq!(
            result_bug.iter().map(|t| t.time_spent).sum::<Duration>(),
            TIME_SPENT_BY_BUGS
        );

        assert!(!result.contains_key(&None));
    }

    #[test]
    fn test_total_time_spent_by_user() {
        const NUMBER_OF_USERS: usize = 3;
        const TIME_SPENT_BY_USER_1: Duration = Duration::seconds(5400);
        const TIME_SPENT_BY_USER_2: Duration = Duration::seconds(10800);
        const TIME_SPENT_BY_USER_3: Duration = Duration::seconds(5400);

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        let totals = total_time_spent_by_user(&input).collect::<BTreeMap<_, _>>();

        let user1 = User {
            name: "user1".to_string(),
            username: "user1".to_string(),
        };
        let user2 = User {
            name: "user2".to_string(),
            username: "user2".to_string(),
        };
        let user3 = User {
            name: "user3".to_string(),
            username: "user3".to_string(),
        };

        assert_eq!(totals.len(), NUMBER_OF_USERS);
        assert_eq!(totals.get(&user1), Some(&TIME_SPENT_BY_USER_1));
        assert_eq!(totals.get(&user2), Some(&TIME_SPENT_BY_USER_2));
        assert_eq!(totals.get(&user3), Some(&TIME_SPENT_BY_USER_3));
    }

    #[test]
    fn test_filter_by_dates() {
        const NUMBER_OF_FILTERED_LOGS: usize = 3;

        let input = get_timelogs();
        assert_eq!(input.len(), NUMBER_OF_LOGS);

        // should take today and yesterday
        let end = Local::now().date_naive();
        let start = end - Duration::days(1);
        let output = filter_by_date(&input, start, end).collect::<Vec<_>>();

        assert_eq!(output.len(), NUMBER_OF_FILTERED_LOGS);
        for node in output {
            let spent_day = node.spent_at.with_timezone(&Local).date_naive();
            assert!(spent_day >= start && spent_day <= end);
        }
    }

    #[test]
    fn test_filter_by_last_n_days() {
        const NUMBER_OF_FILTERED_LOGS: usize = 3;
        const NUMBER_OF_DAYS: i64 = 2;

        let input = get_timelogs();
        let output =
            filter_by_last_n_days(&input, Duration::days(NUMBER_OF_DAYS)).collect::<Vec<_>>();

        let end = Local::now();
        let start = end - Duration::days(NUMBER_OF_DAYS);

        assert_eq!(output.len(), NUMBER_OF_FILTERED_LOGS);
        for log in output {
            assert!(log.spent_at >= start && log.spent_at <= end);
        }
    }
}