This commit is contained in:
@@ -0,0 +1,423 @@
|
||||
use chrono::{Datelike, Days, NaiveDate, NaiveTime};
|
||||
use postgres::{Client, NoTls};
|
||||
|
||||
use crate::model::{CreateRoutine, CreateTask, DueNotification, Routine, Schedule, Task};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, String>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
database_url: String,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub fn new(database_url: impl Into<String>) -> Self {
|
||||
Self {
|
||||
database_url: database_url.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn connect(&self) -> Result<Client> {
|
||||
Client::connect(&self.database_url, NoTls).map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn migrate(&self) -> Result<()> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.batch_execute(
|
||||
"CREATE TABLE IF NOT EXISTS routines (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
section TEXT NOT NULL,
|
||||
priority TEXT NOT NULL,
|
||||
schedule_json JSONB NOT NULL,
|
||||
reminder_time TIME,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
routine_id BIGINT REFERENCES routines(id),
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT,
|
||||
section TEXT NOT NULL,
|
||||
priority TEXT NOT NULL,
|
||||
scheduled_date DATE NOT NULL,
|
||||
reminder_time TIME,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
completed_at TIMESTAMPTZ,
|
||||
notification_sent_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE(routine_id, scheduled_date)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS tasks_by_date
|
||||
ON tasks(scheduled_date, status);
|
||||
CREATE INDEX IF NOT EXISTS tasks_due_notification
|
||||
ON tasks(scheduled_date, reminder_time, notification_sent_at);",
|
||||
)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
|
||||
validate_title(&task.title)?;
|
||||
let scheduled_date = parse_date(&task.scheduled_date)?;
|
||||
let reminder_time = parse_reminder(task.reminder_time.as_deref())?;
|
||||
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO tasks (
|
||||
title, notes, section, priority, scheduled_date, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id",
|
||||
&[
|
||||
&task.title.trim(),
|
||||
&task.notes,
|
||||
&task.section.as_str(),
|
||||
&task.priority.as_str(),
|
||||
&scheduled_date,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn list_tasks(&self, date: &str) -> Result<Vec<Task>> {
|
||||
let date = parse_date(date)?;
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, routine_id, title, notes, section, priority,
|
||||
scheduled_date, reminder_time, status,
|
||||
EXTRACT(EPOCH FROM completed_at)::BIGINT
|
||||
FROM tasks
|
||||
WHERE scheduled_date = $1
|
||||
ORDER BY
|
||||
CASE section
|
||||
WHEN 'morning' THEN 0
|
||||
WHEN 'work' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
CASE priority
|
||||
WHEN 'must' THEN 0
|
||||
WHEN 'should' THEN 1
|
||||
ELSE 2
|
||||
END,
|
||||
id",
|
||||
&[&date],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let scheduled_date: NaiveDate = row.get(6);
|
||||
let reminder_time: Option<NaiveTime> = row.get(7);
|
||||
Task {
|
||||
id: row.get(0),
|
||||
routine_id: row.get(1),
|
||||
title: row.get(2),
|
||||
notes: row.get(3),
|
||||
section: row.get(4),
|
||||
priority: row.get(5),
|
||||
scheduled_date: scheduled_date.to_string(),
|
||||
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
||||
status: row.get(8),
|
||||
completed_at: row.get(9),
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn complete_task(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks
|
||||
SET status = 'completed', completed_at = now()
|
||||
WHERE id = $1 AND status != 'completed'",
|
||||
&[&id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn reschedule_task(&self, id: i64, date: &str) -> Result<bool> {
|
||||
let date = parse_date(date)?;
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks
|
||||
SET scheduled_date = $1, notification_sent_at = NULL
|
||||
WHERE id = $2",
|
||||
&[&date, &id],
|
||||
)
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn delete_task(&self, id: i64) -> Result<bool> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute("DELETE FROM tasks WHERE id = $1", &[&id])
|
||||
.map(|changed| changed == 1)
|
||||
.map_err(db_error)
|
||||
}
|
||||
|
||||
pub fn create_routine(&self, routine: CreateRoutine) -> Result<i64> {
|
||||
validate_title(&routine.title)?;
|
||||
validate_schedule(&routine.schedule)?;
|
||||
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
|
||||
let schedule_json = serde_json::to_value(&routine.schedule).map_err(json_error)?;
|
||||
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_one(
|
||||
"INSERT INTO routines (
|
||||
title, notes, section, priority, schedule_json, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id",
|
||||
&[
|
||||
&routine.title.trim(),
|
||||
&routine.notes,
|
||||
&routine.section.as_str(),
|
||||
&routine.priority.as_str(),
|
||||
&schedule_json,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.get(0))
|
||||
}
|
||||
|
||||
pub fn list_routines(&self) -> Result<Vec<Routine>> {
|
||||
let mut client = self.connect()?;
|
||||
let rows = client
|
||||
.query(
|
||||
"SELECT id, title, notes, section, priority, schedule_json,
|
||||
reminder_time, enabled
|
||||
FROM routines ORDER BY id",
|
||||
&[],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let schedule_json: serde_json::Value = row.get(5);
|
||||
let schedule = serde_json::from_value(schedule_json).map_err(json_error)?;
|
||||
let reminder_time: Option<NaiveTime> = row.get(6);
|
||||
Ok(Routine {
|
||||
id: row.get(0),
|
||||
title: row.get(1),
|
||||
notes: row.get(2),
|
||||
section: row.get(3),
|
||||
priority: row.get(4),
|
||||
schedule,
|
||||
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
||||
enabled: row.get(7),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn generate(&self, start: NaiveDate, horizon_days: u64) -> Result<usize> {
|
||||
let routines = self.list_routines()?;
|
||||
let mut client = self.connect()?;
|
||||
let mut inserted = 0_u64;
|
||||
|
||||
for offset in 0..=horizon_days {
|
||||
let date = start
|
||||
.checked_add_days(Days::new(offset))
|
||||
.ok_or_else(|| "generation date overflow".to_owned())?;
|
||||
for routine in routines.iter().filter(|routine| routine.enabled) {
|
||||
if !schedule_matches(&routine.schedule, date)? {
|
||||
continue;
|
||||
}
|
||||
let reminder_time = parse_reminder(routine.reminder_time.as_deref())?;
|
||||
inserted += client
|
||||
.execute(
|
||||
"INSERT INTO tasks (
|
||||
routine_id, title, notes, section, priority,
|
||||
scheduled_date, reminder_time
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
ON CONFLICT (routine_id, scheduled_date) DO NOTHING",
|
||||
&[
|
||||
&routine.id,
|
||||
&routine.title,
|
||||
&routine.notes,
|
||||
&routine.section,
|
||||
&routine.priority,
|
||||
&date,
|
||||
&reminder_time,
|
||||
],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
}
|
||||
}
|
||||
usize::try_from(inserted).map_err(|_| "generated task count overflow".to_owned())
|
||||
}
|
||||
|
||||
pub fn next_due_notification(&self, date: &str, time: &str) -> Result<Option<DueNotification>> {
|
||||
let date = parse_date(date)?;
|
||||
let time = parse_reminder(Some(time))?.expect("provided reminder is present");
|
||||
let mut client = self.connect()?;
|
||||
let row = client
|
||||
.query_opt(
|
||||
"SELECT id, title, section, priority
|
||||
FROM tasks
|
||||
WHERE scheduled_date = $1
|
||||
AND reminder_time IS NOT NULL
|
||||
AND reminder_time <= $2
|
||||
AND notification_sent_at IS NULL
|
||||
AND status = 'pending'
|
||||
ORDER BY reminder_time, id
|
||||
LIMIT 1",
|
||||
&[&date, &time],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(row.map(|row| DueNotification {
|
||||
task_id: row.get(0),
|
||||
title: row.get(1),
|
||||
section: row.get(2),
|
||||
priority: row.get(3),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn mark_notification_sent(&self, task_id: i64) -> Result<()> {
|
||||
let mut client = self.connect()?;
|
||||
client
|
||||
.execute(
|
||||
"UPDATE tasks SET notification_sent_at = now() WHERE id = $1",
|
||||
&[&task_id],
|
||||
)
|
||||
.map_err(db_error)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_title(title: &str) -> Result<()> {
|
||||
if title.trim().is_empty() {
|
||||
Err("title must not be empty".to_owned())
|
||||
} else if title.len() > 300 {
|
||||
Err("title must be at most 300 bytes".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_date(date: &str) -> Result<NaiveDate> {
|
||||
NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| "date must use YYYY-MM-DD".to_owned())
|
||||
}
|
||||
|
||||
fn parse_reminder(reminder: Option<&str>) -> Result<Option<NaiveTime>> {
|
||||
reminder
|
||||
.map(|value| {
|
||||
NaiveTime::parse_from_str(value, "%H:%M")
|
||||
.map_err(|_| "reminder_time must use HH:MM".to_owned())
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn validate_schedule(schedule: &Schedule) -> Result<()> {
|
||||
match schedule {
|
||||
Schedule::Daily => Ok(()),
|
||||
Schedule::Weekly { weekdays } => {
|
||||
if weekdays.is_empty() || weekdays.iter().any(|day| !(1..=7).contains(day)) {
|
||||
Err("weekly weekdays must contain ISO values 1 through 7".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Schedule::Monthly { days, .. } => {
|
||||
if days.is_empty() || days.iter().any(|day| !(1..=31).contains(day)) {
|
||||
Err("monthly days must contain values 1 through 31".to_owned())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_matches(schedule: &Schedule, date: NaiveDate) -> Result<bool> {
|
||||
match schedule {
|
||||
Schedule::Daily => Ok(true),
|
||||
Schedule::Weekly { weekdays } => {
|
||||
Ok(weekdays.contains(&date.weekday().number_from_monday()))
|
||||
}
|
||||
Schedule::Monthly {
|
||||
days,
|
||||
clamp_to_last_day,
|
||||
} => {
|
||||
let last_day = last_day_of_month(date)?;
|
||||
Ok(days.iter().any(|requested| {
|
||||
date.day() == *requested
|
||||
|| (*clamp_to_last_day && *requested > last_day && date.day() == last_day)
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn last_day_of_month(date: NaiveDate) -> Result<u32> {
|
||||
let (year, month) = if date.month() == 12 {
|
||||
(date.year() + 1, 1)
|
||||
} else {
|
||||
(date.year(), date.month() + 1)
|
||||
};
|
||||
let first_next = NaiveDate::from_ymd_opt(year, month, 1)
|
||||
.ok_or_else(|| "invalid month boundary".to_owned())?;
|
||||
let last = first_next
|
||||
.pred_opt()
|
||||
.ok_or_else(|| "invalid month boundary".to_owned())?;
|
||||
Ok(last.day())
|
||||
}
|
||||
|
||||
fn db_error(error: postgres::Error) -> String {
|
||||
format!("database error: {error}")
|
||||
}
|
||||
|
||||
fn json_error(error: serde_json::Error) -> String {
|
||||
format!("JSON error: {error}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn weekly_schedule_uses_iso_weekdays() {
|
||||
let monday = NaiveDate::from_ymd_opt(2026, 10, 19).unwrap();
|
||||
assert!(schedule_matches(
|
||||
&Schedule::Weekly {
|
||||
weekdays: vec![1, 3],
|
||||
},
|
||||
monday
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monthly_day_clamps_to_end_of_short_month() {
|
||||
let february_end = NaiveDate::from_ymd_opt(2027, 2, 28).unwrap();
|
||||
assert!(schedule_matches(
|
||||
&Schedule::Monthly {
|
||||
days: vec![31],
|
||||
clamp_to_last_day: true,
|
||||
},
|
||||
february_end,
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monthly_day_does_not_clamp_when_disabled() {
|
||||
let february_end = NaiveDate::from_ymd_opt(2027, 2, 28).unwrap();
|
||||
assert!(!schedule_matches(
|
||||
&Schedule::Monthly {
|
||||
days: vec![31],
|
||||
clamp_to_last_day: false,
|
||||
},
|
||||
february_end,
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user