Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

23 history of appointments #25

Merged
merged 16 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 35 additions & 13 deletions todayiwill/src/appointment.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use core::fmt;
use std::{ops::Add, path::PathBuf};

use chrono::Local;
use chrono::{Local, NaiveDate};

extern crate dirs;

Expand All @@ -11,15 +11,23 @@ pub mod helper;
pub mod list;

pub struct Config {
pub appointments_path: Box<PathBuf>,
pub appointment_file_path_current_day: Box<PathBuf>,
pub appointment_file_path_builder: Box<dyn Fn(NaiveDate) -> PathBuf>,
}

impl Config {
pub fn default() -> Self {
let base_dir = dirs::data_dir().unwrap().join("todayiwill");
let appointments_path = base_dir.join("appointments.txt");
let appointment_path_builder = |date: NaiveDate| {
dirs::data_dir()
.unwrap()
.join("todayiwill")
.join(format!("appointments_{}.txt", helper::date_code(date)))
};
Self {
appointments_path: Box::new(appointments_path),
appointment_file_path_current_day: Box::new(appointment_path_builder(
Local::now().date_naive(),
)),
appointment_file_path_builder: Box::new(appointment_path_builder),
}
}
}
Expand All @@ -30,13 +38,13 @@ pub struct AppointmentTime {
pub minutes: i32,
}

impl AppointmentTime {
pub fn new(hour: i32, minutes: i32) -> Result<Self, String> {
impl<'a> AppointmentTime {
pub fn new(hour: i32, minutes: i32) -> Result<Self, &'a str> {
if !(0..24).contains(&hour) {
return Err(String::from("Hour should be between 0 and 23"));
return Err("Hour should be between 0 and 23");
}
if !(0..60).contains(&minutes) {
return Err(String::from("Minutes should be between 0 and 59"));
return Err("Minutes should be between 0 and 59");
}
Ok(Self { hour, minutes })
}
Expand All @@ -49,10 +57,10 @@ impl AppointmentTime {
}
}

