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
use std::collections::HashMap;
use std::fmt;
use std::time::Duration;
use regex::Regex;
#[doc(inline)]
use crate::chart::{Percentages, PieData};
#[cfg(doc)]
use crate::date;
#[doc(inline)]
use crate::date::{Date, DateTime};
#[doc(inline)]
use crate::entry::Entry;
#[doc(inline)]
use crate::error::Error;
use crate::Result;
use crate::TaskEvent;
pub mod report;
pub type DetailReport<'a> = report::DetailReport<'a>;
pub type SummaryReport<'a> = report::SummaryReport<'a>;
pub type HoursReport<'a> = report::HoursReport<'a>;
pub type DailyChart<'a> = report::DailyChart<'a>;
pub type EventReport<'a> = report::EventReport<'a>;
#[derive(Debug)]
pub struct Day {
stamp: Date,
start: Option<DateTime>,
dur: Duration,
tasks: HashMap<String, TaskEvent>,
proj_dur: HashMap<String, Duration>,
entries: Vec<TaskEvent>,
events: Vec<Entry>,
last_start: Option<DateTime>,
last_entry: Option<Entry>
}
#[rustfmt::skip]
pub fn format_dur(dur: &Duration) -> String {
const DAY: u64 = 24 * 60 * 60;
const HOUR: u64 = 3600;
const MINUTE: u64 = 60;
let secs = dur.as_secs() + 30; if secs > DAY {
format!("{}d {:>2}:{:0>2}", secs / DAY, (secs % DAY) / HOUR, (secs % HOUR) / MINUTE)
}
else {
format!("{:>2}:{:0>2}", (secs / HOUR), (secs % HOUR) / MINUTE)
}
}
impl<'a> Day {
pub fn new(stamp: &str) -> Result<Self> {
if stamp.is_empty() {
return Err(Error::MissingDate);
}
Ok(Day {
stamp: Date::try_from(stamp)?,
start: None,
dur: Duration::default(),
tasks: HashMap::new(),
proj_dur: HashMap::new(),
entries: Vec::new(),
events: Vec::new(),
last_start: None,
last_entry: None
})
}
pub fn duration_secs(&self) -> u64 { self.dur.as_secs() }
pub fn is_empty(&self) -> bool { self.entries.is_empty() && self.events.is_empty() }
pub fn is_complete(&self) -> bool { self.last_start.is_none() }
pub fn date_stamp(&self) -> String { self.stamp.into() }
pub fn date(&self) -> Date { self.stamp }
pub fn projects(&self) -> impl Iterator<Item = &'_ str> {
self.proj_dur.keys().map(String::as_str)
}
pub fn events(&self) -> impl Iterator<Item = &'_ Entry> { self.events.iter() }
fn update_task_duration(&mut self, prev: &Entry, dur: &Duration) {
if let Some(task) = self.tasks.get_mut(prev.entry_text()) {
task.add_dur(*dur);
}
else {
let proj = prev.project();
let task = TaskEvent::new(prev.date_time(), proj, *dur);
self.tasks.insert(prev.entry_text().to_string(), task);
}
}
#[rustfmt::skip]
fn update_project_duration(&mut self, proj: &str, dur: &Duration) {
match self.proj_dur.get_mut(proj) {
Some(proj_dur) => { *proj_dur += *dur; },
None => { self.proj_dur.insert(proj.to_string(), *dur); },
}
}
pub fn add_entry(&mut self, entry: Entry) -> Result<()> {
if entry.is_event() {
self.events.push(entry);
}
else if !entry.is_ignore() {
self.update_dur(&entry.date_time())?;
self.start_task(&entry);
self.last_entry = (!entry.is_stop()).then_some(entry);
}
Ok(())
}
pub fn update_dur(&mut self, date_time: &DateTime) -> Result<()> {
if let Some(prev) = &self.last_entry.clone() {
let curr_dur = date_time.diff(&prev.date_time())?;
if !prev.entry_text().is_empty() {
self.update_task_duration(prev, &curr_dur);
}
let prev_proj = prev.project().unwrap_or_default();
self.update_project_duration(prev_proj, &curr_dur);
self.dur += curr_dur;
if let Some(prev) = self.entries.last_mut() {
prev.add_dur(curr_dur);
}
}
Ok(())
}
pub fn finish(&mut self) -> Result<()> {
if !self.is_complete() {
let date = (self.date() == Date::today())
.then(DateTime::now)
.unwrap_or_else(|| self.stamp.day_end());
self.update_dur(&date)?;
self.last_start = None;
}
Ok(())
}
pub fn start_day(&mut self, entry: &Entry) -> Result<()> {
if entry.is_start() {
let stamp = entry.date_time();
self.add_entry(entry.clone())?;
self.last_start = Some(stamp);
}
Ok(())
}
pub fn start_task(&mut self, entry: &Entry) {
if entry.is_stop() {
self.last_start = None;
return;
}
let task = entry.entry_text();
self.last_start = Some(entry.date_time());
self.tasks
.entry(task.to_string())
.or_insert_with(|| TaskEvent::from_entry(entry));
self.entries.push(TaskEvent::from_entry(entry));
}
fn _format_stamp_line(&self, f: &mut fmt::Formatter<'_>, sep: &str) -> fmt::Result {
writeln!(f, "{}{} {}", self.date_stamp(), sep, format_dur(&self.dur))
}
fn _format_project_line(
&self, f: &mut fmt::Formatter<'_>, proj: &str, dur: &Duration
) -> fmt::Result {
writeln!(f, " {:<13} {}", proj, format_dur(dur))
}
fn _format_task_line(
&self, f: &mut fmt::Formatter<'_>, task: &str, dur: &Duration
) -> fmt::Result {
let fdur = format_dur(dur);
match Entry::task_breakdown(task) {
(Some(task), Some(detail)) => {
writeln!(f, " {task:<19} {fdur} ({detail})")
}
(Some(task), None) => writeln!(f, " {task:<19} {fdur}"),
(None, Some(detail)) => writeln!(f, " {detail:<19} {fdur}"),
_ => writeln!(f, " {:<19} {}", "", fdur)
}
}
pub fn detail_report(&'a self) -> DetailReport<'a> { DetailReport::new(self) }
pub fn summary_report(&'a self) -> SummaryReport<'a> { SummaryReport::new(self) }
pub fn hours_report(&'a self) -> HoursReport<'a> { HoursReport::new(self) }
pub fn event_report(&'a self, compact: bool) -> EventReport<'a> {
EventReport::new(self, compact)
}
pub fn daily_chart(&'a self) -> DailyChart<'a> { DailyChart::new(self) }
pub fn has_tasks(&self) -> bool { !self.tasks.is_empty() }
pub fn has_events(&self) -> bool { !self.events.is_empty() }
fn project_filtered_tasks(&self, filter: &Regex) -> HashMap<String, TaskEvent> {
self.tasks
.iter()
.filter(|(_, t)| filter.is_match(&t.project()))
.fold(HashMap::new(), |mut h, (k, t)| {
h.insert(k.to_string(), t.clone());
h
})
}
fn project_filtered_events(&self, filter: &Regex) -> Vec<Entry> {
self.events
.iter()
.filter(|e| filter.is_match(e.project().unwrap_or_default()))
.cloned()
.collect()
}
fn project_filtered_durs(&self, filter: &Regex) -> HashMap<String, Duration> {
self.proj_dur
.iter()
.filter(|(k, _)| filter.is_match(k))
.fold(HashMap::new(), |mut h, (k, v)| {
h.insert(k.to_string(), *v);
h
})
}
#[must_use]
pub fn filtered_by_project(&self, filter: &Regex) -> Self {
let proj_durs = self.project_filtered_durs(filter);
Self {
stamp: self.stamp,
start: self.start,
dur: proj_durs.values().sum(),
tasks: self.project_filtered_tasks(filter),
entries: self.entries.clone(), events: self.project_filtered_events(filter),
proj_dur: proj_durs,
last_start: self.start,
last_entry: None
}
}
pub fn project_percentages(&'a self) -> Percentages {
let mut pie = PieData::default();
self.proj_dur
.iter()
.for_each(|(proj, dur)| pie.add_secs(proj.as_str(), dur.as_secs()));
pie.percentages()
}
pub fn task_percentages(&self, proj: &str) -> Percentages {
let mut pie = PieData::default();
self.tasks
.iter()
.filter(|(_t, tsk)| tsk.project() == proj)
.for_each(|(t, tsk)| {
let task = match Entry::task_breakdown(t) {
(None, None) => String::new(),
(Some(tname), None) => tname,
(None, Some(detail)) => format!(" ({detail})"),
(Some(tname), Some(detail)) => format!("{tname} ({detail})")
};
pie.add_secs(&task, tsk.as_secs());
});
pie.percentages()
}
fn entries(&self) -> impl Iterator<Item = &'_ TaskEvent> { self.entries.iter() }
}
#[cfg(test)]
pub(crate) mod tests {
use spectral::prelude::*;
use super::*;
use crate::chart::TagPercent;
use crate::entry::{Entry, EntryKind};
const INITIAL_ENTRIES: [(&str, u64); 8] = [
("+proj1 @Make changes", 0),
("+proj2 @Start work", 1),
("+proj1 @Make changes", 2),
("+proj1 @Stuff Other changes", 3),
("stop", 4),
("+proj1 @Stuff Other changes", 4),
("+proj1 @Final", 5),
("stop", 6)
];
#[rustfmt::skip]
const SOME_EVENTS: [(&str, u64); 2] = [
("+foo thing1", 30),
("+foo thing2", 30 + 5)
];
const MORE_ENTRIES: [(&str, u64); 4] = [
("+proj3 @Phone call", 60 + 0),
("+proj4 @Research", 60 + 1),
("@Phone call", 60 + 2),
("stop", 60 + 4)
];
#[test]
#[rustfmt::skip]
fn test_new_empty_stamp() {
assert_that!(Day::new("")).is_err_containing(Error::MissingDate);
}
#[test]
fn test_new_invalid_stamp() {
assert_that!(Day::new("foo")).is_err_containing(&(crate::date::Error::InvalidDate).into());
}
#[test]
fn test_update_dur() {
let day_result = Day::new("2021-06-10");
assert_that!(&day_result).is_ok();
let mut day = day_result.unwrap();
let _ = day.update_dur(&DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap());
assert_that!(day.duration_secs()).is_equal_to(&0);
}
#[test]
fn test_add_entry() {
let day_result = Day::new("2021-06-10");
assert_that!(&day_result).is_ok();
let mut day = day_result.unwrap();
let entry = Entry::from_line("2021-06-10 08:00:00 +proj1 do something").unwrap();
let _ = day.add_entry(entry);
let entry = Entry::from_line("2021-06-10 08:45:00 stop").unwrap();
let _ = day.add_entry(entry);
assert_that!(day.duration_secs()).is_equal_to(&(45 * 60));
}
#[test]
fn test_format_dur() {
assert_that!(format_dur(&Duration::default())).is_equal_to(&String::from(" 0:00"));
assert_that!(format_dur(&Duration::from_secs(3600))).is_equal_to(&String::from(" 1:00"));
assert_that!(format_dur(&Duration::from_secs(3629))).is_equal_to(&String::from(" 1:00"));
assert_that!(format_dur(&Duration::from_secs(3630))).is_equal_to(&String::from(" 1:01"));
assert_that!(format_dur(&Duration::from_secs(3660))).is_equal_to(&String::from(" 1:01"));
assert_that!(format_dur(&Duration::from_secs(36000))).is_equal_to(&String::from("10:00"));
assert_that!(format_dur(&Duration::from_secs(360000)))
.is_equal_to(&String::from("4d 4:00"));
assert_that!(format_dur(&Duration::from_secs(300000)))
.is_equal_to(&String::from("3d 11:20"));
}
#[test]
fn test_new_empty() {
let day_result = Day::new("2021-06-10");
assert_that!(&day_result).is_ok();
let day = day_result.unwrap();
assert_that!(&day.is_empty()).is_true();
assert_that!(&day.duration_secs()).is_equal_to(0u64);
assert_that!(&day.is_complete()).is_true();
assert_that!(&day.date_stamp()).is_equal_to(&String::from("2021-06-10"));
}
pub fn add_entries(day: &mut Day) -> Result<()> {
add_some_entries(
day,
DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(),
INITIAL_ENTRIES.iter()
)?;
day.finish()?;
Ok(())
}
pub fn add_some_events(day: &mut Day) -> Result<()> {
let stamp = DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap();
for (entry, mins) in SOME_EVENTS.iter() {
let ev = Entry::new_marked(
entry,
stamp.add(DateTime::minutes(*mins)).unwrap(),
EntryKind::Event
);
day.add_entry(ev)?;
}
day.finish()?;
Ok(())
}
pub fn add_extra_entries(day: &mut Day) -> Result<()> {
add_some_entries(
day,
DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(),
INITIAL_ENTRIES.iter().chain(MORE_ENTRIES.iter())
)?;
day.finish()?;
Ok(())
}
fn add_some_entries<'b, I>(day: &mut Day, stamp: DateTime, entries: I) -> Result<()>
where
I: Iterator<Item = &'b (&'b str, u64)>
{
for (entry, mins) in entries {
let ev = Entry::new(entry, stamp.add(DateTime::minutes(*mins)).unwrap());
day.add_entry(ev)?;
}
Ok(())
}
#[test]
fn test_task_percentages() {
let day_result = Day::new("2021-06-10");
assert_that!(&day_result).is_ok();
let mut day = day_result.unwrap();
add_extra_entries(&mut day).expect("Entries out of order");
let expect: Percentages = vec![
TagPercent::new("Make (changes)", 40.0).unwrap(),
TagPercent::new("Stuff (Other changes)", 40.0).unwrap(),
TagPercent::new("Final", 20.0).unwrap(),
];
let mut actual = day.task_percentages("proj1");
actual.sort_by(|lhs, rhs| lhs.partial_cmp(rhs).unwrap());
assert_that!(actual).is_equal_to(expect);
}
#[test]
fn test_entries() {
let day_result = Day::new("2021-06-10");
assert_that!(&day_result).is_ok();
let mut day = day_result.unwrap();
add_extra_entries(&mut day).expect("Entries out of order");
assert_that!(day.entries().count()).is_equal_to(9);
#[rustfmt::skip]
let expected = [
(DateTime::new((2021, 6, 10), (8, 0, 0)).unwrap(), "proj1", 60),
(DateTime::new((2021, 6, 10), (8, 1, 0)).unwrap(), "proj2", 60),
(DateTime::new((2021, 6, 10), (8, 2, 0)).unwrap(), "proj1", 60),
(DateTime::new((2021, 6, 10), (8, 3, 0)).unwrap(), "proj1", 60),
(DateTime::new((2021, 6, 10), (8, 4, 0)).unwrap(), "proj1", 60),
(DateTime::new((2021, 6, 10), (8, 5, 0)).unwrap(), "proj1", 60),
(DateTime::new((2021, 6, 10), (9, 0, 0)).unwrap(), "proj3", 60),
(DateTime::new((2021, 6, 10), (9, 1, 0)).unwrap(), "proj4", 60),
(DateTime::new((2021, 6, 10), (9, 2, 0)).unwrap(), "", 120),
];
for (ev, expect) in day.entries().zip(expected.iter()) {
assert_that!(ev.start()).is_equal_to(&expect.0);
assert_that!(ev.proj().unwrap_or_default()).is_equal_to(&expect.1.to_string());
assert_that!(ev.as_secs()).is_equal_to(expect.2);
}
}
}