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
use chrono::{DateTime, Duration, Utc};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use std::{
fs::File,
io::{Read, Write},
};
use crate::Event;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Sheet {
pub events: Vec<Event>,
}
impl Sheet {
pub fn load_default() -> Result<Sheet, SheetError> {
let project_dirs =
ProjectDirs::from("dev", "neros", "PunchClock").ok_or(SheetError::FindSheet)?;
let data_dir = project_dirs.data_dir().to_owned();
let mut sheet_path = data_dir.clone();
sheet_path.push("sheet.json");
let mut sheet_json = String::new();
{
let mut sheet_file = File::open(&sheet_path).map_err(SheetError::OpenSheet)?;
sheet_file
.read_to_string(&mut sheet_json)
.map_err(SheetError::ReadSheet)?;
}
if sheet_json.is_empty() {
Ok(Sheet::default())
} else {
serde_json::from_str(&sheet_json).map_err(SheetError::ParseSheet)
}
}
pub fn write_default(&self) -> Result<(), SheetError> {
let new_sheet_json = serde_json::to_string(self).unwrap();
let project_dirs =
ProjectDirs::from("dev", "neros", "PunchClock").ok_or(SheetError::FindSheet)?;
let mut sheet_path = project_dirs.data_dir().to_owned();
sheet_path.push("sheet.json");
match File::create(&sheet_path) {
Ok(mut sheet_file) => {
write!(&mut sheet_file, "{}", new_sheet_json).map_err(SheetError::WriteSheet)
}
Err(e) => Err(SheetError::WriteSheet(e)),
}
}
pub fn punch_in(&mut self) -> Result<DateTime<Utc>, SheetError> {
self.punch_in_at(Utc::now())
}
pub fn punch_in_at(&mut self, time: DateTime<Utc>) -> Result<DateTime<Utc>, SheetError> {
match self.events.last() {
Some(Event { stop: Some(_), .. }) | None => {
let event = Event::new(time);
self.events.push(event);
Ok(time)
}
Some(Event {
start: start_time, ..
}) => Err(SheetError::PunchedIn(*start_time)),
}
}
pub fn punch_out(&mut self) -> Result<DateTime<Utc>, SheetError> {
self.punch_out_at(Utc::now())
}
pub fn punch_out_at(&mut self, time: DateTime<Utc>) -> Result<DateTime<Utc>, SheetError> {
match self.events.last_mut() {
Some(ref mut event @ Event { stop: None, .. }) => {
event.stop = Some(time);
Ok(time)
}
Some(Event {
stop: Some(stop_time),
..
}) => Err(SheetError::PunchedOut(*stop_time)),
None => Err(SheetError::NoPunches),
}
}
pub fn status(&self) -> SheetStatus {
match self.events.last() {
Some(Event {
stop: Some(stop), ..
}) => SheetStatus::PunchedOut(*stop),
Some(Event { start, .. }) => SheetStatus::PunchedIn(*start),
None => SheetStatus::Empty,
}
}
pub fn count_range(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Duration {
self.events
.iter()
.map(|e| (e.start, e.stop.unwrap_or(Utc::now())))
.filter(|(start, stop)| {
let entirely_before = start < &begin && stop < &begin;
let entirely_after = start > &end && stop > &end;
!(entirely_before || entirely_after)
})
.map(|(start, stop)| {
let real_begin = std::cmp::max(begin, start);
let real_end = std::cmp::min(end, stop);
real_end - real_begin
})
.fold(Duration::zero(), |acc, next| acc + next)
}
}
impl Default for Sheet {
fn default() -> Self {
Sheet { events: vec![] }
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SheetStatus {
PunchedIn(DateTime<Utc>),
PunchedOut(DateTime<Utc>),
Empty,
}
#[derive(Error, Debug)]
pub enum SheetError {
#[error("already punched in at {0}")]
PunchedIn(DateTime<Utc>),
#[error("not punched in, last punched out at {0}")]
PunchedOut(DateTime<Utc>),
#[error("not punched in, no punch-ins recorded")]
NoPunches,
#[error("unable to find sheet file")]
FindSheet,
#[error("unable to open sheet file")]
OpenSheet(#[source] std::io::Error),
#[error("unable to read sheet file")]
ReadSheet(#[source] std::io::Error),
#[error("unable to parse sheet")]
ParseSheet(#[source] serde_json::Error),
#[error("unable to write sheet to file")]
WriteSheet(#[source] std::io::Error),
}