diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d530f4..f561515 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## Unreleased + +- Household multi-step chores: a multi-step chore belongs to its project's owner, so one + in a project shared with your household is everyone's, and anyone in it can start it. + Sharing a project shares its multi-step chores too. +- The Routines page lists your own routines and multi-step chores first, then each + household group's under "Shared with …". +- Who does it: give a shared task to one person. Everyone still sees it ("→ Ben") and + anyone can tick it off, but it only shows up on that person's Today, planner and morning + digest. +- Routines and multi-step chores can give what they make to one person by default, or let + people take turns (one occurrence or run each, in the order you pick). Starting a + multi-step chore shows whose turn it is; every step of a run goes to the same person. +- Leaving a group hands your chores in it back to anyone, and takes you out of the turns. +- Fixed: a routine shared with a group that starts a multi-step chore was always skipped; + it now starts the run. Sharing a project now also shares the routines in it (they used + to stay with their creator). + ## 1.5.0 (2026-10-18) - Tracking has its own page (under Reflect in the menu, "Track" in the phone tab bar, or diff --git a/crates/domain/src/assign.rs b/crates/domain/src/assign.rs new file mode 100644 index 0000000..47e090b --- /dev/null +++ b/crates/domain/src/assign.rs @@ -0,0 +1,160 @@ +//! Who does a shared chore (D-116): its default assignee, or members taking turns. +//! Mirrored in `web/src/lib/assign.ts`. + +use chrono::{Duration, NaiveDate}; + +use crate::recurrence::{Schedule, plan_occurrences}; + +/// The person for the `turn`th occurrence or run of a chore (counting from 0). +/// +/// With a rotation, the people in it who are still in the group take turns in order +/// (someone who left is skipped, and the others close up). Without one, or when nobody in +/// it is left, it's the default assignee while they're still in the group; else nobody. +pub fn assignee_for( + default: Option<&str>, + rotation: &[String], + members: &[String], + turn: u64, +) -> Option { + let turns: Vec<&String> = rotation.iter().filter(|u| members.contains(u)).collect(); + if !turns.is_empty() { + return Some(turns[(turn % turns.len() as u64) as usize].clone()); + } + default + .filter(|u| members.iter().any(|m| m == u)) + .map(str::to_string) +} + +/// Which turn an occurrence of a routine is (from 0): how many occurrences come before it +/// since the routine's first day. Counted a year at a time, so it keeps counting past the +/// 1000 dates one recurrence query returns. +pub fn turn_of( + schedule: &Schedule, + dtstart: NaiveDate, + until: Option, + key: &str, + day: NaiveDate, + week_start: u32, +) -> Result { + let mut n = 0; + let mut from = dtstart; + while from <= day { + let to = (from + Duration::days(364)).min(day); + for o in plan_occurrences(schedule, dtstart, until, from, to, week_start)? { + // A flexible window overlapping two years counts once, in the year it starts. + if o.date < from || o.date > to { + continue; + } + if o.key == key { + return Ok(n); + } + n += 1; + } + from = to + Duration::days(1); + } + Ok(n) +} + +/// A rotation as given, without repeats or people outside the group (order kept). +pub fn clean_rotation(rotation: &[String], members: &[String]) -> Vec { + let mut out: Vec = vec![]; + for u in rotation { + if members.contains(u) && !out.contains(u) { + out.push(u.clone()); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::recurrence::Window; + + fn v(xs: &[&str]) -> Vec { + xs.iter().map(|x| x.to_string()).collect() + } + + #[test] + fn default_assignee_while_in_the_group() { + let members = v(&["anna", "ben"]); + assert_eq!( + assignee_for(Some("ben"), &[], &members, 0), + Some("ben".into()) + ); + assert_eq!( + assignee_for(Some("ben"), &[], &members, 7), + Some("ben".into()) + ); + assert_eq!(assignee_for(Some("cid"), &[], &members, 0), None); + assert_eq!(assignee_for(None, &[], &members, 0), None); + } + + #[test] + fn rotation_takes_turns_in_order() { + let members = v(&["anna", "ben", "cid"]); + let rot = v(&["ben", "anna", "cid"]); + let got: Vec<_> = (0..5) + .map(|n| assignee_for(Some("anna"), &rot, &members, n).unwrap()) + .collect(); + assert_eq!(got, ["ben", "anna", "cid", "ben", "anna"]); + } + + #[test] + fn people_who_left_are_skipped() { + let rot = v(&["anna", "ben", "cid"]); + let members = v(&["anna", "cid"]); + let got: Vec<_> = (0..4) + .map(|n| assignee_for(None, &rot, &members, n).unwrap()) + .collect(); + assert_eq!(got, ["anna", "cid", "anna", "cid"]); + // Nobody left in the rotation: the default, if they're still in. + assert_eq!( + assignee_for(Some("anna"), &v(&["ben"]), &members, 3), + Some("anna".into()) + ); + assert_eq!(assignee_for(Some("ben"), &v(&["ben"]), &members, 3), None); + } + + #[test] + fn turns_keep_counting_for_years() { + let d = |s: &str| NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap(); + let daily = Schedule::Rule { + rule: "FREQ=DAILY".into(), + }; + let start = d("2024-01-01"); + let day = d("2027-06-30"); + let key = plan_occurrences(&daily, start, None, day, day, 1).unwrap()[0] + .key + .clone(); + assert_eq!( + turn_of(&daily, start, None, &key, day, 1).unwrap(), + (day - start).num_days() as u64 + ); + // Twice a week: windows across a year boundary count once. + let flex = Schedule::Flexible { + times: 2, + window: Window::Week, + }; + let day = d("2026-01-05"); + let occ = plan_occurrences(&flex, start, None, day, day, 1).unwrap(); + let weeks = (day - d("2024-01-01")).num_days() as u64 / 7; + assert_eq!( + turn_of(&flex, start, None, &occ[0].key, day, 1).unwrap(), + weeks * 2 + ); + assert_eq!( + turn_of(&flex, start, None, &occ[1].key, day, 1).unwrap(), + weeks * 2 + 1 + ); + } + + #[test] + fn cleaning_keeps_order_and_drops_strangers_and_repeats() { + let members = v(&["anna", "ben", "cid"]); + assert_eq!( + clean_rotation(&v(&["cid", "zed", "anna", "cid"]), &members), + ["cid", "anna"] + ); + } +} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs index f3696e1..c61b824 100644 --- a/crates/domain/src/lib.rs +++ b/crates/domain/src/lib.rs @@ -1,6 +1,7 @@ //! Pure domain logic for Streamline: no IO, no database, no HTTP. //! Everything here is deterministic and unit-tested. +pub mod assign; pub mod calendar; pub mod checklist; pub mod conflicts; diff --git a/crates/server/src/blocks.rs b/crates/server/src/blocks.rs index 00731c4..ca674ca 100644 --- a/crates/server/src/blocks.rs +++ b/crates/server/src/blocks.rs @@ -277,6 +277,7 @@ async fn routine_occurrence( WHERE t.series_id IN (SELECT value FROM json_each(?1)) AND t.deleted_at IS NULL AND t.status = 'open' AND (t.occurrence_date = ?2 OR t.window_end IS NOT NULL AND t.occurrence_date <= ?2 AND t.window_end >= ?2) AND t.id NOT IN (SELECT value FROM json_each(?5)) + AND (t.assignee_user_id IS NULL OR t.assignee_user_id = ?3) AND NOT EXISTS (SELECT 1 FROM day_entries e WHERE e.task_id = t.id AND e.user_id = ?3 AND e.deleted_at IS NULL AND e.date >= ?4) ORDER BY t.occurrence_key LIMIT 1", diff --git a/crates/server/src/digest.rs b/crates/server/src/digest.rs index b4415e8..2c09876 100644 --- a/crates/server/src/digest.rs +++ b/crates/server/src/digest.rs @@ -76,6 +76,8 @@ pub async fn gather(state: &AppState, user: &User, day: NaiveDate) -> anyhow::Re WHERE {visible} AND t.deleted_at IS NULL AND t.status = 'open' AND t.due_date IS NOT NULL AND t.due_date <= ?2 -- an ongoing task's end date is mentioned on its last day only (D-102) AND (t.ongoing = 0 OR t.due_date = ?2) + -- someone else's chore isn't yours to do (D-116) + AND (t.assignee_user_id IS NULL OR t.assignee_user_id = ?1) AND NOT EXISTS (SELECT 1 FROM day_entries e WHERE e.task_id = t.id AND e.date = ?2 AND e.deleted_at IS NULL) ORDER BY t.due_date LIMIT 20" )) diff --git a/crates/server/src/federation.rs b/crates/server/src/federation.rs index b446c5f..3e5e918 100644 --- a/crates/server/src/federation.rs +++ b/crates/server/src/federation.rs @@ -212,6 +212,7 @@ pub async fn revoke(state: &AppState, link_id: &str) -> anyhow::Result<()> { .bind(&link.remote_user_id) .execute(&mut *tx) .await?; + changes.extend(crate::ownership::unassign(&mut tx, &g, &link.remote_user_id).await?); bump_group(&mut tx, &g).await?; if let Some(gr) = crate::routes::groups::load(&mut tx, &g).await? { changes.push(Change::group(&gr, &[])); diff --git a/crates/server/src/models.rs b/crates/server/src/models.rs index e543e44..0233c75 100644 --- a/crates/server/src/models.rs +++ b/crates/server/src/models.rs @@ -426,6 +426,16 @@ pub struct WorkflowTemplate { #[ts(as = "Vec")] #[schema(value_type = Vec)] pub variants: sqlx::types::Json>, + /// Who each run goes to by default in a shared chore (D-116); every step of a run goes + /// to the same person. + pub assignee_user_id: Option, + /// Members taking turns, one run each (empty = no rotation; D-116). + #[ts(type = "Array")] + #[schema(value_type = Vec)] + pub rotation_user_ids: sqlx::types::Json>, + /// Runs started so far: the next one goes to the member at this turn. + #[ts(type = "number")] + pub rotation_turn: i64, pub created_at: String, pub updated_at: String, pub deleted_at: Option, @@ -524,13 +534,16 @@ pub async fn upsert_workflow( w: &WorkflowTemplate, ) -> sqlx::Result<()> { sqlx::query( - "INSERT INTO workflow_templates (id, owner_user_id, owner_group_id, name, description, project_id, steps, variants, created_at, updated_at, deleted_at, rev) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?) - ON CONFLICT(id) DO UPDATE SET name=excluded.name, description=excluded.description, project_id=excluded.project_id, - steps=excluded.steps, variants=excluded.variants, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, rev=excluded.rev", + "INSERT INTO workflow_templates (id, owner_user_id, owner_group_id, name, description, project_id, steps, variants, + assignee_user_id, rotation_user_ids, rotation_turn, created_at, updated_at, deleted_at, rev) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET owner_user_id=excluded.owner_user_id, owner_group_id=excluded.owner_group_id, name=excluded.name, description=excluded.description, project_id=excluded.project_id, + steps=excluded.steps, variants=excluded.variants, assignee_user_id=excluded.assignee_user_id, + rotation_user_ids=excluded.rotation_user_ids, rotation_turn=excluded.rotation_turn, + updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, rev=excluded.rev", ) .bind(&w.id).bind(&w.owner_user_id).bind(&w.owner_group_id).bind(&w.name).bind(&w.description).bind(&w.project_id) - .bind(&w.steps).bind(&w.variants).bind(&w.created_at).bind(&w.updated_at).bind(&w.deleted_at).bind(w.rev) + .bind(&w.steps).bind(&w.variants).bind(&w.assignee_user_id).bind(&w.rotation_user_ids).bind(w.rotation_turn).bind(&w.created_at).bind(&w.updated_at).bind(&w.deleted_at).bind(w.rev) .execute(conn) .await .map(|_| ()) @@ -612,6 +625,15 @@ pub struct Series { #[ts(as = "Vec")] #[schema(value_type = Vec)] pub checklist: sqlx::types::Json>, + /// Who each occurrence of a shared routine goes to by default (D-116). (Defaults keep + /// feeds from servers before 1.6 readable, Phase 8.) + #[serde(default)] + pub assignee_user_id: Option, + /// Members taking turns, one occurrence each (empty = no rotation; D-116). + #[serde(default)] + #[ts(type = "Array")] + #[schema(value_type = Vec)] + pub rotation_user_ids: sqlx::types::Json>, #[serde(skip)] #[ts(skip)] pub materialized_through: Option, @@ -776,22 +798,25 @@ pub async fn upsert_series(conn: &mut SqliteConnection, s: &Series) -> sqlx::Res sqlx::query( "INSERT INTO series (id, owner_user_id, owner_group_id, project_id, title, notes, mode, rrule, dtstart, until, start_time, duration_min, times_per_window, window, task_type_id, estimate_min, difficulty, importance, urgency, - materialized_through, split_from, place_id, workflow_template_id, workflow_variant_ids, checklist, created_at, updated_at, deleted_at, rev) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) - ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id, title=excluded.title, notes=excluded.notes, + materialized_through, split_from, place_id, workflow_template_id, workflow_variant_ids, checklist, + assignee_user_id, rotation_user_ids, created_at, updated_at, deleted_at, rev) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT(id) DO UPDATE SET owner_user_id=excluded.owner_user_id, owner_group_id=excluded.owner_group_id, project_id=excluded.project_id, title=excluded.title, notes=excluded.notes, mode=excluded.mode, rrule=excluded.rrule, dtstart=excluded.dtstart, until=excluded.until, start_time=excluded.start_time, duration_min=excluded.duration_min, times_per_window=excluded.times_per_window, window=excluded.window, task_type_id=excluded.task_type_id, estimate_min=excluded.estimate_min, difficulty=excluded.difficulty, importance=excluded.importance, urgency=excluded.urgency, place_id=excluded.place_id, workflow_template_id=excluded.workflow_template_id, workflow_variant_ids=excluded.workflow_variant_ids, checklist=excluded.checklist, + assignee_user_id=excluded.assignee_user_id, rotation_user_ids=excluded.rotation_user_ids, materialized_through=excluded.materialized_through, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, rev=excluded.rev", ) .bind(&s.id).bind(&s.owner_user_id).bind(&s.owner_group_id).bind(&s.project_id).bind(&s.title).bind(&s.notes) .bind(&s.mode).bind(&s.rrule).bind(&s.dtstart).bind(&s.until).bind(&s.start_time).bind(s.duration_min) .bind(s.times_per_window).bind(&s.window).bind(&s.task_type_id).bind(s.estimate_min).bind(s.difficulty) - .bind(s.importance).bind(s.urgency).bind(&s.materialized_through).bind(&s.split_from).bind(&s.place_id).bind(&s.workflow_template_id).bind(&s.workflow_variant_ids).bind(&s.checklist).bind(&s.created_at).bind(&s.updated_at) + .bind(s.importance).bind(s.urgency).bind(&s.materialized_through).bind(&s.split_from).bind(&s.place_id).bind(&s.workflow_template_id).bind(&s.workflow_variant_ids).bind(&s.checklist) + .bind(&s.assignee_user_id).bind(&s.rotation_user_ids).bind(&s.created_at).bind(&s.updated_at) .bind(&s.deleted_at).bind(s.rev) .execute(conn) .await diff --git a/crates/server/src/ownership.rs b/crates/server/src/ownership.rs index d1ba57d..5006299 100644 --- a/crates/server/src/ownership.rs +++ b/crates/server/src/ownership.rs @@ -1,13 +1,18 @@ //! Who owns what (Phase 4): a user or a group. Tasks and routines in a project share the -//! project's owner; sharing a top-level project with a group shares its whole subtree. +//! project's owner, and so do multi-step chores (D-115); sharing a top-level project with a +//! group shares its whole subtree. use sqlx::SqliteConnection; use crate::{ auth::AuthUser, + db::next_rev, error::{ApiResult, bad}, events::Change, - models::{Project, Series, Task, upsert_project, upsert_series, upsert_task}, + models::{ + Project, Series, Task, WorkflowTemplate, upsert_project, upsert_series, upsert_task, + upsert_workflow, + }, visibility, }; @@ -76,6 +81,147 @@ pub async fn project_owner( Ok(p.map(|p| Owner::of_project(&p))) } +/// Everyone in a group, people on other servers too (they can be assigned things; D-116). +pub async fn members(conn: &mut SqliteConnection, group: &str) -> sqlx::Result> { + sqlx::query_scalar( + "SELECT m.user_id FROM group_members m JOIN users u ON u.id = m.user_id + WHERE m.group_id = ? AND u.deleted_at IS NULL ORDER BY m.created_at, m.user_id", + ) + .bind(group) + .fetch_all(conn) + .await +} + +/// Check who something owned by `group` is assigned to (D-116): only shared things can +/// be, and only to someone in the group. +pub async fn check_assignee( + conn: &mut SqliteConnection, + group: Option<&str>, + assignee: Option<&str>, +) -> ApiResult<()> { + let Some(a) = assignee else { return Ok(()) }; + let Some(g) = group else { + return Err(bad("only things shared with a group can be assigned")); + }; + if !members(conn, g).await?.iter().any(|m| m == a) { + return Err(bad("only people in the group can be assigned")); + } + Ok(()) +} + +/// Check a rotation (D-116): people in the group, each once, in the order given. +pub async fn check_rotation( + conn: &mut SqliteConnection, + group: Option<&str>, + rotation: Vec, +) -> ApiResult> { + if rotation.is_empty() { + return Ok(rotation); + } + let Some(g) = group else { + return Err(bad("only things shared with a group can take turns")); + }; + let members = members(conn, g).await?; + if rotation.len() > 50 || rotation.iter().any(|u| !members.contains(u)) { + return Err(bad("only people in the group can take turns")); + } + Ok(streamline_domain::assign::clean_rotation( + &rotation, &members, + )) +} + +/// What's left of an assignment under a (new) owning group: only people in it. +async fn kept( + conn: &mut SqliteConnection, + group: Option<&str>, + assignee: Option, + rotation: Vec, +) -> sqlx::Result<(Option, Vec)> { + let Some(g) = group else { + return Ok((None, vec![])); + }; + if assignee.is_none() && rotation.is_empty() { + return Ok((None, rotation)); + } + let members = members(conn, g).await?; + Ok(( + assignee.filter(|a| members.contains(a)), + streamline_domain::assign::clean_rotation(&rotation, &members), + )) +} + +/// The assignee a task keeps when it gets a new owner (nobody, unless they're in the group). +pub async fn kept_assignee( + conn: &mut SqliteConnection, + group: Option<&str>, + assignee: Option, +) -> sqlx::Result> { + Ok(kept(conn, group, assignee, vec![]).await?.0) +} + +/// Someone left a group (or was removed): their open tasks in it go back to anyone, and +/// they're no longer the default or in the turns of its routines and multi-step chores. +pub async fn unassign( + conn: &mut SqliteConnection, + group: &str, + user_id: &str, +) -> sqlx::Result> { + let mut changes = vec![]; + let tasks: Vec = sqlx::query_as( + "SELECT * FROM tasks WHERE owner_group_id = ? AND assignee_user_id = ? AND status = 'open' AND deleted_at IS NULL", + ) + .bind(group) + .bind(user_id) + .fetch_all(&mut *conn) + .await?; + let series: Vec = sqlx::query_as( + "SELECT s.* FROM series s WHERE s.owner_group_id = ?1 AND s.deleted_at IS NULL + AND (s.assignee_user_id = ?2 OR EXISTS (SELECT 1 FROM json_each(s.rotation_user_ids) j WHERE j.value = ?2))", + ) + .bind(group) + .bind(user_id) + .fetch_all(&mut *conn) + .await?; + let workflows: Vec = sqlx::query_as( + "SELECT w.* FROM workflow_templates w WHERE w.owner_group_id = ?1 AND w.deleted_at IS NULL + AND (w.assignee_user_id = ?2 OR EXISTS (SELECT 1 FROM json_each(w.rotation_user_ids) j WHERE j.value = ?2))", + ) + .bind(group) + .bind(user_id) + .fetch_all(&mut *conn) + .await?; + if tasks.is_empty() && series.is_empty() && workflows.is_empty() { + return Ok(changes); + } + let rev = next_rev(conn).await?; + let ts = crate::util::now(); + for mut t in tasks { + t.assignee_user_id = None; + t.updated_at = ts.clone(); + t.rev = rev; + upsert_task(conn, &t).await?; + changes.push(Change::task(&t)); + } + let not_them = |u: &Option| u.clone().filter(|u| u != user_id); + for mut s in series { + s.assignee_user_id = not_them(&s.assignee_user_id); + s.rotation_user_ids.0.retain(|u| u != user_id); + s.updated_at = ts.clone(); + s.rev = rev; + upsert_series(conn, &s).await?; + changes.push(Change::series(&s)); + } + for mut w in workflows { + w.assignee_user_id = not_them(&w.assignee_user_id); + w.rotation_user_ids.0.retain(|u| u != user_id); + w.updated_at = ts.clone(); + w.rev = rev; + upsert_workflow(conn, &w).await?; + changes.push(Change::workflow(&w)); + } + Ok(changes) +} + /// Tell people who could see something but no longer can that it's gone for them. pub fn gone_for(change: &Change, old: &[String], ts: &str) -> Option { let lost: Vec = old @@ -96,7 +242,8 @@ pub fn gone_for(change: &Change, old: &[String], ts: &str) -> Option { }) } -/// Give a project, its subprojects, and their tasks and routines a new owner. +/// Give a project, its subprojects, and their tasks, routines and multi-step chores a new +/// owner. pub async fn reown_subtree( conn: &mut SqliteConnection, root: &str, @@ -140,6 +287,8 @@ pub async fn reown_subtree( let old = visibility::audience(t.owner_user_id.as_deref(), t.owner_group_id.as_deref()); t.owner_user_id = owner.user.clone(); t.owner_group_id = owner.group.clone(); + t.assignee_user_id = + kept_assignee(conn, owner.group.as_deref(), t.assignee_user_id.take()).await?; t.updated_at = ts.into(); t.rev = rev; upsert_task(conn, &t).await?; @@ -156,6 +305,13 @@ pub async fn reown_subtree( let old = visibility::audience(s.owner_user_id.as_deref(), s.owner_group_id.as_deref()); s.owner_user_id = owner.user.clone(); s.owner_group_id = owner.group.clone(); + (s.assignee_user_id, s.rotation_user_ids.0) = kept( + conn, + owner.group.as_deref(), + s.assignee_user_id.take(), + std::mem::take(&mut s.rotation_user_ids.0), + ) + .await?; s.updated_at = ts.into(); s.rev = rev; upsert_series(conn, &s).await?; @@ -163,6 +319,30 @@ pub async fn reown_subtree( changes.extend(gone_for(&c, &old, ts)); changes.push(c); } + let workflows: Vec = sqlx::query_as( + "SELECT * FROM workflow_templates WHERE project_id = ? AND deleted_at IS NULL", + ) + .bind(pid) + .fetch_all(&mut *conn) + .await?; + for mut w in workflows { + let old = visibility::audience(w.owner_user_id.as_deref(), w.owner_group_id.as_deref()); + w.owner_user_id = owner.user.clone(); + w.owner_group_id = owner.group.clone(); + (w.assignee_user_id, w.rotation_user_ids.0) = kept( + conn, + owner.group.as_deref(), + w.assignee_user_id.take(), + std::mem::take(&mut w.rotation_user_ids.0), + ) + .await?; + w.updated_at = ts.into(); + w.rev = rev; + upsert_workflow(conn, &w).await?; + let c = Change::workflow(&w); + changes.extend(gone_for(&c, &old, ts)); + changes.push(c); + } } Ok(()) } diff --git a/crates/server/src/routes/account.rs b/crates/server/src/routes/account.rs index 6c71411..a17d5a8 100644 --- a/crates/server/src/routes/account.rs +++ b/crates/server/src/routes/account.rs @@ -640,6 +640,17 @@ pub async fn delete_user( .bind(&id) .execute(&mut *tx) .await?; + // Their household chores go back to anyone, and they leave the turns (D-116). + let groups: Vec = + sqlx::query_scalar("SELECT group_id FROM group_members WHERE user_id = ?") + .bind(&id) + .fetch_all(&mut *tx) + .await?; + let mut changes = vec![]; + for g in groups { + changes.extend(crate::ownership::unassign(&mut tx, &g, &id).await?); + } tx.commit().await?; + state.bus.publish(changes); Ok(StatusCode::NO_CONTENT) } diff --git a/crates/server/src/routes/days.rs b/crates/server/src/routes/days.rs index fa9535c..d33d3ca 100644 --- a/crates/server/src/routes/days.rs +++ b/crates/server/src/routes/days.rs @@ -159,7 +159,8 @@ pub async fn get_day( let tasks: Vec = sqlx::query_as(&format!( "SELECT * FROM tasks WHERE {} AND deleted_at IS NULL AND ( id IN (SELECT task_id FROM day_entries WHERE user_id = ?1 AND date = ?2 AND deleted_at IS NULL) - OR (status = 'open' AND due_date IS NOT NULL AND due_date <= ?2)) + OR (status = 'open' AND due_date IS NOT NULL AND due_date <= ?2 + AND (assignee_user_id IS NULL OR assignee_user_id = ?1))) ORDER BY position", visibility::OWNED_VISIBLE_SQL )) diff --git a/crates/server/src/routes/groups.rs b/crates/server/src/routes/groups.rs index b65c126..f6440c4 100644 --- a/crates/server/src/routes/groups.rs +++ b/crates/server/src/routes/groups.rs @@ -234,14 +234,15 @@ pub async fn delete( let owned: i64 = sqlx::query_scalar( "SELECT (SELECT COUNT(*) FROM projects WHERE owner_group_id = ?1 AND deleted_at IS NULL) + (SELECT COUNT(*) FROM tasks WHERE owner_group_id = ?1 AND deleted_at IS NULL AND status = 'open') - + (SELECT COUNT(*) FROM series WHERE owner_group_id = ?1 AND deleted_at IS NULL)", + + (SELECT COUNT(*) FROM series WHERE owner_group_id = ?1 AND deleted_at IS NULL) + + (SELECT COUNT(*) FROM workflow_templates WHERE owner_group_id = ?1 AND deleted_at IS NULL)", ) .bind(&id) .fetch_one(&mut *tx) .await?; if owned > 0 { return Err(AppError::Conflict( - "the group still has shared projects, tasks or routines; move or delete them first" + "the group still has shared projects, tasks, routines or multi-step chores; move or delete them first" .into(), )); } @@ -349,12 +350,15 @@ pub async fn remove_member( .bind(&member) .execute(&mut *tx) .await?; + // Their chores in the group go back to anyone (D-116). + let mut changes = crate::ownership::unassign(&mut tx, &id, &member).await?; bump(&mut tx, &id).await?; let g = load(&mut tx, &id).await?.ok_or(AppError::NotFound)?; tx.commit().await?; - state.bus.publish([ + changes.extend([ Change::group(&g, std::slice::from_ref(&member)), Change::membership(&member), ]); + state.bus.publish(changes); Ok(StatusCode::NO_CONTENT) } diff --git a/crates/server/src/routes/series.rs b/crates/server/src/routes/series.rs index 54538d8..c13691e 100644 --- a/crates/server/src/routes/series.rs +++ b/crates/server/src/routes/series.rs @@ -114,10 +114,22 @@ async fn check(conn: &mut sqlx::SqliteConnection, user: &AuthUser, s: &Series) - .await?; ok.map(|_| ()).ok_or_else(|| bad("unknown task type"))?; crate::routes::places::check_place(conn, user, &s.place_id).await?; + crate::ownership::check_assignee( + conn, + s.owner_group_id.as_deref(), + s.assignee_user_id.as_deref(), + ) + .await?; if let Some(w) = &s.workflow_template_id { let tpl = crate::routes::workflows::load_visible(conn, user, w) .await .map_err(|_| bad("unknown workflow"))?; + // Its runs copy the chore's steps: both must belong to the same person or group. + if (&tpl.owner_user_id, &tpl.owner_group_id) != (&s.owner_user_id, &s.owner_group_id) { + return Err(bad( + "that multi-step chore is shared differently from this routine; put both in the same project", + )); + } if s.workflow_variant_ids .0 .iter() @@ -195,6 +207,11 @@ pub struct CreateSeries { workflow_variant_ids: Option>, /// Share a routine without a project with a group (routines in a project follow it). owner_group_id: Option, + /// For a shared routine: who each occurrence goes to (D-116). + assignee_user_id: Option, + /// For a shared routine: members taking turns, one occurrence each (D-116). + #[serde(default)] + rotation_user_ids: Vec, /// Checklist each occurrence starts with (D-71). #[serde(default)] checklist: Vec, @@ -243,6 +260,8 @@ pub async fn create( workflow_template_id: c.workflow_template_id, workflow_variant_ids: sqlx::types::Json(c.workflow_variant_ids.unwrap_or_default()), checklist: sqlx::types::Json(crate::models::checklist(c.checklist).map_err(bad)?), + assignee_user_id: c.assignee_user_id, + rotation_user_ids: sqlx::types::Json(c.rotation_user_ids), materialized_through: None, split_from: None, created_at: ts.clone(), @@ -266,6 +285,12 @@ pub async fn create( } return Err(AppError::Conflict("id already in use".into())); } + s.rotation_user_ids.0 = crate::ownership::check_rotation( + &mut tx, + s.owner_group_id.as_deref(), + std::mem::take(&mut s.rotation_user_ids.0), + ) + .await?; check(&mut tx, &user, &s).await?; s.rev = next_rev(&mut tx).await?; upsert_series(&mut tx, &s).await?; @@ -301,6 +326,11 @@ pub struct PatchSeries { workflow_variant_ids: Option>, /// Checklist for occurrences from `from` on; open ones keep ticks of items still there. checklist: Option>, + /// Who occurrences from `from` on go to (`null` = anyone in the group; D-116). + #[serde(default, deserialize_with = "double_option")] + assignee_user_id: Option>, + /// Members taking turns from `from` on (empty = no rotation; D-116). + rotation_user_ids: Option>, // Schedule: changing any of these splits the routine at `from`. mode: Option, rrule: Option, @@ -422,6 +452,14 @@ pub async fn patch( if let Some(v) = c.workflow_variant_ids { next.workflow_variant_ids = sqlx::types::Json(v); } + let assignment_changed = c.assignee_user_id.is_some() || c.rotation_user_ids.is_some(); + if let Some(v) = c.assignee_user_id { + next.assignee_user_id = v; + } + if let Some(v) = c.rotation_user_ids { + next.rotation_user_ids.0 = + crate::ownership::check_rotation(&mut tx, next.owner_group_id.as_deref(), v).await?; + } let checklist_changed = c.checklist.is_some(); if let Some(v) = c.checklist { next.checklist = sqlx::types::Json(crate::models::checklist(v).map_err(bad)?); @@ -547,6 +585,72 @@ pub async fn patch( t.importance = next.importance; t.urgency = next.urgency; t.place_id = next.place_id.clone(); + if assignment_changed && let Some(key) = t.occurrence_key.clone() { + let day = t.occurrence_date.as_deref().and_then(date).unwrap_or(from); + t.assignee_user_id = routines::occurrence_assignee( + &mut tx, + &next, + &key, + day, + user.user.week_start as u32, + ) + .await?; + // A fixed-time chore is on its people's timelines by itself: it moves to + // the new assignee's (or everyone's). Other routines' plans are people's own. + if next.mode == "anchored" { + let people = routines::planners( + &mut tx, + next.owner_user_id.as_deref(), + next.owner_group_id.as_deref(), + t.assignee_user_id.as_deref(), + ) + .await?; + let entries: Vec = sqlx::query_as( + "SELECT * FROM day_entries WHERE task_id = ? AND deleted_at IS NULL", + ) + .bind(&t.id) + .fetch_all(&mut *tx) + .await?; + for e in &entries { + if people.contains(&e.user_id) { + continue; + } + let mut e = e.clone(); + e.deleted_at = Some(ts.clone()); + e.updated_at = ts.clone(); + e.rev = rev; + upsert_entry(&mut tx, &e).await?; + changes.push(Change::entry(&e)); + } + for user_id in people { + if entries.iter().any(|e| e.user_id == user_id) { + continue; + } + let last: Option = sqlx::query_scalar( + "SELECT MAX(position) FROM day_entries WHERE user_id = ? AND date = ? AND deleted_at IS NULL", + ) + .bind(&user_id) + .bind(&t.occurrence_date) + .fetch_one(&mut *tx) + .await?; + let e = DayEntry { + id: crate::util::new_id(), + user_id, + date: t.occurrence_date.clone().unwrap_or_default(), + task_id: t.id.clone(), + position: streamline_domain::order::key_after(last.as_deref()), + start_time: next.start_time.clone(), + duration_min: next.duration_min, + created_at: ts.clone(), + updated_at: ts.clone(), + deleted_at: None, + rev, + }; + upsert_entry(&mut tx, &e).await?; + changes.push(Change::entry(&e)); + } + } + } if checklist_changed { t.checklist = sqlx::types::Json(crate::models::with_checklist(&next.checklist, |new| { diff --git a/crates/server/src/routes/sync.rs b/crates/server/src/routes/sync.rs index c89354a..2387829 100644 --- a/crates/server/src/routes/sync.rs +++ b/crates/server/src/routes/sync.rs @@ -184,7 +184,7 @@ pub async fn sync( let groups = crate::routes::groups::visible_groups(&mut *state.db.read.acquire().await?, &user).await?; let workflows = sqlx::query_as( - "SELECT * FROM workflow_templates WHERE owner_user_id = ?1 AND (?2 = 0 AND deleted_at IS NULL OR ?2 > 0 AND rev > ?2)", + "SELECT * FROM workflow_templates WHERE (owner_user_id = ?1 OR owner_group_id IN (SELECT group_id FROM group_members WHERE user_id = ?1)) AND (?2 = 0 AND deleted_at IS NULL OR ?2 > 0 AND rev > ?2)", ) .bind(user.id()) .bind(since) diff --git a/crates/server/src/routes/tasks.rs b/crates/server/src/routes/tasks.rs index 0b05931..0aa29dd 100644 --- a/crates/server/src/routes/tasks.rs +++ b/crates/server/src/routes/tasks.rs @@ -187,6 +187,8 @@ pub struct CreateTask { day_entry_id: Option, /// Share a task without a project with a group (tasks in a project follow the project). owner_group_id: Option, + /// For a shared task: the member who does it (D-116). + assignee_user_id: Option, /// Steps inside the task (D-71). #[serde(default)] checklist: Vec, @@ -249,6 +251,12 @@ pub async fn create( .unwrap_or_else(|| crate::ownership::Owner::me(&user)), None => crate::ownership::chosen(&state, &user, c.owner_group_id.as_deref()).await?, }; + crate::ownership::check_assignee( + &mut tx, + owner.group.as_deref(), + c.assignee_user_id.as_deref(), + ) + .await?; check_task_type(&mut tx, &user, &task_type_id).await?; crate::routes::places::check_place(&mut tx, &user, &c.place_id).await?; check_event(&mut tx, &user, &c.event_id).await?; @@ -281,7 +289,7 @@ pub async fn create( id, owner_user_id: owner.user.clone(), owner_group_id: owner.group.clone(), - assignee_user_id: None, + assignee_user_id: c.assignee_user_id, project_id: c.project_id, title, notes: c.notes, @@ -399,6 +407,9 @@ pub struct PatchTask { /// For a task without a project: share it with a group (`null` = just you). #[serde(default, deserialize_with = "double_option")] owner_group_id: Option>, + /// For a shared task: the member who does it (`null` = anyone in the group; D-116). + #[serde(default, deserialize_with = "double_option")] + assignee_user_id: Option>, /// Waiting for results (D-70): `true` starts waiting (or changes the check-back time /// and note while waiting), `false` ends it; the task stays in progress. waiting: Option, @@ -530,6 +541,7 @@ pub async fn patch( } let old_audience = visibility::audience(t.owner_user_id.as_deref(), t.owner_group_id.as_deref()); + let old_owner = (t.owner_user_id.clone(), t.owner_group_id.clone()); let old_project = t.project_id.clone(); if let Some(v) = c.project_id { check_project(&mut tx, &user, &v).await?; @@ -555,6 +567,22 @@ pub async fn patch( t.owner_user_id = o.user; t.owner_group_id = o.group; } + // A new owner keeps the assignee only if they're in its group; then an explicit one. + if (t.owner_user_id.as_deref(), t.owner_group_id.as_deref()) + != (old_owner.0.as_deref(), old_owner.1.as_deref()) + { + t.assignee_user_id = crate::ownership::kept_assignee( + &mut tx, + t.owner_group_id.as_deref(), + t.assignee_user_id.take(), + ) + .await?; + } + if let Some(a) = c.assignee_user_id { + crate::ownership::check_assignee(&mut tx, t.owner_group_id.as_deref(), a.as_deref()) + .await?; + t.assignee_user_id = a; + } if let Some(v) = c.wait_min { check_range("wait_min", v, 0, 24 * 60)?; t.wait_min = v; diff --git a/crates/server/src/routes/workflows.rs b/crates/server/src/routes/workflows.rs index cecadd9..aa4777e 100644 --- a/crates/server/src/routes/workflows.rs +++ b/crates/server/src/routes/workflows.rs @@ -17,6 +17,7 @@ use crate::{ Series, Task, WorkflowStep, WorkflowTemplate, WorkflowVariant, upsert_series, upsert_workflow, }, + ownership::Owner, util::{check_range, double_option, id_or_new, now, parse_date}, visibility, workflows::{self, RunOptions}, @@ -87,6 +88,27 @@ fn check(name: &str, steps: &[WorkflowStep], variants: &[WorkflowVariant]) -> Ap Ok(name.to_string()) } +/// The owner a template gets from its project (D-115): a shared project's group, else you. +async fn owner_for( + conn: &mut sqlx::SqliteConnection, + state: &AppState, + user: &AuthUser, + project_id: Option<&str>, +) -> ApiResult { + let Some(p) = project_id else { + return Ok(Owner::me(user)); + }; + let project = crate::routes::projects::load_visible(conn, user, p) + .await + .map_err(|_| bad("unknown project"))?; + if crate::federation::is_replica_project(state, p).await { + return Err(bad( + "multi-step chores can't use a project shared from another server yet", + )); + } + Ok(Owner::of_project(&project)) +} + #[utoipa::path(get, path = "/workflows", tag = "workflows", summary = "List workflow templates", responses((status = 200, body = Vec), (status = 401, description = "Not signed in", body = crate::error::Problem)))] pub async fn list( State(state): State, @@ -112,6 +134,11 @@ pub struct CreateWorkflow { steps: Vec, #[serde(default)] variants: Vec, + /// For a shared chore: who each run goes to (D-116). + assignee_user_id: Option, + /// For a shared chore: members taking turns, one run each (D-116). + #[serde(default)] + rotation_user_ids: Vec, } #[utoipa::path(post, path = "/workflows", tag = "workflows", summary = "Create a workflow template", request_body = CreateWorkflow, responses((status = 200, body = WorkflowTemplate), (status = 400, description = "Invalid input", body = crate::error::Problem), (status = 401, description = "Not signed in", body = crate::error::Problem)))] @@ -129,26 +156,39 @@ pub async fn create( .fetch_optional(&mut *tx) .await? { - if existing.owner_user_id.as_deref() == Some(user.id()) { + // A replayed create (offline outbox, D-79) gets the record, shared ones too. + if visibility::can_see( + &user, + existing.owner_user_id.as_deref(), + existing.owner_group_id.as_deref(), + ) { return Ok(Json(existing)); } return Err(AppError::Conflict("id already in use".into())); } - if let Some(p) = &c.project_id { - crate::routes::projects::load_visible(&mut tx, &user, p) - .await - .map_err(|_| bad("unknown project"))?; - } + let owner = owner_for(&mut tx, &state, &user, c.project_id.as_deref()).await?; + crate::ownership::check_assignee( + &mut tx, + owner.group.as_deref(), + c.assignee_user_id.as_deref(), + ) + .await?; + let rotation = + crate::ownership::check_rotation(&mut tx, owner.group.as_deref(), c.rotation_user_ids) + .await?; let ts = now(); let w = WorkflowTemplate { id, - owner_user_id: Some(user.id().into()), - owner_group_id: None, + owner_user_id: owner.user, + owner_group_id: owner.group, name, description: c.description, project_id: c.project_id, steps: sqlx::types::Json(c.steps), variants: sqlx::types::Json(c.variants), + assignee_user_id: c.assignee_user_id, + rotation_user_ids: sqlx::types::Json(rotation), + rotation_turn: 0, created_at: ts.clone(), updated_at: ts, deleted_at: None, @@ -168,6 +208,12 @@ pub struct PatchWorkflow { project_id: Option>, steps: Option>, variants: Option>, + /// Who runs go to (`null` = anyone in the group; D-116). + #[serde(default, deserialize_with = "double_option")] + assignee_user_id: Option>, + /// Members taking turns (empty = no rotation; D-116). A changed rotation starts with + /// its first person. + rotation_user_ids: Option>, } /// Edit a template. Runs already started keep their tasks. @@ -186,14 +232,38 @@ pub async fn patch( if let Some(v) = c.description { w.description = v; } + let old_audience = + visibility::audience(w.owner_user_id.as_deref(), w.owner_group_id.as_deref()); if let Some(v) = c.project_id { - if let Some(p) = &v { - crate::routes::projects::load_visible(&mut tx, &user, p) - .await - .map_err(|_| bad("unknown project"))?; + // A template belongs to its project's owner: moving it into a shared project hands + // it to the group, out of one (or to no project) makes it yours. + let owner = owner_for(&mut tx, &state, &user, v.as_deref()).await?; + if (&owner.user, &owner.group) != (&w.owner_user_id, &w.owner_group_id) { + // Assignments only carry over to people in the new group. + let members = match &owner.group { + Some(g) => crate::ownership::members(&mut tx, g).await?, + None => vec![], + }; + w.assignee_user_id = w.assignee_user_id.take().filter(|a| members.contains(a)); + w.rotation_user_ids.0 = + streamline_domain::assign::clean_rotation(&w.rotation_user_ids.0, &members); } + w.owner_user_id = owner.user; + w.owner_group_id = owner.group; w.project_id = v; } + if let Some(a) = c.assignee_user_id { + crate::ownership::check_assignee(&mut tx, w.owner_group_id.as_deref(), a.as_deref()) + .await?; + w.assignee_user_id = a; + } + if let Some(r) = c.rotation_user_ids { + let r = crate::ownership::check_rotation(&mut tx, w.owner_group_id.as_deref(), r).await?; + if r != w.rotation_user_ids.0 { + w.rotation_turn = 0; + } + w.rotation_user_ids.0 = r; + } if let Some(v) = c.steps { w.steps = sqlx::types::Json(v); } @@ -205,7 +275,9 @@ pub async fn patch( w.rev = next_rev(&mut tx).await?; upsert_workflow(&mut tx, &w).await?; tx.commit().await?; - state.bus.publish([Change::workflow(&w)]); + let change = Change::workflow(&w); + let gone = crate::ownership::gone_for(&change, &old_audience, &w.updated_at); + state.bus.publish(gone.into_iter().chain([change])); Ok(Json(w)) } @@ -252,8 +324,13 @@ pub struct StartWorkflow { variant_ids: Vec, /// Put the steps in this project (default: the template's). project_id: Option, - /// Plan the first step of each chain into this day (`YYYY-MM-DD`). + /// Plan the first step of each chain into this day (`YYYY-MM-DD`): the day of whoever + /// does it. day: Option, + /// For a shared chore: who does this run (`null` = anyone in the group). Left out: the + /// chore's default, or whose turn it is (D-116). + #[serde(default, deserialize_with = "double_option")] + assignee_user_id: Option>, } #[utoipa::path(post, path = "/workflows/{id}/start", tag = "workflows", summary = "Start a workflow: one chain of tasks per chosen variant", params(("id" = String, Path, description = "ULID")), request_body = StartWorkflow, responses((status = 200, description = "The created step tasks", body = Vec), (status = 400, description = "Invalid input", body = crate::error::Problem), (status = 401, description = "Not signed in", body = crate::error::Problem)))] @@ -286,12 +363,30 @@ pub async fn start( "workflows can't be started in a project shared from another server yet; add its steps as tasks", )); } + let owner = match c.project_id.as_ref().or(w.project_id.as_ref()) { + Some(p) => crate::ownership::project_owner(&mut tx, p).await?, + None => None, + }; + let assignee = match c.assignee_user_id { + Some(a) => { + crate::ownership::check_assignee( + &mut tx, + owner.as_ref().and_then(|o| o.group.as_deref()), + a.as_deref(), + ) + .await?; + workflows::Assignee::Person(a) + } + None => workflows::Assignee::FromChore, + }; let opts = RunOptions { + assignee, project_id: c.project_id, day: c.day, ..Default::default() }; - let (tasks, changes) = workflows::start(&mut tx, user.id(), &w, &c.variant_ids, &opts).await?; + let (tasks, changes) = + workflows::start(&mut tx, Some(user.id()), &w, &c.variant_ids, &opts).await?; tx.commit().await?; state.bus.publish(changes); Ok(Json(tasks)) diff --git a/crates/server/src/routines.rs b/crates/server/src/routines.rs index 2da75c1..a06dd4d 100644 --- a/crates/server/src/routines.rs +++ b/crates/server/src/routines.rs @@ -19,7 +19,7 @@ use crate::{ }, rollover::today_for, util::{new_id, now}, - workflows::RunOptions, + workflows::{Assignee, RunOptions}, }; /// How far back occurrences are created when catching up after downtime. @@ -45,6 +45,39 @@ pub fn schedule(s: &Series) -> Option { } } +/// Who an occurrence of a shared routine goes to (D-116): its default assignee, or with a +/// rotation, whose turn it is (turns count the routine's occurrences from its first day, +/// so they don't depend on when occurrences are created; a new version starts again). +pub async fn occurrence_assignee( + conn: &mut SqliteConnection, + s: &Series, + key: &str, + day: NaiveDate, + week_start: u32, +) -> anyhow::Result> { + let Some(g) = &s.owner_group_id else { + return Ok(None); + }; + if s.assignee_user_id.is_none() && s.rotation_user_ids.0.is_empty() { + return Ok(None); + } + let members = crate::ownership::members(conn, g).await?; + let mut turn = 0; + if !s.rotation_user_ids.0.is_empty() + && let (Some(sched), Some(dtstart)) = (schedule(s), date(&s.dtstart)) + { + let until = s.until.as_deref().and_then(date); + turn = streamline_domain::assign::turn_of(&sched, dtstart, until, key, day, week_start) + .map_err(anyhow::Error::msg)?; + } + Ok(streamline_domain::assign::assignee_for( + s.assignee_user_id.as_deref(), + &s.rotation_user_ids.0, + &members, + turn, + )) +} + /// Create the occurrences of one routine within `[from, to]` that don't exist yet /// (including ones deleted on purpose). Returns the changes to broadcast. pub async fn materialize_series( @@ -107,7 +140,7 @@ pub async fn materialize_series( .fetch_optional(&mut *conn) .await?; if exists.is_none() { - changes.extend(start_run(conn, s, &o).await?); + changes.extend(start_run(conn, s, &o, week_start).await?); } continue; } @@ -122,23 +155,21 @@ pub async fn materialize_series( } let rev = next_rev(conn).await?; let ts = now(); - let t = occurrence_task(conn, s, &o, "open", rev).await?; + let mut t = occurrence_task(conn, s, &o, "open", rev).await?; + t.assignee_user_id = occurrence_assignee(conn, s, &o.key, o.date, week_start).await?; upsert_task(conn, &t).await?; changes.push(Change::task(&t)); // Fixed-time routines are planned on their day's timeline right away: on the - // owner's, or for a shared routine on every member's (each gets their own entry). + // owner's, or for a shared routine on the assignee's or else every member's (each + // gets their own entry). if s.mode == "anchored" { - let people: Vec = match (&s.owner_user_id, &s.owner_group_id) { - (Some(u), _) => vec![u.clone()], - (None, Some(g)) => { - // Only people of this server: day plans stay on each person's server. - sqlx::query_scalar("SELECT m.user_id FROM group_members m JOIN users u ON u.id = m.user_id WHERE m.group_id = ? AND u.home IS NULL") - .bind(g) - .fetch_all(&mut *conn) - .await? - } - _ => vec![], - }; + let people = planners( + conn, + s.owner_user_id.as_deref(), + s.owner_group_id.as_deref(), + t.assignee_user_id.as_deref(), + ) + .await?; for user_id in people { let last: Option = sqlx::query_scalar( "SELECT MAX(position) FROM day_entries WHERE user_id = ? AND date = ? AND deleted_at IS NULL", @@ -168,6 +199,30 @@ pub async fn materialize_series( Ok(changes) } +/// Whose day plans something lands on: its owner's; for a shared one its assignee's, or +/// else every member's. Only people of this server: day plans stay on each person's server. +pub async fn planners( + conn: &mut SqliteConnection, + owner_user: Option<&str>, + owner_group: Option<&str>, + assignee: Option<&str>, +) -> sqlx::Result> { + if let Some(u) = owner_user { + return Ok(vec![u.to_string()]); + } + let Some(g) = owner_group else { + return Ok(vec![]); + }; + sqlx::query_scalar( + "SELECT m.user_id FROM group_members m JOIN users u ON u.id = m.user_id + WHERE m.group_id = ?1 AND u.home IS NULL AND (?2 IS NULL OR m.user_id = ?2)", + ) + .bind(g) + .bind(assignee) + .fetch_all(conn) + .await +} + /// The task for one occurrence of a routine (not saved). async fn occurrence_task( conn: &mut SqliteConnection, @@ -246,6 +301,7 @@ async fn start_run( conn: &mut SqliteConnection, s: &Series, o: &streamline_domain::recurrence::Occurrence, + week_start: u32, ) -> anyhow::Result> { let unfinished: Option = sqlx::query_scalar( "SELECT id FROM tasks WHERE series_id = ? AND workflow_instance_id IS NOT NULL AND status = 'open' @@ -259,23 +315,48 @@ async fn start_run( .bind(&s.workflow_template_id) .fetch_optional(&mut *conn) .await?; - let (Some(tpl), None, Some(owner)) = (tpl, unfinished, s.owner_user_id.as_deref()) else { + // The chore must still belong to whoever owns the routine (it may have moved since). + let tpl = tpl + .filter(|w| (&w.owner_user_id, &w.owner_group_id) == (&s.owner_user_id, &s.owner_group_id)); + let (Some(tpl), None) = (&tpl, &unfinished) else { let rev = next_rev(conn).await?; let mut t = occurrence_task(conn, s, o, "skipped", rev).await?; - t.notes = "Skipped: the previous run of this routine wasn't finished yet.".into(); + let (notes, reason) = if unfinished.is_some() { + ( + "Skipped: the previous run of this routine wasn't finished yet.", + "previous run open", + ) + } else { + ( + "Skipped: its multi-step chore is gone or no longer shared like this routine.", + "no chore", + ) + }; + t.notes = notes.into(); upsert_task(conn, &t).await?; log_task_event( conn, &t.id, None, "skipped", - Some(serde_json::json!({"reason": "previous run open"})), + Some(serde_json::json!({ "reason": reason })), ) .await?; return Ok(vec![Change::task(&t)]); }; let day = fmt(o.date); + // The routine's own assignment wins; without one, the chore's (D-116). + let assignee = if s.assignee_user_id.is_some() || !s.rotation_user_ids.0.is_empty() { + Assignee::Person(occurrence_assignee(conn, s, &o.key, o.date, week_start).await?) + } else { + Assignee::FromChore + }; let opts = RunOptions { + owner: Some(crate::ownership::Owner { + user: s.owner_user_id.clone(), + group: s.owner_group_id.clone(), + }), + assignee, project_id: s.project_id.clone(), day: (s.mode == "anchored").then(|| day.clone()), start_time: s.start_time.clone().filter(|_| s.mode == "anchored"), @@ -285,7 +366,7 @@ async fn start_run( due_date: Some(fmt(o.window_end.unwrap_or(o.date))), }; let (_, changes) = - crate::workflows::start(conn, owner, &tpl, &s.workflow_variant_ids.0, &opts).await?; + crate::workflows::start(conn, None, tpl, &s.workflow_variant_ids.0, &opts).await?; Ok(changes) } diff --git a/crates/server/src/workflows.rs b/crates/server/src/workflows.rs index ee929c0..b7ad7e0 100644 --- a/crates/server/src/workflows.rs +++ b/crates/server/src/workflows.rs @@ -7,13 +7,26 @@ use streamline_domain::{order::key_after, workflow}; use crate::{ db::next_rev, events::Change, - models::{DayEntry, Task, WorkflowTemplate, upsert_entry, upsert_task}, + models::{DayEntry, Task, WorkflowTemplate, upsert_entry, upsert_task, upsert_workflow}, util::{new_id, now}, }; +/// Who a run goes to (D-116). +#[derive(Default)] +pub enum Assignee { + /// The chore's default assignee, or whose turn it is (which moves the turns on). + #[default] + FromChore, + /// This person (`None` = anyone in the group). + Person(Option), +} + /// Where the created tasks go and how they belong to a routine, if any. #[derive(Default)] pub struct RunOptions { + /// Who owns the steps when they have no project (a routine's owner; default: the starter). + pub owner: Option, + pub assignee: Assignee, pub project_id: Option, /// Plan the first step of each chain into this day (at `start_time`, if given). pub day: Option, @@ -26,10 +39,12 @@ pub struct RunOptions { } /// Create the runs: for each chosen variant (or the whole template if it has none, or -/// none were chosen) a chain of tasks where each step waits for the previous one. +/// none were chosen) a chain of tasks where each step waits for the previous one. All of +/// them go to one person, if any (D-116). `starter` is who pressed Start (`None` for a +/// routine). pub async fn start( conn: &mut SqliteConnection, - owner_user_id: &str, + starter: Option<&str>, tpl: &WorkflowTemplate, variant_ids: &[String], opts: &RunOptions, @@ -61,12 +76,12 @@ pub async fn start( let mut project_id = opts.project_id.clone().or(tpl.project_id.clone()); // The template's project was checked when it was saved; the starter may have lost // access since (left the group). Then the run goes to their inbox instead. - if let Some(p) = &project_id { + if let (Some(p), Some(u)) = (&project_id, starter) { let visible: bool = sqlx::query_scalar(&format!( "SELECT EXISTS(SELECT 1 FROM projects WHERE id = ?2 AND deleted_at IS NULL AND {})", crate::visibility::OWNED_VISIBLE_SQL )) - .bind(owner_user_id) + .bind(u) .bind(p) .fetch_one(&mut *conn) .await?; @@ -79,12 +94,42 @@ pub async fn start( Some(p) => crate::ownership::project_owner(conn, p).await?, None => None, } + .or(opts.owner.clone()) .unwrap_or(crate::ownership::Owner { - user: Some(owner_user_id.into()), + user: starter.map(str::to_string), group: None, }); - let mut tasks = vec![]; let mut changes = vec![]; + let assignee = match (&owner.group, &opts.assignee) { + (None, _) => None, + (Some(g), a) => { + let members = crate::ownership::members(conn, g).await?; + let turn = streamline_domain::assign::assignee_for( + tpl.assignee_user_id.as_deref(), + &tpl.rotation_user_ids.0, + &members, + tpl.rotation_turn.max(0) as u64, + ); + let chosen = match a { + Assignee::FromChore => turn.clone(), + Assignee::Person(p) => p.clone().filter(|p| members.contains(p)), + }; + // Whoever's turn it was took it: the turns move on (not for a routine's own + // assignee: the routine has its own turns). + let own = matches!(a, Assignee::FromChore) || opts.occurrence.is_none(); + let rotating = tpl.rotation_user_ids.0.iter().any(|u| members.contains(u)); + if own && rotating && chosen.is_some() && chosen == turn { + let mut next = tpl.clone(); + next.rotation_turn += 1; + next.updated_at = now(); + next.rev = next_rev(conn).await?; + upsert_workflow(conn, &next).await?; + changes.push(Change::workflow(&next)); + } + chosen + } + }; + let mut tasks = vec![]; for (run_index, (variant, skip)) in runs.iter().enumerate() { let instance = new_id(); let mut prev: Option = None; @@ -93,10 +138,11 @@ pub async fn start( let rev = next_rev(conn).await?; let ts = now(); let last: Option = sqlx::query_scalar( - "SELECT MAX(position) FROM tasks WHERE project_id IS ?1 AND (?1 IS NOT NULL OR owner_user_id = ?2) AND deleted_at IS NULL", + "SELECT MAX(position) FROM tasks WHERE project_id IS ?1 AND (?1 IS NOT NULL OR (owner_user_id IS ?2 AND owner_group_id IS ?3)) AND deleted_at IS NULL", ) .bind(&project_id) - .bind(owner_user_id) + .bind(&owner.user) + .bind(&owner.group) .fetch_one(&mut *conn) .await?; let first = c.number == 1; @@ -104,7 +150,7 @@ pub async fn start( id: new_id(), owner_user_id: owner.user.clone(), owner_group_id: owner.group.clone(), - assignee_user_id: None, + assignee_user_id: assignee.clone(), project_id: project_id.clone(), title: match variant { Some(v) => format!("{} ({v})", c.step.title), @@ -166,24 +212,42 @@ pub async fn start( }; upsert_task(conn, &t).await?; changes.push(Change::task(&t)); - if first && let Some(day) = &opts.day { + // The first step goes on the day of the person doing it: the assignee, else + // whoever started it, else (a shared routine) everyone in the group. + let people = match (first, &opts.day) { + (false, _) | (_, None) => vec![], + _ => match (&assignee, starter) { + (Some(_), _) | (None, None) => { + crate::routines::planners( + conn, + owner.user.as_deref(), + owner.group.as_deref(), + assignee.as_deref(), + ) + .await? + } + (None, Some(u)) => vec![u.to_string()], + }, + }; + for user_id in people { + let day = opts.day.clone().unwrap_or_default(); let last: Option = sqlx::query_scalar( "SELECT MAX(position) FROM day_entries WHERE user_id = ? AND date = ? AND deleted_at IS NULL", ) - .bind(owner_user_id) - .bind(day) + .bind(&user_id) + .bind(&day) .fetch_one(&mut *conn) .await?; let e = DayEntry { id: new_id(), - user_id: owner_user_id.into(), - date: day.clone(), + user_id, + date: day, task_id: t.id.clone(), position: key_after(last.as_deref()), start_time: opts.start_time.clone(), duration_min: None, created_at: ts.clone(), - updated_at: ts, + updated_at: ts.clone(), deleted_at: None, rev, }; diff --git a/crates/server/tests/api.rs b/crates/server/tests/api.rs index 7663c46..c33a691 100644 --- a/crates/server/tests/api.rs +++ b/crates/server/tests/api.rs @@ -2722,6 +2722,623 @@ async fn routine_week_score_and_rescheduling() { ); } +#[tokio::test] +async fn workflows_belong_to_their_project_owner() { + // D-115: a multi-step chore in a shared project is the group's; anyone in it can start it. + let t = setup().await; + let admin = t.admin().await; + let anna = t.user(&admin, "anna").await; + let ben = t.user(&admin, "ben").await; + let cid = t.user(&admin, "cid").await; + let id_of = |v: &Value| v["id"].as_str().unwrap().to_string(); + let (_, me_ben, _) = t.req("GET", "/api/v1/me", Some(&ben), None).await; + let (_, fam, _) = t + .req( + "POST", + "/api/v1/groups", + Some(&anna), + Some(json!({"name": "Family"})), + ) + .await; + let gid = id_of(&fam); + let (s, _, _) = t + .req( + "POST", + &format!("/api/v1/groups/{gid}/members"), + Some(&anna), + Some(json!({"user_id": id_of(&me_ben)})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (_, house, _) = t + .req( + "POST", + "/api/v1/projects", + Some(&anna), + Some(json!({"name": "House"})), + ) + .await; + let house_id = id_of(&house); + let (_, mine, _) = t + .req( + "POST", + "/api/v1/projects", + Some(&anna), + Some(json!({"name": "Mine"})), + ) + .await; + let workflow_names = |v: &Value| -> Vec { + let mut out: Vec = v["workflows"] + .as_array() + .unwrap() + .iter() + .filter(|w| w["deleted_at"].is_null()) + .map(|w| w["name"].as_str().unwrap().to_string()) + .collect(); + out.sort(); + out + }; + + // Made in a personal project: Anna's alone. + let (s, laundry, _) = t + .req( + "POST", + "/api/v1/workflows", + Some(&anna), + Some(json!({"name": "Laundry", "project_id": house_id, + "steps": [{"id": "wash", "title": "Wash"}, {"id": "fold", "title": "Fold"}]})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{laundry}"); + let wid = id_of(&laundry); + assert!(laundry["owner_group_id"].is_null()); + let (_, b, _) = t.req("GET", "/api/v1/sync", Some(&ben), None).await; + assert!(workflow_names(&b).is_empty()); + let (s, _, _) = t + .req( + "POST", + &format!("/api/v1/workflows/{wid}/start"), + Some(&ben), + Some(json!({})), + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + + // A routine in the same project, to check it's shared along (its owner used to stay). + let (s, _, _) = t + .req( + "POST", + "/api/v1/series", + Some(&anna), + Some(json!({"title": "Hoover", "mode": "repeat", "rrule": "FREQ=WEEKLY", "project_id": house_id})), + ) + .await; + assert_eq!(s, StatusCode::OK); + + // Sharing the project shares the chore with it. + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/projects/{house_id}"), + Some(&anna), + Some(json!({"owner_group_id": gid})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (_, b, _) = t.req("GET", "/api/v1/sync", Some(&ben), None).await; + assert_eq!(workflow_names(&b), ["Laundry"]); + assert_eq!(b["workflows"][0]["owner_group_id"], gid); + assert!( + b["series"] + .as_array() + .unwrap() + .iter() + .any(|r| r["title"] == "Hoover" && r["owner_group_id"] == gid), + "routines in the project are shared too" + ); + let (_, c, _) = t.req("GET", "/api/v1/sync", Some(&cid), None).await; + assert!(workflow_names(&c).is_empty(), "non-members don't see it"); + + // Ben starts it; the steps are the group's. + let (s, steps, _) = t + .req( + "POST", + &format!("/api/v1/workflows/{wid}/start"), + Some(&ben), + Some(json!({})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{steps}"); + assert!( + steps + .as_array() + .unwrap() + .iter() + .all(|x| x["owner_group_id"] == gid) + ); + let (s, _, _) = t + .req( + "POST", + &format!("/api/v1/workflows/{wid}/start"), + Some(&cid), + Some(json!({})), + ) + .await; + assert_eq!(s, StatusCode::NOT_FOUND); + + // Made straight in a shared project: the group's from the start. + let (_, bins, _) = t + .req( + "POST", + "/api/v1/workflows", + Some(&ben), + Some(json!({"name": "Bins", "project_id": house_id, + "steps": [{"id": "out", "title": "Out"}, {"id": "in", "title": "In"}]})), + ) + .await; + assert_eq!(bins["owner_group_id"], gid); + assert!(bins["owner_user_id"].is_null()); + + // Moving it to a personal project (or none) makes it that person's. + let (s, moved, _) = t + .req( + "PATCH", + &format!("/api/v1/workflows/{wid}"), + Some(&anna), + Some(json!({"project_id": mine["id"]})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{moved}"); + assert!(moved["owner_group_id"].is_null()); + let (_, b, _) = t.req("GET", "/api/v1/sync", Some(&ben), None).await; + assert_eq!(workflow_names(&b), ["Bins"]); + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/workflows/{}", id_of(&bins)), + Some(&ben), + Some(json!({"project_id": null})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (_, a, _) = t.req("GET", "/api/v1/sync", Some(&anna), None).await; + assert_eq!(workflow_names(&a), ["Laundry"]); + + // Someone else's personal project can't be used. + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/workflows/{}", id_of(&bins)), + Some(&ben), + Some(json!({"project_id": mine["id"]})), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); +} + +#[tokio::test] +async fn household_chores_can_be_assigned() { + // D-116: a shared chore can go to one member, by hand, by default or taking turns. + let t = setup().await; + let admin = t.admin().await; + let anna = t.user(&admin, "anna").await; + let ben = t.user(&admin, "ben").await; + let cid = t.user(&admin, "cid").await; + let id_of = |v: &Value| v["id"].as_str().unwrap().to_string(); + let me = |v: Value| id_of(&v); + let anna_id = me(t.req("GET", "/api/v1/me", Some(&anna), None).await.1); + let ben_id = me(t.req("GET", "/api/v1/me", Some(&ben), None).await.1); + let cid_id = me(t.req("GET", "/api/v1/me", Some(&cid), None).await.1); + let (_, fam, _) = t + .req( + "POST", + "/api/v1/groups", + Some(&anna), + Some(json!({"name": "Family"})), + ) + .await; + let gid = id_of(&fam); + t.req( + "POST", + &format!("/api/v1/groups/{gid}/members"), + Some(&anna), + Some(json!({"user_id": ben_id})), + ) + .await; + let (_, house, _) = t + .req( + "POST", + "/api/v1/projects", + Some(&anna), + Some(json!({"name": "House", "owner_group_id": gid})), + ) + .await; + let house_id = id_of(&house); + let today = today_of(&t, &anna).await; + let tomorrow = today + chrono::Duration::days(1); + + // 13.2: a task by hand. Only people in the group, and only shared tasks. + let (s, bins, _) = t + .req( + "POST", + "/api/v1/tasks", + Some(&anna), + Some(json!({"title": "Bins out", "project_id": house_id, "due_date": ymd(today), "assignee_user_id": ben_id})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{bins}"); + assert_eq!(bins["assignee_user_id"], ben_id); + let bins_id = id_of(&bins); + for (auth, body) in [ + ( + &anna, + json!({"title": "x", "project_id": house_id, "assignee_user_id": cid_id}), + ), + (&anna, json!({"title": "x", "assignee_user_id": anna_id})), + ] { + let (s, _, _) = t + .req("POST", "/api/v1/tasks", Some(auth), Some(body.clone())) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST, "{body}"); + } + // Everyone sees it; it's due on Ben's day only. + let day = |auth: &str| { + let auth = auth.to_string(); + let t = &t; + async move { + let (_, v, _) = t + .req( + "GET", + &format!("/api/v1/days/{}", ymd(today)), + Some(&auth), + None, + ) + .await; + v["tasks"] + .as_array() + .unwrap() + .iter() + .map(|x| x["title"].as_str().unwrap().to_string()) + .collect::>() + } + }; + assert!(day(&ben).await.contains(&"Bins out".to_string())); + assert!(!day(&anna).await.contains(&"Bins out".to_string())); + let (s, v, _) = t + .req( + "GET", + &format!("/api/v1/tasks/{bins_id}"), + Some(&anna), + None, + ) + .await; + assert_eq!(s, StatusCode::OK, "{v}"); + // Back to anyone, and anyone can still complete an assigned one. + let (s, v, _) = t + .req( + "PATCH", + &format!("/api/v1/tasks/{bins_id}"), + Some(&ben), + Some(json!({"assignee_user_id": null})), + ) + .await; + assert_eq!(s, StatusCode::OK); + assert!(v["assignee_user_id"].is_null()); + assert!(day(&anna).await.contains(&"Bins out".to_string())); + + // 13.3: a routine's default assignee; a fixed-time one lands on their timeline only. + let (s, walk, _) = t + .req( + "POST", + "/api/v1/series", + Some(&anna), + Some(json!({"title": "Walk the dog", "mode": "anchored", "rrule": "FREQ=DAILY", "start_time": "07:30", + "project_id": house_id, "assignee_user_id": ben_id})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{walk}"); + let occ = occurrences(&t, &anna, &id_of(&walk)).await; + assert!(!occ.is_empty() && occ.iter().all(|o| o["assignee_user_id"] == ben_id)); + let planned_for = |sync: &Value, task: &str| { + sync["day_entries"] + .as_array() + .unwrap() + .iter() + .any(|e| e["task_id"] == task && e["deleted_at"].is_null()) + }; + let first = id_of(&occ[0]); + let (_, a, _) = t.req("GET", "/api/v1/sync", Some(&anna), None).await; + let (_, b, _) = t.req("GET", "/api/v1/sync", Some(&ben), None).await; + assert!(planned_for(&b, &first) && !planned_for(&a, &first)); + let (s, _, _) = t + .req( + "POST", + "/api/v1/series", + Some(&anna), + Some(json!({"title": "x", "mode": "repeat", "rrule": "FREQ=DAILY", "assignee_user_id": ben_id})), + ) + .await; + assert_eq!( + s, + StatusCode::BAD_REQUEST, + "a personal routine can't be assigned" + ); + + // 13.4: taking turns, one occurrence each, from the routine's first day. + let (s, dishes, _) = t + .req( + "POST", + "/api/v1/series", + Some(&anna), + Some(json!({"title": "Dishes", "mode": "repeat", "rrule": "FREQ=DAILY", "project_id": house_id, + "rotation_user_ids": [anna_id, ben_id]})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{dishes}"); + let turns = |occ: Vec| { + let mut v: Vec<(String, String)> = occ + .iter() + .map(|o| { + ( + o["occurrence_date"].as_str().unwrap().to_string(), + o["assignee_user_id"].as_str().unwrap_or("").to_string(), + ) + }) + .collect(); + v.sort(); + v + }; + assert_eq!( + turns(occurrences(&t, &anna, &id_of(&dishes)).await), + [ + (ymd(today), anna_id.clone()), + (ymd(tomorrow), ben_id.clone()) + ] + ); + // Changing the turns re-assigns the open ones. + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/series/{}", id_of(&dishes)), + Some(&anna), + Some(json!({"rotation_user_ids": [ben_id, anna_id]})), + ) + .await; + assert_eq!(s, StatusCode::OK); + assert_eq!( + turns(occurrences(&t, &anna, &id_of(&dishes)).await), + [ + (ymd(today), ben_id.clone()), + (ymd(tomorrow), anna_id.clone()) + ] + ); + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/series/{}", id_of(&dishes)), + Some(&anna), + Some(json!({"rotation_user_ids": [ben_id, cid_id]})), + ) + .await; + assert_eq!( + s, + StatusCode::BAD_REQUEST, + "only people in the group take turns" + ); + + // Multi-step chores: one person per run, all steps; turns move on per run. + let (s, laundry, _) = t + .req( + "POST", + "/api/v1/workflows", + Some(&anna), + Some(json!({"name": "Laundry", "project_id": house_id, "rotation_user_ids": [ben_id, anna_id], + "steps": [{"id": "wash", "title": "Wash"}, {"id": "fold", "title": "Fold"}]})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{laundry}"); + let wid = id_of(&laundry); + let start = |body: Value| { + let t = &t; + let anna = anna.clone(); + let wid = wid.clone(); + async move { + let (s, v, _) = t + .req( + "POST", + &format!("/api/v1/workflows/{wid}/start"), + Some(&anna), + Some(body), + ) + .await; + assert_eq!(s, StatusCode::OK, "{v}"); + let who: Vec = v + .as_array() + .unwrap() + .iter() + .map(|x| x["assignee_user_id"].clone()) + .collect(); + assert!( + who.windows(2).all(|w| w[0] == w[1]), + "every step to the same person" + ); + who[0].clone() + } + }; + assert_eq!(start(json!({})).await, ben_id); + assert_eq!(start(json!({})).await, anna_id); + assert_eq!(start(json!({"assignee_user_id": null})).await, Value::Null); + assert_eq!( + start(json!({})).await, + ben_id, + "a run for anyone doesn't use a turn" + ); + let (s, _, _) = t + .req( + "POST", + &format!("/api/v1/workflows/{wid}/start"), + Some(&anna), + Some(json!({"assignee_user_id": cid_id})), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); + + // A shared routine that starts a multi-step chore runs it (it used to be skipped), + // for the routine's assignee. + let (s, wash, _) = t + .req( + "POST", + "/api/v1/series", + Some(&ben), + Some(json!({"title": "Laundry", "mode": "repeat", "rrule": "FREQ=DAILY", "project_id": house_id, + "workflow_template_id": wid, "assignee_user_id": anna_id})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{wash}"); + let run = occurrences(&t, &ben, &id_of(&wash)).await; + assert_eq!(run.len(), 2, "{run:?}"); + assert!(run.iter().all(|o| o["status"] == "open" + && o["owner_group_id"] == gid + && o["assignee_user_id"] == anna_id)); + + // A routine and its chore must be shared alike. + let (_, mine, _) = t + .req( + "POST", + "/api/v1/workflows", + Some(&anna), + Some(json!({"name": "Mine", "steps": [{"id": "a", "title": "A"}]})), + ) + .await; + let (s, _, _) = t + .req( + "POST", + "/api/v1/series", + Some(&anna), + Some(json!({"title": "x", "mode": "repeat", "rrule": "FREQ=DAILY", "project_id": house_id, + "workflow_template_id": mine["id"]})), + ) + .await; + assert_eq!(s, StatusCode::BAD_REQUEST); + // A replayed create of a shared chore gets the record (D-79). + let (s, again, _) = t + .req( + "POST", + "/api/v1/workflows", + Some(&ben), + Some(json!({"id": wid, "name": "Laundry", "project_id": house_id, "steps": [{"id": "wash", "title": "Wash"}]})), + ) + .await; + assert_eq!(s, StatusCode::OK, "{again}"); + + // Giving the fixed-time walk to Anna moves it from Ben's timeline to hers. + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/series/{}", id_of(&walk)), + Some(&anna), + Some(json!({"assignee_user_id": anna_id})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (_, a, _) = t.req("GET", "/api/v1/sync", Some(&anna), None).await; + let (_, b, _) = t.req("GET", "/api/v1/sync", Some(&ben), None).await; + assert!(planned_for(&a, &first) && !planned_for(&b, &first)); + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/series/{}", id_of(&walk)), + Some(&anna), + Some(json!({"assignee_user_id": ben_id})), + ) + .await; + assert_eq!(s, StatusCode::OK); + + // Ben leaves: what was his goes back to anyone, and he's out of the turns. + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/tasks/{bins_id}"), + Some(&anna), + Some(json!({"assignee_user_id": ben_id})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (s, _, _) = t + .req( + "DELETE", + &format!("/api/v1/groups/{gid}/members/{ben_id}"), + Some(&ben), + None, + ) + .await; + assert_eq!(s, StatusCode::NO_CONTENT); + let (_, v, _) = t + .req( + "GET", + &format!("/api/v1/tasks/{bins_id}"), + Some(&anna), + None, + ) + .await; + assert!(v["assignee_user_id"].is_null()); + let (_, a, _) = t.req("GET", "/api/v1/sync", Some(&anna), None).await; + let find = |key: &str, id: &str| { + a[key] + .as_array() + .unwrap() + .iter() + .find(|x| x["id"] == id) + .cloned() + .unwrap() + }; + assert!(find("series", &id_of(&walk))["assignee_user_id"].is_null()); + assert_eq!( + find("series", &id_of(&dishes))["rotation_user_ids"], + json!([anna_id]) + ); + assert_eq!( + find("workflows", &wid)["rotation_user_ids"], + json!([anna_id]) + ); + + // Deleting someone does the same. + t.req( + "POST", + &format!("/api/v1/groups/{gid}/members"), + Some(&anna), + Some(json!({"user_id": cid_id})), + ) + .await; + let (s, _, _) = t + .req( + "PATCH", + &format!("/api/v1/tasks/{bins_id}"), + Some(&anna), + Some(json!({"assignee_user_id": cid_id})), + ) + .await; + assert_eq!(s, StatusCode::OK); + let (s, _, _) = t + .req( + "DELETE", + &format!("/api/v1/users/{cid_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(s, StatusCode::NO_CONTENT); + let (_, v, _) = t + .req( + "GET", + &format!("/api/v1/tasks/{bins_id}"), + Some(&anna), + None, + ) + .await; + assert!(v["assignee_user_id"].is_null()); +} + #[tokio::test] async fn routines_start_workflow_runs() { let t = setup().await; diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 8446c87..fe3c87a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -220,6 +220,9 @@ Any of them can be revisited when the chunk that implements it starts. - **D-112 · 2026-10-17 · Goal tree, attachments and rules** (owner request; rules: "more like a goal or a rule for myself", not a habit question): goals get `parent_id` (any number of top-level goals) and `series_ids` (routines). A child has its parent's owner (moving a goal under a shared one shares it); no cycles (`domain::tree`); deleting a goal moves its children up. Progress of a goal is the average of its parts: each child's progress (achieved = 100 %, dropped and rules left out) and its own linked work (milestones, tasks, projects as before, plus each routine as done ÷ (done + missed) over the last four weeks); the manual override still wins. A third kind, **rule** (`kind = 'rule'`: title, notes, `start_date`, optional end `target_date`, status), has no daily question and no progress; rules have their own *Rules* tab and sit in the goal tree under any goal. Goals can also be attached from a task, a project, a routine or a rule. Only newly linked ids are checked, so a deleted linked task no longer blocks edits. Goals, reviews and habit answers are added to the JSON export. *As built:* rules can't have sub-goals (and a goal with sub-goals can't become a rule); the web offers only open outcome goals as parents (the server also allows habits); a habit's progress stays its habit score even with children; rules without a parent show only on the Rules page; "Kept it, end now" ends a rule (status achieved, end today). A sub-goal can't set its own `owner_group_id`; moving re-owns the whole subtree. Goal links follow a routine when a schedule edit splits it into a new version (D-49); ended routines drop out of progress; rules don't make the review due. Roll-up: `domain::goals::roll_up`, routine rate `routines::recent_outcomes` (28 days, across versions, skipped and pending neutral). - **D-113 · 2026-10-18 · Week templates with routines and tasks in blocks** (owner request and choices: "there is a deep work or admin block, but some routines are visible there and can be scheduled"; a visual week editor, several week templates, one-off tasks too, a preview on the Week view): blocks keep their theme; a template block can also hold **items**: routines and one-off tasks. Routines keep their own days: on a day a template sets up, a routine in one of its blocks is planned into that block if it has an occurrence that day (an N-per-week/month routine: one open slot of its current window, if any is left); items are laid one after another from the block's start (by estimate, 30 min if none; what doesn't fit goes on the day's plan without a time). One-off items become a new task in that block each day the template is used (keyed per item and date, so a deleted or moved one isn't made again). As before (D-58), days are set up 8 days ahead and follow template changes until changed by hand; a routine occurrence already planned by the user is left where it is. **Week templates** map Mon–Sun to day templates (or none): one *default*, at most one *alternating* (every other week, counted from its start week) and any number for *date ranges* (a range wins, then alternation, then the default). The existing weekday assignments become the default week template. The **week editor** is a page with 7 columns on an hour grid; every drag has a menu alternative. The **Week view** previews days not yet set up (template blocks and their items, marked as a preview). *As built:* placement is `domain::templates::lay_out` (around timed tasks and busy events); `block_days.placed` records what each day got, so setting a day up again never plans an item twice; items already planned stay where they are when their block moves, and items removed from a template stay on days already set up. Template edits now re-apply to days set up automatically (blocks recreated, new items added), as D-58 describes; days changed by hand stay as they are. The alternating week applies in its start week and every second week after. Overlapping ranges: the first by position wins. `day_templates.weekdays` stays in line with the default week both ways, so older clients keep working. A default week can be deleted or changed to another mode, and then nothing is set up automatically until there's a default again. Routine items point at the routine's current version; one whose routine was deleted is dropped the next time the template's blocks are saved. The preview is computed in the web client (`web/src/lib/weekTemplates.ts`, tested). It shows custom rules and N-per-week routines with a "?", because it doesn't know which flexible slots are already used. - **D-114 · 2026-10-18 · v1.5 security review** (phase gates 11.5 and 12.5): the diff from v1.4 was reviewed for cross-user and group visibility, ownership in the goal tree, SQL binding, the export, sync and live-event audiences, template items and roll-on. Nothing exploitable was found. Checked: a goal can only be put under a goal the user can see, and takes its owner; `check_links` compares against the stored goal, so an unseen id can't pass as "already linked"; progress counts only what the viewer sees; week templates, day templates in them and template items are owner-checked (routine items again when placed); new sync fields and events go to the owner only; the export uses the visibility rule; no new query mixes `?1` with a plain `?`; no user content is rendered as HTML. Noted, not exploitable: the template-task lookup isn't limited to the owner (item ids are personal and never shared). Encryption at rest was discussed and left for later (owner's choice); the server's database files are readable by other accounts on the host (`0644`), unlike the desktop app's (D-92). +- **D-115 · 2026-10-30 · Household multi-step chores** (owner request: "the (multistep) chores to be able to be either under a user or under a project. Household chores are for everybody in the household and should not be in the normal user chores"): a multi-step chore (workflow template) **belongs to its project's owner**, like tasks and routines: no project or a personal project → its creator (or whoever moves it there); a project shared with a group → that group, so every member sees it, can start it, edit it and delete it. Sharing or unsharing a project carries its chores along (`reown_subtree`), and moving a chore to a differently shared project re-owns it (unlike routines, a template has no history to protect; running chains keep their owner). Projects copied from another server can't hold one (D-100 leaves workflow templates out). The Routines page lists your own routines and chores first and each group's under "Shared with ". *Found while building:* `upsert_workflow` never wrote the owner on update; it does now. *Also found:* a group-owned routine that started a multi-step chore was always skipped, since `routines::start_run` needed a single owning user; fixed in 13.4 (D-116). +- **D-116 · 2026-10-30 · Assigning household chores to a member (Q-4, replaces D-4)** (owner choices): a shared task can be **assigned to one member** (`assignee_user_id`, already in the schema). Everyone still sees it with the person's name, and anyone can still complete it, but it only lands in the assignee's Today, ready stack, planner suggestions and reminders; unassigned shared tasks stay up for grabs as now. **Default assignee** on routines (each occurrence) and on multi-step chores (each run; every step of a run goes to the same person, changeable at Start). **Rotation** between chosen members (per occurrence or run) is available but off by default, and is switched on in the routine's or chore's options. Only group members can be assigned; when someone leaves the group, their open assignments are cleared. *As built (13.2–13.4):* migration 0039 adds `assignee_user_id` and `rotation_user_ids` (JSON, in turn order; empty = off) to `series` and `workflow_templates`, plus `rotation_turn` (runs started so far) on templates. Turn order is `domain::assign::assignee_for` (mirrored in `web/src/lib/assign.ts`): people in the rotation who are still in the group take turns, then the default, else nobody. A routine's turn is the occurrence's position among the routine's occurrences from its first day (so it doesn't depend on when occurrences are created); a new version (schedule change) starts again with the first person. Changing a routine's assignee or turns re-assigns its open occurrences from the chosen date on. A multi-step chore's turn moves on only when the run goes to whoever's turn it was (a run for anyone, or for someone picked by hand, leaves it). A routine that starts a chore uses its own assignment if it has one, else the chore's. Assigned tasks are left out of other members' ready stack, Today (due, window, ongoing), planner, weekly review loose ends, morning digest, the day API's due list and week-template placement; a fixed-time chore is put only on its assignee's timeline, and the first step of a run on the assignee's day (else the starter's; for a shared routine without an assignee, everyone's). Moving something to a differently shared owner keeps only assignees still in the new group. People on other servers who joined a shared project (D-100) can be assigned too. A group with multi-step chores can't be deleted, like one with routines. *Also found:* `upsert_series` never wrote the owner on update, so sharing a project left its routines with their creator; fixed, and migration 0039 re-owns existing routines and multi-step chores to their project's owner (projects copied from another server excepted). +- **D-117 · 2026-10-30 · Phase 13 security review** (phase gate 13.5): an independent review of the Phase 13 diff found no SQL binding mistakes and no cross-group visibility leaks; these were fixed: (1) a routine could start a multi-step chore owned by someone else (a group routine copying a member's private steps, or a personal routine following a group's chore after leaving it): a routine's chore must now have the same owner, checked on save and again at each run (else the occurrence is skipped with a note); (2) deleted users stayed assignable and in turns: they no longer count as members for assignment, and deleting a user clears their assignments like leaving a group; (3) rotation stopped turning after 1000 occurrences (the recurrence query's cap): turns are now counted a year at a time (`domain::assign::turn_of`, tested); (4) a routine's own assignee moved its chore's turns: only the chore's own runs do; (5) changing a fixed-time routine's assignee only removed others' entries: entries now move to the new assignee (or everyone), and other routines' hand-made plans are left alone; (6) a replayed create of a shared multi-step chore was refused: it now returns the record, like routines. Left as is: assignments arriving in another server's feed are only filtered when used (D-100 copies aren't assigned on the replica); reassigning a task by hand leaves day plans as they are (a plan is the planner's own choice). ## Resource log @@ -239,5 +242,6 @@ Any of them can be revisited when the chunk that implements it starts. | End of Phase 9 (v1.3) | 15.0 MB | 7.8 MiB (fresh container, 20 s) | 97.9 KB initial | not re-measured | 2026-10-14 | | End of v1.4 (Phases 10, 7.3/7.6/7.7, 8) | 16.2 MB | 9.0 MiB (fresh container, 20 s) | 110.4 KB initial | not re-measured | 2026-10-15 | | End of v1.5 (Phases 11, 12) | 16.7 MB | 9.4 MiB (fresh container, 20 s) | 117.7 KB initial | not re-measured | 2026-10-18 | +| Phase 13 (household chores) | not measured | not measured | 119.6 KB initial | not re-measured | 2026-10-30 | Desktop app (Linux, release build, signed in to a server, idle on Today for 45 s, 2026-10-14): **294 MiB PSS** in total: the app process 91, WebKit's web process 170, its network process 33. RSS adds up to 548 MiB but counts shared libraries once per process. Most of it is the web engine itself. diff --git a/docs/WORKPLAN.md b/docs/WORKPLAN.md index 9a4d949..f6d50f9 100644 --- a/docs/WORKPLAN.md +++ b/docs/WORKPLAN.md @@ -813,6 +813,38 @@ Owner request of 2026-10-18. On the `v1.5` branch, after Phase 11. Migration 003 --- +### Phase 13: Household chores and assignment (D-115, D-116) + +Owner request of 2026-10-30. Next version not planned yet. + +- [x] **13.1 Household multi-step chores** (D-115): a workflow template belongs to its + project's owner (on create, on moving it, and when its project is shared or unshared); + group members sync, see, start and edit it; refused for projects copied from another + server; the Routines page lists yours first and each group's under "Shared with …"; + server test; help and CHANGELOG. +- [x] **13.2 Assign a task to a member** (D-116): `assignee_user_id` settable on shared + tasks (members of the owning group only; cleared when they leave); the name shows on + the task everywhere; assigned tasks only appear in the assignee's Today, ready stack, + planner and reminders; visibility tests stay green; client store and task sheet. +- [x] **13.3 Default assignee on routines and multi-step chores** (D-116): routines give + each occurrence their default assignee; multi-step chores give every step of a run the + same person, chosen at Start (defaulting to the chore's); routine and chore sheets. +- [x] **13.4 Rotation, and shared routines that start chores** (D-116, D-115): optional + rotation between chosen members per occurrence or run (off by default, switched on in + the routine's or chore's options; pure turn order in `domain` with tests); fix + group-owned routines with a multi-step chore, which are skipped today. +- [x] **13.5 Phase gate**: Part D checklist, including a security review of assignment. + *Done 2026-10-30:* fmt, clippy, all tests (server, domain, web) green; TS types + regenerated; docs site builds with `--strict`; web payload 119.6 KB initial; the new + screens tried in the real app (headless Chromium, scratch data: Routines page split, + Start with whose turn it is, turns in the routine sheet, assignee on tasks, an + assigned task left out of the others' Today); security review done and fixed (D-117). + *Left for the owner:* image size and idle memory (`make measure`, needs a Docker + build), the phone and HTTPS smoke test, a look on a phone, push so CI runs, and the + release. + +--- + ## Part C. Open questions with proposed defaults > **Status: all defaults below accepted by the owner on 2026-10-05** (recorded as D-1…D-23 @@ -827,7 +859,7 @@ column says when it must be settled. | Q-1 | Default task types; custom types in v1? | One-off → `carry_on`; anchored routine → `expires`; flexible routine → `window`; tasks with due date may opt into `deadline`; workflow steps inherit from the template (default `carry_on`). Users **can** create custom types in v1, since types are just config. | 2.3 | | Q-2 | Day-end rollover | Configurable per user, **default 04:00**. | 2.1 | | Q-3 | Flexible routine window | **Fixed calendar periods** (ISO week with configurable week start; calendar month), not rolling. Easier to reason about and to show as "1 of 2 this week". | 3.4 | -| Q-4 | Assign to a member within a group | Not in v1. The schema keeps a nullable `assignee_user_id` so it can be added later without a migration. | 4.2 | +| Q-4 | Assign to a member within a group | Not in v1. The schema keeps a nullable `assignee_user_id` so it can be added later without a migration. **Answered later (D-116):** yes, with a default assignee and optional turns; built in Phase 13. | 4.2 | | Q-5 | Reminders on HTTP-only | In-app (SSE banner/toast) always; **optional ntfy** backend in Phase 6; Web Push when HTTPS is available. | 2a.3 | | Q-6 | Prerequisite skipped or deleted | **Auto-unblock**, with a visible note on the dependent task ("prerequisite X was skipped"). `wont_do` counts the same as skipped. | 3b.1 | | Q-7 | Routine spawns a workflow while the previous instance is unfinished | **Don't spawn**; log the occurrence as skipped ("previous run still open"). Can be changed per routine. | 3b.6 | diff --git a/docs/features.md b/docs/features.md index 75ec1bd..5d5a8b8 100644 --- a/docs/features.md +++ b/docs/features.md @@ -71,7 +71,9 @@ Everything below is in the app today. *Help* inside the app explains each one st ## Household - **Groups**: share projects, tasks, routines and goals with a group; anyone can complete a - shared chore (who did is shown), and changes appear live for everyone. Day plans, focus time, + shared chore (who did is shown), and changes appear live for everyone. Multi-step chores in a + shared project belong to the household, and anyone in it can start them. Give a chore to + one person, or let people take turns; it then shows up only on that person's day. Day plans, focus time, journals and logs stay personal. - **Namedays and birthdays**: a shared nameday calendar (the official Estonian list by default); everyone picks their own people and gets tasks like "buy a present" → "wish a happy diff --git a/migrations/0039_assignment.sql b/migrations/0039_assignment.sql new file mode 100644 index 0000000..f58893a --- /dev/null +++ b/migrations/0039_assignment.sql @@ -0,0 +1,36 @@ +-- Assigning household chores to a member (D-116). `tasks.assignee_user_id` exists since +-- the start (Q-4); routines and multi-step chores get a default assignee and an optional +-- rotation: `rotation_user_ids` is a JSON array of user ids taking turns (empty = off). +ALTER TABLE series ADD COLUMN assignee_user_id TEXT; +ALTER TABLE series ADD COLUMN rotation_user_ids TEXT NOT NULL DEFAULT '[]'; + +-- Multi-step chores take turns per run: `rotation_turn` counts the runs started so far. +ALTER TABLE workflow_templates ADD COLUMN assignee_user_id TEXT; +ALTER TABLE workflow_templates ADD COLUMN rotation_user_ids TEXT NOT NULL DEFAULT '[]'; +ALTER TABLE workflow_templates ADD COLUMN rotation_turn INTEGER NOT NULL DEFAULT 0; + +CREATE INDEX tasks_assignee ON tasks (assignee_user_id) WHERE assignee_user_id IS NOT NULL; + +-- Things in a project belong to its owner (D-115). Multi-step chores never followed their +-- project, and routines didn't when a project was shared after they were made (the owner +-- wasn't written on update): put them right, with a new revision so clients pick them up. +-- Projects copied from another server are left alone (their groups are mirrors). +UPDATE meta_rev SET rev = rev + 1 WHERE id = 1; +UPDATE workflow_templates + SET owner_user_id = (SELECT p.owner_user_id FROM projects p WHERE p.id = workflow_templates.project_id), + owner_group_id = (SELECT p.owner_group_id FROM projects p WHERE p.id = workflow_templates.project_id), + rev = (SELECT rev FROM meta_rev WHERE id = 1) + WHERE deleted_at IS NULL + AND project_id IN (SELECT p.id FROM projects p LEFT JOIN groups g ON g.id = p.owner_group_id + WHERE p.deleted_at IS NULL AND g.home IS NULL) + AND (owner_user_id IS NOT (SELECT p.owner_user_id FROM projects p WHERE p.id = workflow_templates.project_id) + OR owner_group_id IS NOT (SELECT p.owner_group_id FROM projects p WHERE p.id = workflow_templates.project_id)); +UPDATE series + SET owner_user_id = (SELECT p.owner_user_id FROM projects p WHERE p.id = series.project_id), + owner_group_id = (SELECT p.owner_group_id FROM projects p WHERE p.id = series.project_id), + rev = (SELECT rev FROM meta_rev WHERE id = 1) + WHERE deleted_at IS NULL + AND project_id IN (SELECT p.id FROM projects p LEFT JOIN groups g ON g.id = p.owner_group_id + WHERE p.deleted_at IS NULL AND g.home IS NULL) + AND (owner_user_id IS NOT (SELECT p.owner_user_id FROM projects p WHERE p.id = series.project_id) + OR owner_group_id IS NOT (SELECT p.owner_group_id FROM projects p WHERE p.id = series.project_id)); diff --git a/web/src/lib/api/types/Series.ts b/web/src/lib/api/types/Series.ts index 5560b2e..a785bb2 100644 --- a/web/src/lib/api/types/Series.ts +++ b/web/src/lib/api/types/Series.ts @@ -41,6 +41,15 @@ workflow_template_id: string | null, workflow_variant_ids: Array, * Checklist each occurrence starts with, unticked (D-71). */ checklist: Array, +/** + * Who each occurrence of a shared routine goes to by default (D-116). (Defaults keep + * feeds from servers before 1.6 readable, Phase 8.) + */ +assignee_user_id: string | null, +/** + * Members taking turns, one occurrence each (empty = no rotation; D-116). + */ +rotation_user_ids: Array, /** * The routine this one replaced when its schedule changed (progress and streaks * continue across versions). diff --git a/web/src/lib/api/types/WorkflowTemplate.ts b/web/src/lib/api/types/WorkflowTemplate.ts index 3e47e9a..f42caa2 100644 --- a/web/src/lib/api/types/WorkflowTemplate.ts +++ b/web/src/lib/api/types/WorkflowTemplate.ts @@ -9,4 +9,17 @@ export type WorkflowTemplate = { id: string, owner_user_id: string | null, owner /** * Project the steps go into (optional). */ -project_id: string | null, steps: Array, variants: Array, created_at: string, updated_at: string, deleted_at: string | null, rev: number, }; +project_id: string | null, steps: Array, variants: Array, +/** + * Who each run goes to by default in a shared chore (D-116); every step of a run goes + * to the same person. + */ +assignee_user_id: string | null, +/** + * Members taking turns, one run each (empty = no rotation; D-116). + */ +rotation_user_ids: Array, +/** + * Runs started so far: the next one goes to the member at this turn. + */ +rotation_turn: number, created_at: string, updated_at: string, deleted_at: string | null, rev: number, }; diff --git a/web/src/lib/assign.test.ts b/web/src/lib/assign.test.ts new file mode 100644 index 0000000..4a6832d --- /dev/null +++ b/web/src/lib/assign.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { assigneeFor, isForMe } from './assign' + +describe('assignment (D-116)', () => { + const members = ['anna', 'ben', 'cid'] + it('uses the default while they are in the group', () => { + expect(assigneeFor('ben', [], members, 3)).toBe('ben') + expect(assigneeFor('zed', [], members, 0)).toBeNull() + expect(assigneeFor(null, [], members, 0)).toBeNull() + }) + it('takes turns in order, skipping people who left', () => { + expect([0, 1, 2, 3].map((n) => assigneeFor(null, ['ben', 'anna'], members, n))).toEqual(['ben', 'anna', 'ben', 'anna']) + expect([0, 1, 2].map((n) => assigneeFor(null, ['anna', 'zed', 'cid'], members, n))).toEqual(['anna', 'cid', 'anna']) + expect(assigneeFor('anna', ['zed'], members, 1)).toBe('anna') + }) + it('keeps unassigned and own tasks in my lists only', () => { + expect(isForMe(null, 'anna')).toBe(true) + expect(isForMe('anna', 'anna')).toBe(true) + expect(isForMe('ben', 'anna')).toBe(false) + }) +}) diff --git a/web/src/lib/assign.ts b/web/src/lib/assign.ts new file mode 100644 index 0000000..f40f916 --- /dev/null +++ b/web/src/lib/assign.ts @@ -0,0 +1,17 @@ +// Who does a shared chore (D-116): its default assignee, or members taking turns. +// Mirrors `crates/domain/src/assign.rs`. + +/** + * The person for the `turn`th occurrence or run (from 0): with a rotation, the people in it + * still in the group take turns in order; otherwise the default, while they're in the group. + */ +export function assigneeFor(fallback: string | null, rotation: string[], members: string[], turn: number): string | null { + const turns = rotation.filter((u) => members.includes(u)) + if (turns.length) return turns[turn % turns.length] + return fallback && members.includes(fallback) ? fallback : null +} + +/** Whether a task belongs in my lists: it's for anyone, or for me. */ +export function isForMe(assignee: string | null, me: string | null | undefined): boolean { + return !assignee || assignee === me +} diff --git a/web/src/lib/components/AssignPicker.svelte b/web/src/lib/components/AssignPicker.svelte new file mode 100644 index 0000000..d98cab1 --- /dev/null +++ b/web/src/lib/components/AssignPicker.svelte @@ -0,0 +1,113 @@ + + +
+

