716 lines
25 KiB
Rust
716 lines
25 KiB
Rust
use chrono::{Datelike, Days, NaiveDate, NaiveTime};
|
|
use postgres::{Client, NoTls};
|
|
|
|
use crate::model::{
|
|
CreateEncryptionDevice, CreateRoutine, CreateTask, DueNotification, EncryptionDevice,
|
|
EncryptionRecipient, 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,
|
|
public_title TEXT NOT NULL,
|
|
encrypted_payload TEXT,
|
|
encryption_version SMALLINT,
|
|
content_id 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(),
|
|
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
|
|
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
|
|
);
|
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
routine_id BIGINT REFERENCES routines(id),
|
|
public_title TEXT NOT NULL,
|
|
encrypted_payload TEXT,
|
|
encryption_version SMALLINT,
|
|
content_id TEXT,
|
|
section TEXT NOT NULL,
|
|
priority TEXT NOT NULL,
|
|
scheduled_date DATE NOT NULL,
|
|
reminder_time TIME,
|
|
status TEXT NOT NULL DEFAULT 'pending',
|
|
status_before_archive TEXT,
|
|
completed_at TIMESTAMPTZ,
|
|
archived_at TIMESTAMPTZ,
|
|
notification_sent_at TIMESTAMPTZ,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
UNIQUE(routine_id, scheduled_date),
|
|
CHECK ((encrypted_payload IS NULL AND encryption_version IS NULL AND content_id IS NULL)
|
|
OR (encrypted_payload IS NOT NULL AND encryption_version IS NOT NULL AND content_id IS NOT NULL))
|
|
);
|
|
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);
|
|
ALTER TABLE tasks
|
|
ADD COLUMN IF NOT EXISTS status_before_archive TEXT;
|
|
ALTER TABLE tasks
|
|
ADD COLUMN IF NOT EXISTS archived_at TIMESTAMPTZ;
|
|
CREATE TABLE IF NOT EXISTS encryption_devices (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
age_recipient TEXT NOT NULL UNIQUE,
|
|
status TEXT NOT NULL DEFAULT 'active',
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
revoked_at TIMESTAMPTZ,
|
|
CHECK (status IN ('active', 'revoked')),
|
|
CHECK ((status = 'active' AND revoked_at IS NULL)
|
|
OR (status = 'revoked' AND revoked_at IS NOT NULL))
|
|
);",
|
|
)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn list_encryption_devices(&self) -> Result<Vec<EncryptionDevice>> {
|
|
let mut client = self.connect()?;
|
|
let rows = client
|
|
.query(
|
|
"SELECT id, name, age_recipient, status,
|
|
EXTRACT(EPOCH FROM created_at)::BIGINT,
|
|
EXTRACT(EPOCH FROM revoked_at)::BIGINT
|
|
FROM encryption_devices
|
|
ORDER BY status, id",
|
|
&[],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(rows
|
|
.into_iter()
|
|
.map(|row| EncryptionDevice {
|
|
id: row.get(0),
|
|
name: row.get(1),
|
|
age_recipient: row.get(2),
|
|
status: row.get(3),
|
|
created_at: row.get(4),
|
|
revoked_at: row.get(5),
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
pub fn list_encryption_recipients(&self) -> Result<Vec<EncryptionRecipient>> {
|
|
let mut client = self.connect()?;
|
|
let rows = client
|
|
.query(
|
|
"SELECT id, name, age_recipient
|
|
FROM encryption_devices
|
|
WHERE status = 'active'
|
|
ORDER BY id",
|
|
&[],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(rows
|
|
.into_iter()
|
|
.map(|row| EncryptionRecipient {
|
|
id: row.get(0),
|
|
name: row.get(1),
|
|
age_recipient: row.get(2),
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
pub fn create_encryption_device(&self, device: CreateEncryptionDevice) -> Result<i64> {
|
|
let name = device.name.trim();
|
|
let recipient = device.age_recipient.trim();
|
|
validate_device(name, recipient)?;
|
|
let mut client = self.connect()?;
|
|
let row = client
|
|
.query_one(
|
|
"INSERT INTO encryption_devices (name, age_recipient)
|
|
VALUES ($1, $2)
|
|
RETURNING id",
|
|
&[&name, &recipient],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(row.get(0))
|
|
}
|
|
|
|
pub fn revoke_encryption_device(&self, id: i64) -> Result<bool> {
|
|
let mut client = self.connect()?;
|
|
client
|
|
.execute(
|
|
"UPDATE encryption_devices
|
|
SET status = 'revoked', revoked_at = now()
|
|
WHERE id = $1 AND status = 'active'",
|
|
&[&id],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn create_task(&self, task: CreateTask) -> Result<i64> {
|
|
validate_public_title(&task.public_title)?;
|
|
validate_encrypted_fields(
|
|
task.encrypted_payload.as_deref(),
|
|
task.encryption_version,
|
|
task.content_id.as_deref(),
|
|
)?;
|
|
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 (
|
|
public_title, encrypted_payload, encryption_version, content_id,
|
|
section, priority, scheduled_date, reminder_time
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
RETURNING id",
|
|
&[
|
|
&task.public_title.trim(),
|
|
&task.encrypted_payload,
|
|
&task.encryption_version,
|
|
&task.content_id,
|
|
&task.section.as_str(),
|
|
&task.priority.as_str(),
|
|
&scheduled_date,
|
|
&reminder_time,
|
|
],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(row.get(0))
|
|
}
|
|
|
|
pub fn update_task(&self, id: i64, task: CreateTask) -> Result<bool> {
|
|
validate_public_title(&task.public_title)?;
|
|
validate_encrypted_fields(
|
|
task.encrypted_payload.as_deref(),
|
|
task.encryption_version,
|
|
task.content_id.as_deref(),
|
|
)?;
|
|
let scheduled_date = parse_date(&task.scheduled_date)?;
|
|
let reminder_time = parse_reminder(task.reminder_time.as_deref())?;
|
|
|
|
let mut client = self.connect()?;
|
|
client
|
|
.execute(
|
|
"UPDATE tasks
|
|
SET public_title = $1,
|
|
encrypted_payload = $2,
|
|
encryption_version = $3,
|
|
content_id = $4,
|
|
section = $5,
|
|
priority = $6,
|
|
scheduled_date = $7,
|
|
reminder_time = $8,
|
|
notification_sent_at = NULL
|
|
WHERE id = $9 AND status != 'archived'",
|
|
&[
|
|
&task.public_title.trim(),
|
|
&task.encrypted_payload,
|
|
&task.encryption_version,
|
|
&task.content_id,
|
|
&task.section.as_str(),
|
|
&task.priority.as_str(),
|
|
&scheduled_date,
|
|
&reminder_time,
|
|
&id,
|
|
],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
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, public_title, encrypted_payload,
|
|
encryption_version, content_id, section, priority,
|
|
scheduled_date, reminder_time, status,
|
|
EXTRACT(EPOCH FROM completed_at)::BIGINT
|
|
FROM tasks
|
|
WHERE scheduled_date = $1
|
|
AND status != 'archived'
|
|
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(task_from_row).collect())
|
|
}
|
|
|
|
pub fn list_overdue_tasks(&self, before: &str) -> Result<Vec<Task>> {
|
|
let before = parse_date(before)?;
|
|
let mut client = self.connect()?;
|
|
let rows = client
|
|
.query(
|
|
"SELECT id, routine_id, public_title, encrypted_payload,
|
|
encryption_version, content_id, section, priority,
|
|
scheduled_date, reminder_time, status,
|
|
EXTRACT(EPOCH FROM completed_at)::BIGINT
|
|
FROM tasks
|
|
WHERE scheduled_date < $1
|
|
AND status = 'pending'
|
|
ORDER BY scheduled_date,
|
|
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",
|
|
&[&before],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(rows.into_iter().map(task_from_row).collect())
|
|
}
|
|
|
|
pub fn list_archived_tasks(&self) -> Result<Vec<Task>> {
|
|
let mut client = self.connect()?;
|
|
let rows = client
|
|
.query(
|
|
"SELECT id, routine_id, public_title, encrypted_payload,
|
|
encryption_version, content_id, section, priority,
|
|
scheduled_date, reminder_time, status,
|
|
EXTRACT(EPOCH FROM completed_at)::BIGINT
|
|
FROM tasks
|
|
WHERE status = 'archived'
|
|
ORDER BY archived_at DESC, id DESC",
|
|
&[],
|
|
)
|
|
.map_err(db_error)?;
|
|
Ok(rows.into_iter().map(task_from_row).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 NOT IN ('completed', 'archived')",
|
|
&[&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 AND status != 'archived'",
|
|
&[&date, &id],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn archive_task(&self, id: i64) -> Result<bool> {
|
|
let mut client = self.connect()?;
|
|
client
|
|
.execute(
|
|
"UPDATE tasks
|
|
SET status_before_archive = status,
|
|
status = 'archived',
|
|
archived_at = now()
|
|
WHERE id = $1 AND status != 'archived'",
|
|
&[&id],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn restore_task(&self, id: i64) -> Result<bool> {
|
|
let mut client = self.connect()?;
|
|
client
|
|
.execute(
|
|
"UPDATE tasks
|
|
SET status = COALESCE(status_before_archive, 'pending'),
|
|
status_before_archive = NULL,
|
|
archived_at = NULL
|
|
WHERE id = $1 AND status = 'archived'",
|
|
&[&id],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn delete_archived_task(&self, id: i64) -> Result<bool> {
|
|
let mut client = self.connect()?;
|
|
client
|
|
.execute(
|
|
"DELETE FROM tasks WHERE id = $1 AND status = 'archived'",
|
|
&[&id],
|
|
)
|
|
.map(|changed| changed == 1)
|
|
.map_err(db_error)
|
|
}
|
|
|
|
pub fn create_routine(&self, routine: CreateRoutine) -> Result<i64> {
|
|
validate_public_title(&routine.public_title)?;
|
|
validate_encrypted_fields(
|
|
routine.encrypted_payload.as_deref(),
|
|
routine.encryption_version,
|
|
routine.content_id.as_deref(),
|
|
)?;
|
|
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 (
|
|
public_title, encrypted_payload, encryption_version, content_id,
|
|
section, priority, schedule_json, reminder_time
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
RETURNING id",
|
|
&[
|
|
&routine.public_title.trim(),
|
|
&routine.encrypted_payload,
|
|
&routine.encryption_version,
|
|
&routine.content_id,
|
|
&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, public_title, encrypted_payload, encryption_version,
|
|
content_id, 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(7);
|
|
let schedule = serde_json::from_value(schedule_json).map_err(json_error)?;
|
|
let reminder_time: Option<NaiveTime> = row.get(8);
|
|
Ok(Routine {
|
|
id: row.get(0),
|
|
public_title: row.get(1),
|
|
encrypted_payload: row.get(2),
|
|
encryption_version: row.get(3),
|
|
content_id: row.get(4),
|
|
section: row.get(5),
|
|
priority: row.get(6),
|
|
schedule,
|
|
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
|
enabled: row.get(9),
|
|
})
|
|
})
|
|
.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, public_title, encrypted_payload,
|
|
encryption_version, content_id, section, priority,
|
|
scheduled_date, reminder_time
|
|
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
|
ON CONFLICT (routine_id, scheduled_date) DO NOTHING",
|
|
&[
|
|
&routine.id,
|
|
&routine.public_title,
|
|
&routine.encrypted_payload,
|
|
&routine.encryption_version,
|
|
&routine.content_id,
|
|
&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, public_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),
|
|
public_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 task_from_row(row: postgres::Row) -> Task {
|
|
let scheduled_date: NaiveDate = row.get(8);
|
|
let reminder_time: Option<NaiveTime> = row.get(9);
|
|
Task {
|
|
id: row.get(0),
|
|
routine_id: row.get(1),
|
|
public_title: row.get(2),
|
|
encrypted_payload: row.get(3),
|
|
encryption_version: row.get(4),
|
|
content_id: row.get(5),
|
|
section: row.get(6),
|
|
priority: row.get(7),
|
|
scheduled_date: scheduled_date.to_string(),
|
|
reminder_time: reminder_time.map(|time| time.format("%H:%M").to_string()),
|
|
status: row.get(10),
|
|
completed_at: row.get(11),
|
|
}
|
|
}
|
|
|
|
fn validate_public_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 validate_device(name: &str, recipient: &str) -> Result<()> {
|
|
if name.is_empty() {
|
|
return Err("device name must not be empty".to_owned());
|
|
}
|
|
if name.len() > 100 {
|
|
return Err("device name must be at most 100 bytes".to_owned());
|
|
}
|
|
if recipient.is_empty() {
|
|
return Err("age recipient must not be empty".to_owned());
|
|
}
|
|
if recipient.len() > 4096 || recipient.contains('\n') || recipient.contains('\r') {
|
|
return Err("age recipient must be a single line of at most 4096 bytes".to_owned());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn validate_encrypted_fields(
|
|
payload: Option<&str>,
|
|
version: Option<i16>,
|
|
content_id: Option<&str>,
|
|
) -> Result<()> {
|
|
if payload.map(str::len).unwrap_or(0) > 128 * 1024 {
|
|
return Err("encrypted_payload must be at most 128 KiB".to_owned());
|
|
}
|
|
if content_id.map(str::len).unwrap_or(0) > 128 {
|
|
return Err("content_id must be at most 128 bytes".to_owned());
|
|
}
|
|
if payload.is_some() == version.is_some() && version.is_some() == content_id.is_some() {
|
|
Ok(())
|
|
} else {
|
|
Err("encrypted_payload, encryption_version, and content_id must be set together".to_owned())
|
|
}
|
|
}
|
|
|
|
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());
|
|
}
|
|
|
|
#[test]
|
|
fn validates_encryption_device_fields() {
|
|
assert!(validate_device("Laptop", "age1example").is_ok());
|
|
assert_eq!(
|
|
validate_device("", "age1example").unwrap_err(),
|
|
"device name must not be empty"
|
|
);
|
|
assert!(validate_device("Laptop", "age1example\nother").is_err());
|
|
}
|
|
}
|