pub fn from(time: &str) -> Result<Self, String> {
pub fn from(time: &str) -> Result<Self, &'a str> {
let (hour, minutes) = match helper::parse_time(time) {
Some((hour, minutes)) => (hour, minutes),
None => return Err(String::from("Invalid string for appointment time")),
None => return Err("Invalid string for appointment time"),
};
let appointment_time = Self::new(hour, minutes)?;
Ok(appointment_time)
Expand Down Expand Up @@ -108,9 +116,9 @@ impl fmt::Display for Appointment {

#[cfg(test)]
mod tests {
use chrono::Local;
use chrono::{Local, NaiveDate};

use super::AppointmentTime;
use super::{AppointmentTime, Config};

#[test]
fn wellformed_appointment_time() {
Expand Down Expand Up @@ -215,4 +223,18 @@ mod tests {
let result = AppointmentTime::new(23, 55).unwrap() + 4;
assert_eq!(result, AppointmentTime::max_value());
}

#[test]
fn config_default_should_return_a_builder_fn() {
let result = (Config::default().appointment_file_path_builder)(
NaiveDate::from_ymd_opt(2023, 10, 21).unwrap(),
);
assert_eq!(
result,
dirs::data_dir()
.unwrap()
.join("todayiwill")
.join("appointments_21102023.txt")
);
}
}
5 changes: 3 additions & 2 deletions todayiwill/src/appointment/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ use super::{list, Appointment, Config};

/// Adds a new appointment to the list stored in files
pub fn add_appointment(appointment: Appointment, config: Config) -> Result<(), io::Error> {
let mut appointments = list::get_appointments_from_file(&config.appointments_path);
let mut appointments =
list::get_appointments_from_file(&config.appointment_file_path_current_day);
appointments.push(appointment);
appointments.sort();
write_appointments_to_file(appointments, &config.appointments_path)?;
write_appointments_to_file(appointments, &config.appointment_file_path_current_day)?;
println!("Appointment added successfully.");
Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion todayiwill/src/appointment/clear.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{fs, io, path::PathBuf};
use super::Config;

pub fn clear_appointments(config: Config) {
match remove_file(&config.appointments_path) {
match remove_file(&config.appointment_file_path_current_day) {
Ok(..) => println!("Appointments cleared successfully."),
Err(error) => println!(
"An error occurred when clearing the appointments. {}",
Expand Down
44 changes: 43 additions & 1 deletion todayiwill/src/appointment/helper.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use chrono::{NaiveDate, ParseError};

/// Parses string time (hours and minutes) and returns a tuple with both values
/// `10:43` -> Option<(10, 43)>
pub fn parse_time(time: &str) -> Option<(i32, i32)> {
Expand All @@ -7,9 +9,22 @@ pub fn parse_time(time: &str) -> Option<(i32, i32)> {
Some((hour, minutes))
}

/// Returns a string code for a given date
/// Option<20/01/2021> -> "20012021"
pub fn date_code(date: NaiveDate) -> String {
date.format("%d%m%Y").to_string()
}

/// Converts a string to a naive date
pub fn str_dmy_to_naive_date(date: &str) -> Result<NaiveDate, ParseError> {
NaiveDate::parse_from_str(date, "%d/%m/%Y")
}

#[cfg(test)]
mod tests {
use super::parse_time;
use chrono::NaiveDate;

use super::{date_code, parse_time, str_dmy_to_naive_date};

#[test]
fn parse_wellformed_time() {
Expand All @@ -22,4 +37,31 @@ mod tests {
let result = parse_time("0x:21e");
assert!(result.is_none());
}

#[test]
fn date_code_check() {
let result = date_code(NaiveDate::from_ymd_opt(2024, 1, 2).unwrap());
assert_eq!(result, "02012024");
}

#[test]
fn wellformed_date_naive_parse() {
let result = str_dmy_to_naive_date("24/06/2023");
assert_eq!(
result.unwrap(),
NaiveDate::from_ymd_opt(2023, 6, 24).unwrap()
);
}

#[test]
fn malformed_date_naive_parse() {
let result = str_dmy_to_naive_date("12/96202");
assert!(result.is_err());
}

#[test]
fn malformed_date_naive_parse_edge_case() {
let result = str_dmy_to_naive_date("2020-01-23");
assert!(result.is_err());
}
}
18 changes: 17 additions & 1 deletion todayiwill/src/appointment/list.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::{fs, path::PathBuf};

use chrono::NaiveDate;

use crate::appointment::AppointmentTime;

use super::{Appointment, Config};

/// Displays the list of appointments in the standard output
pub fn display_list(ref_time: Option<AppointmentTime>, expire_time: Option<i32>, config: Config) {
let mut appointments = get_appointments_from_file(&config.appointments_path);
let mut appointments = get_appointments_from_file(&config.appointment_file_path_current_day);
if appointments.is_empty() {
println!("There are no appointments added for today.");
return;
Expand All @@ -33,6 +35,20 @@ pub fn display_list(ref_time: Option<AppointmentTime>, expire_time: Option<i32>,
}
}

/// Displays all appointments for specific dates
pub fn display_all_from(date: NaiveDate, config: Config) {
let mut appointments =
get_appointments_from_file(&(config.appointment_file_path_builder)(date));
if appointments.is_empty() {
println!("There are no appointments added this day.");
return;
}
appointments.sort();
for appointment in &appointments {
println!("{}", appointment)
}
}

/// Get the string version of the list of appointments
/// Should read the appointments of a specific file and return a list
/// of appointments
Expand Down
14 changes: 11 additions & 3 deletions todayiwill/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::process;

use chrono::NaiveDate;
use clap::{Parser, Subcommand};

extern crate chrono;
Expand All @@ -20,7 +21,7 @@ struct Cli {

#[derive(Debug, Subcommand)]
enum Commands {
/// Add appointment
/// Add appointment for today
Add {
/// Appointment description
#[arg(short, long)]
Expand All @@ -34,9 +35,9 @@ enum Commands {
#[arg(short, long, value_parser=AppointmentTime::from, default_value_t=AppointmentTime::now())]
current_time: AppointmentTime,
},
/// Clear all the appointments added until now
/// Clear all the appointments added for today
Clear,
/// List the appointments to come
/// List the appointments to come for today
List {
/// Current time, defaults to system time
#[arg(short, long, value_parser=AppointmentTime::from, default_value_t=AppointmentTime::now())]
Expand All @@ -50,6 +51,12 @@ enum Commands {
#[arg(short, long, default_value_t = false)]
all: bool,
},
/// List the appointments for other days
History {
/// Show appointments which will expire in X seconds
#[arg(short, long, value_parser=helper::str_dmy_to_naive_date)]
date: NaiveDate,
},
}

fn main() {
Expand Down Expand Up @@ -108,5 +115,6 @@ fn main() {
list::display_list(ref_time, ref_expiration, config)
}
Commands::Clear => clear::clear_appointments(config),
Commands::History { date } => list::display_all_from(date, config),
}
}
Loading