Who does it

+ {#if !rotating} + +

+ {assignee ? `Everyone sees it, but it's on ${name(assignee)}'s day and lists only. Anyone can still tick it off.` : 'Up for grabs: it shows up for everyone.'} +

+ {/if} + {#if turns && members.length > 1} + + {#if rotating} +
+ {#each members as m (m.user_id)} + {@const n = rotation.indexOf(m.user_id)} + + {/each} +
+

+ One {each} each, in this order: {rotation.map(name).join(' → ') || 'pick who takes part'}. Tap to leave someone out or add them at the end. +

+ {/if} + {/if} +
+ + diff --git a/web/src/lib/components/RoutineSheet.svelte b/web/src/lib/components/RoutineSheet.svelte index b16f850..adcee86 100644 --- a/web/src/lib/components/RoutineSheet.svelte +++ b/web/src/lib/components/RoutineSheet.svelte @@ -11,6 +11,7 @@ import Icon from './Icon.svelte' import Sheet from './Sheet.svelte' import GoalLinks from './GoalLinks.svelte' + import AssignPicker from './AssignPicker.svelte' let { id }: { id: string } = $props() const existing = untrack(() => (id === 'new' ? null : (store.series.get(id) ?? null))) @@ -27,6 +28,10 @@ let projectId = $state(existing?.project_id ?? '') let placeId = $state(existing?.place_id ?? '') let groupId = $state(existing?.owner_group_id ?? '') + let assignee = $state(existing?.assignee_user_id ?? '') + let rotation = $state(existing ? [...existing.rotation_user_ids] : []) + // A shared routine (through its project, or on its own) can go to someone (D-116). + const sharedWith = $derived(projectId ? (store.projects.get(projectId)?.owner_group_id ?? '') : (existing?.owner_group_id ?? groupId)) let workflowId = $state(existing?.workflow_template_id ?? '') let variantIds = $state(existing ? [...existing.workflow_variant_ids] : []) const workflow = $derived(workflowId ? store.workflows.get(workflowId) : null) @@ -109,6 +114,8 @@ difficulty, checklist: workflowId ? [] : checklist, until: until || null, + assignee_user_id: sharedWith && !rotation.length ? assignee || null : null, + rotation_user_ids: sharedWith ? rotation : [], } const ok = existing ? await store.updateSeries(existing.id, { ...body, from }) @@ -246,6 +253,10 @@ {/if} + {#if sharedWith} + + {/if} + {#if store.workflows.size && mode !== 'flexible'}

Each time

diff --git a/web/src/lib/components/StartWorkflowSheet.svelte b/web/src/lib/components/StartWorkflowSheet.svelte index 1d43655..cce994b 100644 --- a/web/src/lib/components/StartWorkflowSheet.svelte +++ b/web/src/lib/components/StartWorkflowSheet.svelte @@ -1,9 +1,12 @@