Core: authz, clock, member/session/board/task/comment/activity store
Browse files at this commit76964b1144553e7dc1caf7564095174f6ad02613Parent: 92956ed- feat
- core: authz, clock, member/session/board/task/comment/activity store
11 changed files +3884 -2
- crates/iz-core/src/authz.rs +244 -0
- crates/iz-core/src/board.rs +24 -0
- crates/iz-core/src/clock.rs +160 -0
- crates/iz-core/src/lib.rs +2 -0
- crates/iz-core/src/store/activity.rs +174 -0
- crates/iz-core/src/store/board.rs +625 -0
- crates/iz-core/src/store/comments.rs +333 -0
- crates/iz-core/src/store/members.rs +412 -0
- crates/iz-core/src/store/mod.rs +80 -2
- crates/iz-core/src/store/sessions.rs +245 -0
- crates/iz-core/src/store/tasks.rs +1585 -0
crates/iz-core/src/authz.rsadded+244 -0
| @@ -0,0 +1,244 @@ | ||
| 1 | +//! Authorization (docs/architecture.md section 6). One pure function decides what an actor may do: | |
| 2 | +//! every page, form handler, API route and live stream calls [`authorize`] before it reads or writes. | |
| 3 | +//! A denial is `NotFound` when the viewer must not learn that the thing exists, and `Forbidden` | |
| 4 | +//! when the viewer may know it but may not act on it. | |
| 5 | +//! | |
| 6 | +//! Levels: admin contains member, member contains viewer. `im_admin` acts as admin. A disabled | |
| 7 | +//! account and role `none` are denied everything with `NotFound`. An anonymous actor is `Forbidden`, | |
| 8 | +//! so the caller can show the sign-in card. The store repeats the disabled and `none` checks in its | |
| 9 | +//! own queries (sessions, assignments), so a denied member cannot reach data through another path. | |
| 10 | + | |
| 11 | +use crate::error::Error; | |
| 12 | + | |
| 13 | +/// A member's stored role (`members.role`). Matches the CHECK constraint in the schema. | |
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 15 | +pub enum Role { | |
| 16 | + /// Full control of the board, including settings, tags, columns and roles. | |
| 17 | + Admin, | |
| 18 | + /// Reads and writes tasks, comments and files, and may be assigned. | |
| 19 | + Member, | |
| 20 | + /// Reads the board only. Never assigned, never mailed. | |
| 21 | + Viewer, | |
| 22 | + /// In the directory but with no access (stored as `none`). | |
| 23 | + NoAccess, | |
| 24 | +} | |
| 25 | + | |
| 26 | +impl Role { | |
| 27 | + /// The stored spelling of the role. | |
| 28 | + pub fn as_str(self) -> &'static str { | |
| 29 | + match self { | |
| 30 | + Role::Admin => "admin", | |
| 31 | + Role::Member => "member", | |
| 32 | + Role::Viewer => "viewer", | |
| 33 | + Role::NoAccess => "none", | |
| 34 | + } | |
| 35 | + } | |
| 36 | + | |
| 37 | + /// Parses the stored spelling. Unknown text is `None`, so a corrupt row is never read as a role. | |
| 38 | + pub fn parse(text: &str) -> Option<Role> { | |
| 39 | + match text { | |
| 40 | + "admin" => Some(Role::Admin), | |
| 41 | + "member" => Some(Role::Member), | |
| 42 | + "viewer" => Some(Role::Viewer), | |
| 43 | + "none" => Some(Role::NoAccess), | |
| 44 | + _ => None, | |
| 45 | + } | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +/// Who is asking. Built by the web layer from the session, never from request input. | |
| 50 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 51 | +pub enum Actor { | |
| 52 | + /// No session. | |
| 53 | + Anonymous, | |
| 54 | + /// A signed-in member, with the flags read from the members row. | |
| 55 | + Member { | |
| 56 | + /// The member's stable id (the OIDC `sub`). | |
| 57 | + sub: String, | |
| 58 | + /// The stored role. | |
| 59 | + role: Role, | |
| 60 | + /// Whether the directory marks the member as an administrator. | |
| 61 | + im_admin: bool, | |
| 62 | + /// Whether the account is disabled. | |
| 63 | + disabled: bool, | |
| 64 | + }, | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// What the actor wants to do. Actions that depend on ownership carry the owner's id. | |
| 68 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 69 | +pub enum Action { | |
| 70 | + /// Read the board, its tasks and their activity. | |
| 71 | + ReadBoard, | |
| 72 | + /// Read a person's card (same board only; the caller scopes the query). | |
| 73 | + ViewPerson, | |
| 74 | + /// Create, edit, move, assign, link or delete tasks. | |
| 75 | + WriteTask, | |
| 76 | + /// Post a comment. | |
| 77 | + Comment, | |
| 78 | + /// Edit a comment. Only its author may, and only while still a member. | |
| 79 | + EditComment { | |
| 80 | + /// Author of the comment. | |
| 81 | + author: String, | |
| 82 | + }, | |
| 83 | + /// Delete a comment: its author while still a member, or any admin. | |
| 84 | + DeleteComment { | |
| 85 | + /// Author of the comment. | |
| 86 | + author: String, | |
| 87 | + }, | |
| 88 | + /// Attach a file. | |
| 89 | + UploadFile, | |
| 90 | + /// Delete a file: its uploader while still a member, or any admin. | |
| 91 | + DeleteFile { | |
| 92 | + /// Uploader of the file. | |
| 93 | + uploader: String, | |
| 94 | + }, | |
| 95 | + /// Manage settings, tags, columns, roles and mail rules. | |
| 96 | + Administer, | |
| 97 | +} | |
| 98 | + | |
| 99 | +/// Why an action was refused. | |
| 100 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 101 | +pub enum Denied { | |
| 102 | + /// The viewer may not know that the resource exists. Answer as if it were missing. | |
| 103 | + NotFound, | |
| 104 | + /// The viewer may know the resource but may not do this. | |
| 105 | + Forbidden, | |
| 106 | +} | |
| 107 | + | |
| 108 | +impl From<Denied> for Error { | |
| 109 | + fn from(denied: Denied) -> Error { | |
| 110 | + match denied { | |
| 111 | + Denied::NotFound => Error::NotFound, | |
| 112 | + Denied::Forbidden => { | |
| 113 | + Error::Forbidden("this action is not allowed for your account".into()) | |
| 114 | + } | |
| 115 | + } | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +/// Ordered levels. A larger level includes every permission of the smaller ones. | |
| 120 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] | |
| 121 | +enum Level { | |
| 122 | + Viewer, | |
| 123 | + Member, | |
| 124 | + Admin, | |
| 125 | +} | |
| 126 | + | |
| 127 | +/// Decides whether `actor` may perform `action`. Pure: no I/O, no clock. | |
| 128 | +pub fn authorize(actor: &Actor, action: &Action) -> Result<(), Denied> { | |
| 129 | + let (sub, level) = match actor { | |
| 130 | + Actor::Anonymous => return Err(Denied::Forbidden), | |
| 131 | + Actor::Member { disabled: true, .. } => return Err(Denied::NotFound), | |
| 132 | + Actor::Member { | |
| 133 | + sub, | |
| 134 | + im_admin: true, | |
| 135 | + .. | |
| 136 | + } => (sub.as_str(), Level::Admin), | |
| 137 | + Actor::Member { sub, role, .. } => { | |
| 138 | + let level = match role { | |
| 139 | + Role::Admin => Level::Admin, | |
| 140 | + Role::Member => Level::Member, | |
| 141 | + Role::Viewer => Level::Viewer, | |
| 142 | + Role::NoAccess => return Err(Denied::NotFound), | |
| 143 | + }; | |
| 144 | + (sub.as_str(), level) | |
| 145 | + } | |
| 146 | + }; | |
| 147 | + let allowed = match action { | |
| 148 | + Action::ReadBoard | Action::ViewPerson => level >= Level::Viewer, | |
| 149 | + Action::WriteTask | Action::Comment | Action::UploadFile => level >= Level::Member, | |
| 150 | + Action::EditComment { author } => level >= Level::Member && sub == author, | |
| 151 | + Action::DeleteComment { author } => { | |
| 152 | + level == Level::Admin || (level >= Level::Member && sub == author) | |
| 153 | + } | |
| 154 | + Action::DeleteFile { uploader } => { | |
| 155 | + level == Level::Admin || (level >= Level::Member && sub == uploader) | |
| 156 | + } | |
| 157 | + Action::Administer => level == Level::Admin, | |
| 158 | + }; | |
| 159 | + if allowed { | |
| 160 | + Ok(()) | |
| 161 | + } else { | |
| 162 | + Err(Denied::Forbidden) | |
| 163 | + } | |
| 164 | +} | |
| 165 | + | |
| 166 | +#[cfg(test)] | |
| 167 | +mod tests { | |
| 168 | + use super::*; | |
| 169 | + | |
| 170 | + fn member(sub: &str, role: Role, im_admin: bool, disabled: bool) -> Actor { | |
| 171 | + Actor::Member { | |
| 172 | + sub: sub.into(), | |
| 173 | + role, | |
| 174 | + im_admin, | |
| 175 | + disabled, | |
| 176 | + } | |
| 177 | + } | |
| 178 | + | |
| 179 | + /// The truth table: each row is one actor and the result for each action, in this order: | |
| 180 | + /// read, write, comment, edit own comment `ada`, delete `ada`'s comment, upload, delete `ada`'s | |
| 181 | + /// file, administer. | |
| 182 | + #[test] | |
| 183 | + fn truth_table() { | |
| 184 | + use Denied::{Forbidden as F, NotFound as N}; | |
| 185 | + let ok = Ok(()); | |
| 186 | + let edit_ada = Action::EditComment { | |
| 187 | + author: "ada".into(), | |
| 188 | + }; | |
| 189 | + let del_ada = Action::DeleteComment { | |
| 190 | + author: "ada".into(), | |
| 191 | + }; | |
| 192 | + let file_ada = Action::DeleteFile { | |
| 193 | + uploader: "ada".into(), | |
| 194 | + }; | |
| 195 | + let rows: Vec<(Actor, [Result<(), Denied>; 8])> = vec![ | |
| 196 | + (Actor::Anonymous, [Err(F); 8]), | |
| 197 | + ( | |
| 198 | + member("ada", Role::Admin, false, false), | |
| 199 | + [ok, ok, ok, ok, ok, ok, ok, ok], | |
| 200 | + ), | |
| 201 | + ( | |
| 202 | + member("ada", Role::Member, false, false), | |
| 203 | + [ok, ok, ok, ok, ok, ok, ok, Err(F)], | |
| 204 | + ), | |
| 205 | + ( | |
| 206 | + member("bo", Role::Member, false, false), | |
| 207 | + [ok, ok, ok, Err(F), Err(F), ok, Err(F), Err(F)], | |
| 208 | + ), | |
| 209 | + ( | |
| 210 | + member("bo", Role::Viewer, false, false), | |
| 211 | + [ok, Err(F), Err(F), Err(F), Err(F), Err(F), Err(F), Err(F)], | |
| 212 | + ), | |
| 213 | + ( | |
| 214 | + member("bo", Role::Member, true, false), | |
| 215 | + [ok, ok, ok, Err(F), ok, ok, ok, ok], | |
| 216 | + ), | |
| 217 | + (member("ada", Role::NoAccess, false, false), [Err(N); 8]), | |
| 218 | + (member("ada", Role::Admin, false, true), [Err(N); 8]), | |
| 219 | + ]; | |
| 220 | + let actions = [ | |
| 221 | + Action::ReadBoard, | |
| 222 | + Action::WriteTask, | |
| 223 | + Action::Comment, | |
| 224 | + edit_ada, | |
| 225 | + del_ada, | |
| 226 | + Action::UploadFile, | |
| 227 | + file_ada, | |
| 228 | + Action::Administer, | |
| 229 | + ]; | |
| 230 | + for (actor, expected) in rows { | |
| 231 | + for (action, want) in actions.iter().zip(expected) { | |
| 232 | + assert_eq!(authorize(&actor, action), want, "{actor:?} {action:?}"); | |
| 233 | + } | |
| 234 | + } | |
| 235 | + } | |
| 236 | + | |
| 237 | + #[test] | |
| 238 | + fn role_spelling_round_trips() { | |
| 239 | + for role in [Role::Admin, Role::Member, Role::Viewer, Role::NoAccess] { | |
| 240 | + assert_eq!(Role::parse(role.as_str()), Some(role)); | |
| 241 | + } | |
| 242 | + assert_eq!(Role::parse("owner"), None); | |
| 243 | + } | |
| 244 | +} |
crates/iz-core/src/board.rsmodified+24 -0
| @@ -76,6 +76,20 @@ pub fn position_between(before: Option<f64>, after: Option<f64>) -> f64 { | ||
| 76 | 76 | } |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | +/// Folds text for case-insensitive search. Turkish letters are folded the way a Turkish reader | |
| 80 | +/// expects: `I`, `ı`, `İ` and `i` all match each other, so a search for `istanbul` finds `İSTANBUL` | |
| 81 | +/// and `ISTANBUL` finds `istanbul`. Every other letter uses Unicode lowercasing. | |
| 82 | +pub fn fold_for_search(text: &str) -> String { | |
| 83 | + let mut out = String::with_capacity(text.len()); | |
| 84 | + for c in text.chars() { | |
| 85 | + match c { | |
| 86 | + 'I' | 'İ' | 'ı' | 'i' => out.push('i'), | |
| 87 | + other => out.extend(other.to_lowercase()), | |
| 88 | + } | |
| 89 | + } | |
| 90 | + out | |
| 91 | +} | |
| 92 | + | |
| 79 | 93 | /// A task key: `PREFIX-n`, for example `IZ-42`. The counter `n` comes from the board row. |
| 80 | 94 | pub fn format_key(prefix: &str, n: u64) -> String { |
| 81 | 95 | format!("{prefix}-{n}") |
| @@ -144,6 +158,16 @@ mod tests { | ||
| 144 | 158 | assert!(!would_cycle(&[(1, 2)], (4, 2))); |
| 145 | 159 | } |
| 146 | 160 | |
| 161 | + #[test] | |
| 162 | + fn search_folds_turkish_dotted_and_dotless_i() { | |
| 163 | + let target = fold_for_search("İSTANBUL Şişli"); | |
| 164 | + assert!(target.contains(&fold_for_search("istanbul"))); | |
| 165 | + assert!(target.contains(&fold_for_search("ıstanbul"))); | |
| 166 | + assert!(target.contains(&fold_for_search("ISTANBUL"))); | |
| 167 | + assert!(target.contains(&fold_for_search("şişli"))); | |
| 168 | + assert!(!target.contains(&fold_for_search("ankara"))); | |
| 169 | + } | |
| 170 | + | |
| 147 | 171 | #[test] |
| 148 | 172 | fn positions_and_keys() { |
| 149 | 173 | assert_eq!(position_between(None, None), 1.0); |
crates/iz-core/src/clock.rsadded+160 -0
| @@ -0,0 +1,160 @@ | ||
| 1 | +//! Deadline and meeting-time rules (docs/reference/old-inventory.md 2.4), on real IANA zones through | |
| 2 | +//! `zones.rs`. A task has a deadline day, a meeting instant, or both. The user types a day and an | |
| 3 | +//! optional `HH:MM` in their own zone; this module turns that into the values the store keeps. | |
| 4 | +//! | |
| 5 | +//! Rules: a time needs a day; hour and minute are both given or neither; a meeting sets the deadline | |
| 6 | +//! day to the meeting's local day. A local time that does not exist (DST gap) or happens twice | |
| 7 | +//! (DST overlap) is refused, because the user has to choose. | |
| 8 | + | |
| 9 | +use jiff::civil::Date; | |
| 10 | +use jiff::tz::TimeZone; | |
| 11 | +use jiff::{SignedDuration, Timestamp}; | |
| 12 | +use time::OffsetDateTime; | |
| 13 | + | |
| 14 | +use crate::error::{Error, Result}; | |
| 15 | +use crate::time::format_stamp; | |
| 16 | +use crate::zones::{local_to_utc, utc_to_local}; | |
| 17 | + | |
| 18 | +/// How long before a meeting its reminder is due, in minutes. A default; the `reminder_minutes` | |
| 19 | +/// setting replaces it once the setting exists. | |
| 20 | +pub const REMINDER_LEAD_MINUTES: i64 = 15; | |
| 21 | + | |
| 22 | +/// What the user typed for a deadline and meeting time. Every part is optional. | |
| 23 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | |
| 24 | +pub struct MeetingInput { | |
| 25 | + /// The day (a deadline, or the day of the meeting). | |
| 26 | + pub day: Option<Date>, | |
| 27 | + /// Hour of the meeting in the user's zone, 0 to 23. | |
| 28 | + pub hour: Option<u8>, | |
| 29 | + /// Minute of the meeting in the user's zone, 0 to 59. | |
| 30 | + pub minute: Option<u8>, | |
| 31 | +} | |
| 32 | + | |
| 33 | +/// Validates the input and resolves it to the stored values: the deadline day and the meeting as a | |
| 34 | +/// UTC stamp (the fixed-width format of `time::format_stamp`). Errors are `Invalid` and name the rule. | |
| 35 | +pub fn resolve_meeting( | |
| 36 | + input: MeetingInput, | |
| 37 | + zone: &TimeZone, | |
| 38 | +) -> Result<(Option<Date>, Option<String>)> { | |
| 39 | + match (input.day, input.hour, input.minute) { | |
| 40 | + (day, None, None) => Ok((day, None)), | |
| 41 | + (None, _, _) => Err(Error::Invalid("a meeting time needs a day".into())), | |
| 42 | + (Some(day), Some(hour), Some(minute)) => { | |
| 43 | + let hour = i8::try_from(hour) | |
| 44 | + .map_err(|_| Error::Invalid(format!("hour {hour} is out of range")))?; | |
| 45 | + let minute = i8::try_from(minute) | |
| 46 | + .map_err(|_| Error::Invalid(format!("minute {minute} is out of range")))?; | |
| 47 | + let at = local_to_utc(zone, day, hour, minute)?; | |
| 48 | + let local_day = utc_to_local(zone, at).date(); | |
| 49 | + Ok((Some(local_day), Some(stamp_of(at)?))) | |
| 50 | + } | |
| 51 | + _ => Err(Error::Invalid( | |
| 52 | + "set both the hour and the minute, or neither".into(), | |
| 53 | + )), | |
| 54 | + } | |
| 55 | +} | |
| 56 | + | |
| 57 | +/// The stored stamp of an instant. Fails only for instants outside the range of `time`. | |
| 58 | +pub fn stamp_of(at: Timestamp) -> Result<String> { | |
| 59 | + OffsetDateTime::from_unix_timestamp_nanos(at.as_nanosecond()) | |
| 60 | + .map(format_stamp) | |
| 61 | + .map_err(|e| Error::Invalid(format!("meeting time out of range: {e}"))) | |
| 62 | +} | |
| 63 | + | |
| 64 | +/// Parses a stored stamp back into an instant for comparisons. | |
| 65 | +pub fn timestamp_of(stamp: &str) -> Result<Timestamp> { | |
| 66 | + stamp | |
| 67 | + .parse::<Timestamp>() | |
| 68 | + .map_err(|e| Error::Database(format!("stored meeting time is not a stamp: {e}"))) | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// The moment a reminder for a meeting at `meeting` is due: `REMINDER_LEAD_MINUTES` before it. | |
| 72 | +pub fn reminder_due(meeting: Timestamp) -> Result<String> { | |
| 73 | + let due = meeting | |
| 74 | + .checked_sub(SignedDuration::from_mins(REMINDER_LEAD_MINUTES)) | |
| 75 | + .map_err(|e| Error::Invalid(format!("reminder time out of range: {e}")))?; | |
| 76 | + stamp_of(due) | |
| 77 | +} | |
| 78 | + | |
| 79 | +#[cfg(test)] | |
| 80 | +mod tests { | |
| 81 | + use super::*; | |
| 82 | + use crate::zones::parse_zone; | |
| 83 | + use jiff::civil::date; | |
| 84 | + | |
| 85 | + #[test] | |
| 86 | + fn meeting_rules_truth_table() { | |
| 87 | + let berlin = parse_zone("Europe/Berlin").unwrap(); | |
| 88 | + let d = Some(date(2026, 1, 15)); | |
| 89 | + // No time: the day stands alone. | |
| 90 | + let plain = MeetingInput { | |
| 91 | + day: d, | |
| 92 | + hour: None, | |
| 93 | + minute: None, | |
| 94 | + }; | |
| 95 | + assert_eq!(resolve_meeting(plain, &berlin).unwrap(), (d, None)); | |
| 96 | + // Nothing at all clears both. | |
| 97 | + assert_eq!( | |
| 98 | + resolve_meeting(MeetingInput::default(), &berlin).unwrap(), | |
| 99 | + (None, None) | |
| 100 | + ); | |
| 101 | + // Day and full time: 09:30 Berlin winter is 08:30Z, and the deadline day is kept. | |
| 102 | + let full = MeetingInput { | |
| 103 | + day: d, | |
| 104 | + hour: Some(9), | |
| 105 | + minute: Some(30), | |
| 106 | + }; | |
| 107 | + assert_eq!( | |
| 108 | + resolve_meeting(full, &berlin).unwrap(), | |
| 109 | + (d, Some("2026-01-15T08:30:00.000000000Z".into())) | |
| 110 | + ); | |
| 111 | + // A time without a day, or only half a time, is refused. | |
| 112 | + let no_day = MeetingInput { | |
| 113 | + day: None, | |
| 114 | + hour: Some(9), | |
| 115 | + minute: Some(30), | |
| 116 | + }; | |
| 117 | + assert!(matches!( | |
| 118 | + resolve_meeting(no_day, &berlin), | |
| 119 | + Err(Error::Invalid(_)) | |
| 120 | + )); | |
| 121 | + let half = MeetingInput { | |
| 122 | + day: d, | |
| 123 | + hour: Some(9), | |
| 124 | + minute: None, | |
| 125 | + }; | |
| 126 | + assert!(matches!( | |
| 127 | + resolve_meeting(half, &berlin), | |
| 128 | + Err(Error::Invalid(_)) | |
| 129 | + )); | |
| 130 | + // A DST gap is refused (02:30 does not exist on 2026-03-29 in Berlin). | |
| 131 | + let gap = MeetingInput { | |
| 132 | + day: Some(date(2026, 3, 29)), | |
| 133 | + hour: Some(2), | |
| 134 | + minute: Some(30), | |
| 135 | + }; | |
| 136 | + assert!(matches!( | |
| 137 | + resolve_meeting(gap, &berlin), | |
| 138 | + Err(Error::Invalid(_)) | |
| 139 | + )); | |
| 140 | + // Out-of-range clock values are refused. | |
| 141 | + let late = MeetingInput { | |
| 142 | + day: d, | |
| 143 | + hour: Some(24), | |
| 144 | + minute: Some(0), | |
| 145 | + }; | |
| 146 | + assert!(matches!( | |
| 147 | + resolve_meeting(late, &berlin), | |
| 148 | + Err(Error::Invalid(_)) | |
| 149 | + )); | |
| 150 | + } | |
| 151 | + | |
| 152 | + #[test] | |
| 153 | + fn reminder_is_lead_time_before_meeting() { | |
| 154 | + let meeting: Timestamp = "2026-01-15T08:30:00Z".parse().unwrap(); | |
| 155 | + assert_eq!( | |
| 156 | + reminder_due(meeting).unwrap(), | |
| 157 | + "2026-01-15T08:15:00.000000000Z" | |
| 158 | + ); | |
| 159 | + } | |
| 160 | +} |
crates/iz-core/src/lib.rsmodified+2 -0
| @@ -3,7 +3,9 @@ | ||
| 3 | 3 | //! This crate has no HTTP. It keeps the invariants: the schema, the length limits, the board rules |
| 4 | 4 | //! (overdue, cycles, ordering), time zone math and sealing of secrets. `iz-web` builds on it. |
| 5 | 5 | |
| 6 | +pub mod authz; | |
| 6 | 7 | pub mod board; |
| 8 | +pub mod clock; | |
| 7 | 9 | pub mod config; |
| 8 | 10 | pub mod error; |
| 9 | 11 | pub mod limits; |
crates/iz-core/src/store/activity.rsadded+174 -0
| @@ -0,0 +1,174 @@ | ||
| 1 | +//! The activity trail. `record` writes one row and must be called inside the transaction of the change | |
| 2 | +//! it describes, so an activity row exists if and only if the change committed. Reads are keyset | |
| 3 | +//! pages ordered newest first; the cursor is `<stamp>~<id>` (stamps never contain `~`). | |
| 4 | +//! | |
| 5 | +//! Account events (`task_id` NULL) are visible to every board query. The web layer decides who may | |
| 6 | +//! see them; this module only keeps the board scope for task events. | |
| 7 | + | |
| 8 | +use turso::transaction::Transaction; | |
| 9 | + | |
| 10 | +use super::{col_opt_text, col_text, db_err, fetch_all, new_id}; | |
| 11 | +use crate::error::{Error, Result}; | |
| 12 | +use crate::store::Store; | |
| 13 | +use crate::time::now_stamp; | |
| 14 | + | |
| 15 | +/// Smallest and largest page size accepted by [`Store::list_recent`]. | |
| 16 | +pub const PAGE_MIN: usize = 1; | |
| 17 | +/// Largest page size accepted by [`Store::list_recent`]. Reason: bounds one response. | |
| 18 | +pub const PAGE_MAX: usize = 200; | |
| 19 | + | |
| 20 | +/// One activity row as read back. | |
| 21 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 22 | +pub struct Activity { | |
| 23 | + /// Row id (ULID). | |
| 24 | + pub id: String, | |
| 25 | + /// The task the event is about, or `None` for account events. | |
| 26 | + pub task_id: Option<String>, | |
| 27 | + /// Who did it, or `None` for system events. | |
| 28 | + pub actor: Option<String>, | |
| 29 | + /// The member the event is about (for example the person assigned), if any. | |
| 30 | + pub subject: Option<String>, | |
| 31 | + /// Event kind (one of the CHECK list in the schema). | |
| 32 | + pub kind: String, | |
| 33 | + /// JSON text with the details. | |
| 34 | + pub detail: String, | |
| 35 | + /// UTC stamp. | |
| 36 | + pub at: String, | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// An event to record. `kind` is one of the schema's CHECK list; the schema refuses anything else. | |
| 40 | +pub struct NewActivity<'a> { | |
| 41 | + /// The task, if the event is about one. | |
| 42 | + pub task_id: Option<&'a str>, | |
| 43 | + /// The acting member, or `None` for a system event. | |
| 44 | + pub actor: Option<&'a str>, | |
| 45 | + /// The member the event concerns, if any. | |
| 46 | + pub subject: Option<&'a str>, | |
| 47 | + /// Event kind. | |
| 48 | + pub kind: &'static str, | |
| 49 | + /// Details. Never secrets. | |
| 50 | + pub detail: serde_json::Value, | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// Filters for the recent-activity page. `None` means no filter. | |
| 54 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | |
| 55 | +pub struct ActivityFilter { | |
| 56 | + /// Only this event kind. | |
| 57 | + pub kind: Option<String>, | |
| 58 | + /// Only events by this member. | |
| 59 | + pub actor: Option<String>, | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// One keyset page of activity. | |
| 63 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 64 | +pub struct ActivityPage { | |
| 65 | + /// Newest first. | |
| 66 | + pub items: Vec<Activity>, | |
| 67 | + /// Pass back as `cursor` for the next (older) page; `None` when this page is not full. | |
| 68 | + pub next_cursor: Option<String>, | |
| 69 | +} | |
| 70 | + | |
| 71 | +/// Writes one activity row inside `tx`. The caller commits or rolls back with the change. | |
| 72 | +pub async fn record(tx: &Transaction<'_>, entry: NewActivity<'_>) -> Result<()> { | |
| 73 | + let detail = serde_json::to_string(&entry.detail) | |
| 74 | + .map_err(|e| Error::Database(format!("activity detail is not JSON: {e}")))?; | |
| 75 | + tx.execute( | |
| 76 | + "INSERT INTO activity (id, task_id, actor, subject, kind, detail, at) \ | |
| 77 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", | |
| 78 | + ( | |
| 79 | + new_id(), | |
| 80 | + entry.task_id.map(str::to_owned), | |
| 81 | + entry.actor.map(str::to_owned), | |
| 82 | + entry.subject.map(str::to_owned), | |
| 83 | + entry.kind, | |
| 84 | + detail, | |
| 85 | + now_stamp(), | |
| 86 | + ), | |
| 87 | + ) | |
| 88 | + .await | |
| 89 | + .map_err(db_err)?; | |
| 90 | + Ok(()) | |
| 91 | +} | |
| 92 | + | |
| 93 | +const ACTIVITY_COLS: &str = "a.id, a.task_id, a.actor, a.subject, a.kind, a.detail, a.at"; | |
| 94 | + | |
| 95 | +fn map_activity(row: &turso::Row) -> Result<Activity> { | |
| 96 | + Ok(Activity { | |
| 97 | + id: col_text(row, 0)?, | |
| 98 | + task_id: col_opt_text(row, 1)?, | |
| 99 | + actor: col_opt_text(row, 2)?, | |
| 100 | + subject: col_opt_text(row, 3)?, | |
| 101 | + kind: col_text(row, 4)?, | |
| 102 | + detail: col_text(row, 5)?, | |
| 103 | + at: col_text(row, 6)?, | |
| 104 | + }) | |
| 105 | +} | |
| 106 | + | |
| 107 | +impl Store { | |
| 108 | + /// Every event about one task of `board_id`, oldest first (the order of the task's history). | |
| 109 | + pub async fn list_for_task(&self, board_id: &str, task_id: &str) -> Result<Vec<Activity>> { | |
| 110 | + let conn = self.read_conn().await; | |
| 111 | + fetch_all( | |
| 112 | + &conn, | |
| 113 | + &format!( | |
| 114 | + "SELECT {ACTIVITY_COLS} FROM activity a JOIN tasks t ON t.id = a.task_id \ | |
| 115 | + WHERE a.task_id = ?1 AND t.board_id = ?2 ORDER BY a.at, a.id" | |
| 116 | + ), | |
| 117 | + (task_id.to_owned(), board_id.to_owned()), | |
| 118 | + map_activity, | |
| 119 | + ) | |
| 120 | + .await | |
| 121 | + } | |
| 122 | + | |
| 123 | + /// One page of recent activity, newest first. `cursor` is the `next_cursor` of the previous page. | |
| 124 | + /// `limit` must be between [`PAGE_MIN`] and [`PAGE_MAX`]. | |
| 125 | + pub async fn list_recent( | |
| 126 | + &self, | |
| 127 | + board_id: &str, | |
| 128 | + filter: &ActivityFilter, | |
| 129 | + cursor: Option<&str>, | |
| 130 | + limit: usize, | |
| 131 | + ) -> Result<ActivityPage> { | |
| 132 | + if !(PAGE_MIN..=PAGE_MAX).contains(&limit) { | |
| 133 | + return Err(Error::Invalid(format!( | |
| 134 | + "page size must be {PAGE_MIN} to {PAGE_MAX}" | |
| 135 | + ))); | |
| 136 | + } | |
| 137 | + let (before_at, before_id) = match cursor { | |
| 138 | + None => (None, None), | |
| 139 | + Some(text) => { | |
| 140 | + let (at, id) = text | |
| 141 | + .split_once('~') | |
| 142 | + .ok_or_else(|| Error::Invalid("malformed activity cursor".into()))?; | |
| 143 | + (Some(at.to_owned()), Some(id.to_owned())) | |
| 144 | + } | |
| 145 | + }; | |
| 146 | + let conn = self.read_conn().await; | |
| 147 | + let items = fetch_all( | |
| 148 | + &conn, | |
| 149 | + &format!( | |
| 150 | + "SELECT {ACTIVITY_COLS} FROM activity a LEFT JOIN tasks t ON t.id = a.task_id \ | |
| 151 | + WHERE (t.board_id = ?1 OR a.task_id IS NULL) \ | |
| 152 | + AND (?2 IS NULL OR a.kind = ?2) \ | |
| 153 | + AND (?3 IS NULL OR a.actor = ?3) \ | |
| 154 | + AND (?4 IS NULL OR a.at < ?4 OR (a.at = ?4 AND a.id < ?5)) \ | |
| 155 | + ORDER BY a.at DESC, a.id DESC LIMIT ?6" | |
| 156 | + ), | |
| 157 | + ( | |
| 158 | + board_id.to_owned(), | |
| 159 | + filter.kind.clone(), | |
| 160 | + filter.actor.clone(), | |
| 161 | + before_at, | |
| 162 | + before_id, | |
| 163 | + i64::try_from(limit).unwrap_or(i64::MAX), | |
| 164 | + ), | |
| 165 | + map_activity, | |
| 166 | + ) | |
| 167 | + .await?; | |
| 168 | + let next_cursor = match items.last() { | |
| 169 | + Some(last) if items.len() == limit => Some(format!("{}~{}", last.at, last.id)), | |
| 170 | + _ => None, | |
| 171 | + }; | |
| 172 | + Ok(ActivityPage { items, next_cursor }) | |
| 173 | + } | |
| 174 | +} |
crates/iz-core/src/store/board.rsadded+625 -0
| @@ -0,0 +1,625 @@ | ||
| 1 | +//! The board itself: its row, its columns and its tags (projects). Columns are never deleted; a column | |
| 2 | +//! that is no longer used is retired (`deleted_at`), so transitions keep naming it. Exactly one live | |
| 3 | +//! column is the done column, and it is always last. Tags keep positions without gaps, and the default | |
| 4 | +//! tag cannot be deleted. | |
| 5 | +//! | |
| 6 | +//! Each multi-step change runs in one transaction. Positions are renumbered from 1 (columns) and 1.0 | |
| 7 | +//! (tags) after every move or removal, so the order never has holes. | |
| 8 | + | |
| 9 | +use turso::Connection; | |
| 10 | +use turso::transaction::Transaction; | |
| 11 | + | |
| 12 | +use super::{col_bool, col_int, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | |
| 13 | +use crate::error::{Error, Result}; | |
| 14 | +use crate::limits::{COLUMN_NAME_MAX, TAG_NAME_MAX}; | |
| 15 | +use crate::store::Store; | |
| 16 | +use crate::time::now_stamp; | |
| 17 | + | |
| 18 | +/// Name of the board created on first start. The board has no other name source yet. | |
| 19 | +const DEFAULT_BOARD_NAME: &str = "Board"; | |
| 20 | +/// The four seeded columns, in order. The last one is the done column. | |
| 21 | +const DEFAULT_COLUMNS: [(&str, bool); 4] = [ | |
| 22 | + ("Backlog", false), | |
| 23 | + ("In Progress", false), | |
| 24 | + ("Review", false), | |
| 25 | + ("Done", true), | |
| 26 | +]; | |
| 27 | +/// Name of the tag every task wears when no other is chosen. | |
| 28 | +pub const DEFAULT_TAG_NAME: &str = "General"; | |
| 29 | +/// Longest tag colour name, in characters. Reason: colours come from a short fixed palette. | |
| 30 | +const COLOR_MAX: usize = 20; | |
| 31 | + | |
| 32 | +/// The board row. | |
| 33 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 34 | +pub struct Board { | |
| 35 | + /// Board id (ULID). | |
| 36 | + pub id: String, | |
| 37 | + /// Display name. | |
| 38 | + pub name: String, | |
| 39 | + /// Two to six uppercase letters; task keys are `PREFIX-n`. | |
| 40 | + pub key_prefix: String, | |
| 41 | + /// The next task number to hand out. Only goes up, so keys are never reused. | |
| 42 | + pub next_task_number: i64, | |
| 43 | + /// UTC stamp. | |
| 44 | + pub created_at: String, | |
| 45 | +} | |
| 46 | + | |
| 47 | +/// A column of the board. | |
| 48 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 49 | +pub struct Column { | |
| 50 | + /// Column id (ULID). | |
| 51 | + pub id: String, | |
| 52 | + /// Board the column belongs to. | |
| 53 | + pub board_id: String, | |
| 54 | + /// Display name, 1 to 60 characters. | |
| 55 | + pub name: String, | |
| 56 | + /// Order among the live columns, from 1. | |
| 57 | + pub position: i64, | |
| 58 | + /// Whether this is the done column (entering it stamps `done_at`). | |
| 59 | + pub is_done: bool, | |
| 60 | + /// Set when the column is retired. Retired columns are hidden but still named by transitions. | |
| 61 | + pub deleted_at: Option<String>, | |
| 62 | +} | |
| 63 | + | |
| 64 | +/// A tag (project). Every task wears exactly one. | |
| 65 | +#[derive(Debug, Clone, PartialEq)] | |
| 66 | +pub struct Tag { | |
| 67 | + /// Tag id (ULID). | |
| 68 | + pub id: String, | |
| 69 | + /// Board the tag belongs to. | |
| 70 | + pub board_id: String, | |
| 71 | + /// Name, unique per board regardless of case. | |
| 72 | + pub name: String, | |
| 73 | + /// Order among the tags, from 1.0. | |
| 74 | + pub position: f64, | |
| 75 | + /// Whether this is the default tag (one per board, not deletable). | |
| 76 | + pub is_default: bool, | |
| 77 | + /// Optional colour name from the fixed palette. | |
| 78 | + pub color: Option<String>, | |
| 79 | +} | |
| 80 | + | |
| 81 | +/// Direction for moving a column or a tag one place. | |
| 82 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 83 | +pub enum Direction { | |
| 84 | + /// Towards the start. | |
| 85 | + Up, | |
| 86 | + /// Towards the end. | |
| 87 | + Down, | |
| 88 | +} | |
| 89 | + | |
| 90 | +const BOARD_COLS: &str = "id, name, key_prefix, next_task_number, created_at"; | |
| 91 | +const COLUMN_COLS: &str = "id, board_id, name, position, is_done, deleted_at"; | |
| 92 | +const TAG_COLS: &str = "id, board_id, name, position, is_default, color"; | |
| 93 | + | |
| 94 | +fn map_board(row: &turso::Row) -> Result<Board> { | |
| 95 | + Ok(Board { | |
| 96 | + id: col_text(row, 0)?, | |
| 97 | + name: col_text(row, 1)?, | |
| 98 | + key_prefix: col_text(row, 2)?, | |
| 99 | + next_task_number: col_int(row, 3)?, | |
| 100 | + created_at: col_text(row, 4)?, | |
| 101 | + }) | |
| 102 | +} | |
| 103 | + | |
| 104 | +fn map_column(row: &turso::Row) -> Result<Column> { | |
| 105 | + Ok(Column { | |
| 106 | + id: col_text(row, 0)?, | |
| 107 | + board_id: col_text(row, 1)?, | |
| 108 | + name: col_text(row, 2)?, | |
| 109 | + position: col_int(row, 3)?, | |
| 110 | + is_done: col_bool(row, 4)?, | |
| 111 | + deleted_at: super::col_opt_text(row, 5)?, | |
| 112 | + }) | |
| 113 | +} | |
| 114 | + | |
| 115 | +fn map_tag(row: &turso::Row) -> Result<Tag> { | |
| 116 | + Ok(Tag { | |
| 117 | + id: col_text(row, 0)?, | |
| 118 | + board_id: col_text(row, 1)?, | |
| 119 | + name: col_text(row, 2)?, | |
| 120 | + position: col_real(row, 3)?, | |
| 121 | + is_default: col_bool(row, 4)?, | |
| 122 | + color: super::col_opt_text(row, 5)?, | |
| 123 | + }) | |
| 124 | +} | |
| 125 | + | |
| 126 | +/// A board key prefix: two to six uppercase ASCII letters. | |
| 127 | +pub fn valid_prefix(prefix: &str) -> bool { | |
| 128 | + (2..=6).contains(&prefix.len()) && prefix.bytes().all(|b| b.is_ascii_uppercase()) | |
| 129 | +} | |
| 130 | + | |
| 131 | +/// Trims and checks a column name. | |
| 132 | +pub fn clean_column_name(name: &str) -> Result<String> { | |
| 133 | + let name = name.trim(); | |
| 134 | + if name.is_empty() || name.chars().count() > COLUMN_NAME_MAX { | |
| 135 | + return Err(Error::Invalid(format!( | |
| 136 | + "column name must be 1 to {COLUMN_NAME_MAX} characters" | |
| 137 | + ))); | |
| 138 | + } | |
| 139 | + Ok(name.to_owned()) | |
| 140 | +} | |
| 141 | + | |
| 142 | +/// Trims and checks a tag name. | |
| 143 | +pub fn clean_tag_name(name: &str) -> Result<String> { | |
| 144 | + let name = name.trim(); | |
| 145 | + if name.is_empty() || name.chars().count() > TAG_NAME_MAX { | |
| 146 | + return Err(Error::Invalid(format!( | |
| 147 | + "project name must be 1 to {TAG_NAME_MAX} characters" | |
| 148 | + ))); | |
| 149 | + } | |
| 150 | + Ok(name.to_owned()) | |
| 151 | +} | |
| 152 | + | |
| 153 | +/// Live columns of a board in display order. A query helper shared with the task module. | |
| 154 | +pub(super) async fn live_columns(conn: &Connection, board_id: &str) -> Result<Vec<Column>> { | |
| 155 | + fetch_all( | |
| 156 | + conn, | |
| 157 | + &format!( | |
| 158 | + "SELECT {COLUMN_COLS} FROM columns WHERE board_id = ?1 AND deleted_at IS NULL \ | |
| 159 | + ORDER BY position, id" | |
| 160 | + ), | |
| 161 | + (board_id.to_owned(),), | |
| 162 | + map_column, | |
| 163 | + ) | |
| 164 | + .await | |
| 165 | +} | |
| 166 | + | |
| 167 | +/// One column of a board, retired or not. | |
| 168 | +pub(super) async fn column_in( | |
| 169 | + conn: &Connection, | |
| 170 | + board_id: &str, | |
| 171 | + column_id: &str, | |
| 172 | +) -> Result<Option<Column>> { | |
| 173 | + fetch_opt( | |
| 174 | + conn, | |
| 175 | + &format!("SELECT {COLUMN_COLS} FROM columns WHERE id = ?1 AND board_id = ?2"), | |
| 176 | + (column_id.to_owned(), board_id.to_owned()), | |
| 177 | + map_column, | |
| 178 | + ) | |
| 179 | + .await | |
| 180 | +} | |
| 181 | + | |
| 182 | +/// Writes `order` back as positions 1, 2, 3, ... for the live columns of the board. | |
| 183 | +async fn renumber_columns(tx: &Transaction<'_>, board_id: &str, order: &[String]) -> Result<()> { | |
| 184 | + for (i, id) in order.iter().enumerate() { | |
| 185 | + let position = i64::try_from(i + 1).unwrap_or(i64::MAX); | |
| 186 | + tx.execute( | |
| 187 | + "UPDATE columns SET position = ?3 WHERE id = ?1 AND board_id = ?2", | |
| 188 | + (id.clone(), board_id.to_owned(), position), | |
| 189 | + ) | |
| 190 | + .await | |
| 191 | + .map_err(db_err)?; | |
| 192 | + } | |
| 193 | + Ok(()) | |
| 194 | +} | |
| 195 | + | |
| 196 | +/// Writes `order` back as positions 1.0, 2.0, ... for the tags of the board. | |
| 197 | +async fn renumber_tags(tx: &Transaction<'_>, board_id: &str, order: &[String]) -> Result<()> { | |
| 198 | + for (i, id) in order.iter().enumerate() { | |
| 199 | + let position = f64::from(u32::try_from(i + 1).unwrap_or(u32::MAX)); | |
| 200 | + tx.execute( | |
| 201 | + "UPDATE tags SET position = ?3 WHERE id = ?1 AND board_id = ?2", | |
| 202 | + (id.clone(), board_id.to_owned(), position), | |
| 203 | + ) | |
| 204 | + .await | |
| 205 | + .map_err(db_err)?; | |
| 206 | + } | |
| 207 | + Ok(()) | |
| 208 | +} | |
| 209 | + | |
| 210 | +async fn all_tags(tx: &Transaction<'_>, board_id: &str) -> Result<Vec<Tag>> { | |
| 211 | + fetch_all( | |
| 212 | + tx, | |
| 213 | + &format!("SELECT {TAG_COLS} FROM tags WHERE board_id = ?1 ORDER BY position, id"), | |
| 214 | + (board_id.to_owned(),), | |
| 215 | + map_tag, | |
| 216 | + ) | |
| 217 | + .await | |
| 218 | +} | |
| 219 | + | |
| 220 | +impl Store { | |
| 221 | + /// Makes sure the board exists, creating it with its four columns and the default tag on first | |
| 222 | + /// use. Idempotent: an existing board is returned unchanged. Returns the board. | |
| 223 | + pub async fn ensure_board(&self, key_prefix: &str) -> Result<Board> { | |
| 224 | + if !valid_prefix(key_prefix) { | |
| 225 | + return Err(Error::Invalid( | |
| 226 | + "key prefix must be 2 to 6 uppercase letters".into(), | |
| 227 | + )); | |
| 228 | + } | |
| 229 | + let conn = self.inner.conn.lock().await; | |
| 230 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 231 | + let outcome: Result<Board> = async { | |
| 232 | + if let Some(board) = fetch_opt( | |
| 233 | + &tx, | |
| 234 | + &format!("SELECT {BOARD_COLS} FROM boards ORDER BY created_at, id LIMIT 1"), | |
| 235 | + (), | |
| 236 | + map_board, | |
| 237 | + ) | |
| 238 | + .await? | |
| 239 | + { | |
| 240 | + return Ok(board); | |
| 241 | + } | |
| 242 | + let board_id = new_id(); | |
| 243 | + let now = now_stamp(); | |
| 244 | + tx.execute( | |
| 245 | + "INSERT INTO boards (id, name, key_prefix, created_at) VALUES (?1, ?2, ?3, ?4)", | |
| 246 | + ( | |
| 247 | + board_id.clone(), | |
| 248 | + DEFAULT_BOARD_NAME, | |
| 249 | + key_prefix.to_owned(), | |
| 250 | + now.clone(), | |
| 251 | + ), | |
| 252 | + ) | |
| 253 | + .await | |
| 254 | + .map_err(db_err)?; | |
| 255 | + for (i, (name, is_done)) in DEFAULT_COLUMNS.iter().enumerate() { | |
| 256 | + let position = i64::try_from(i + 1).unwrap_or(i64::MAX); | |
| 257 | + tx.execute( | |
| 258 | + "INSERT INTO columns (id, board_id, name, position, is_done, created_at) \ | |
| 259 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 260 | + ( | |
| 261 | + new_id(), | |
| 262 | + board_id.clone(), | |
| 263 | + *name, | |
| 264 | + position, | |
| 265 | + i64::from(*is_done), | |
| 266 | + now.clone(), | |
| 267 | + ), | |
| 268 | + ) | |
| 269 | + .await | |
| 270 | + .map_err(db_err)?; | |
| 271 | + } | |
| 272 | + tx.execute( | |
| 273 | + "INSERT INTO tags (id, board_id, name, position, is_default, created_at) \ | |
| 274 | + VALUES (?1, ?2, ?3, 1.0, 1, ?4)", | |
| 275 | + (new_id(), board_id.clone(), DEFAULT_TAG_NAME, now), | |
| 276 | + ) | |
| 277 | + .await | |
| 278 | + .map_err(db_err)?; | |
| 279 | + fetch_opt( | |
| 280 | + &tx, | |
| 281 | + &format!("SELECT {BOARD_COLS} FROM boards WHERE id = ?1"), | |
| 282 | + (board_id,), | |
| 283 | + map_board, | |
| 284 | + ) | |
| 285 | + .await? | |
| 286 | + .ok_or_else(|| Error::Database("board vanished after insert".into())) | |
| 287 | + } | |
| 288 | + .await; | |
| 289 | + finish(tx, outcome).await | |
| 290 | + } | |
| 291 | + | |
| 292 | + /// The board, or `None` before [`Store::ensure_board`] has run. | |
| 293 | + pub async fn board(&self) -> Result<Option<Board>> { | |
| 294 | + let conn = self.read_conn().await; | |
| 295 | + fetch_opt( | |
| 296 | + &conn, | |
| 297 | + &format!("SELECT {BOARD_COLS} FROM boards ORDER BY created_at, id LIMIT 1"), | |
| 298 | + (), | |
| 299 | + map_board, | |
| 300 | + ) | |
| 301 | + .await | |
| 302 | + } | |
| 303 | + | |
| 304 | + /// The live columns of a board, in order. Retired columns are not included. | |
| 305 | + pub async fn columns(&self, board_id: &str) -> Result<Vec<Column>> { | |
| 306 | + let conn = self.read_conn().await; | |
| 307 | + live_columns(&conn, board_id).await | |
| 308 | + } | |
| 309 | + | |
| 310 | + /// One column of `board_id`, retired or not. `None` when it belongs to another board or does not exist. | |
| 311 | + pub async fn column(&self, board_id: &str, column_id: &str) -> Result<Option<Column>> { | |
| 312 | + let conn = self.read_conn().await; | |
| 313 | + column_in(&conn, board_id, column_id).await | |
| 314 | + } | |
| 315 | + | |
| 316 | + /// Adds a column before the done column (so done stays last). Returns the new column. | |
| 317 | + pub async fn add_column(&self, board_id: &str, name: &str) -> Result<Column> { | |
| 318 | + let name = clean_column_name(name)?; | |
| 319 | + let conn = self.inner.conn.lock().await; | |
| 320 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 321 | + let outcome: Result<Column> = async { | |
| 322 | + let live = live_columns(&tx, board_id).await?; | |
| 323 | + let mut order: Vec<String> = live.iter().map(|c| c.id.clone()).collect(); | |
| 324 | + let at = live.iter().position(|c| c.is_done).unwrap_or(order.len()); | |
| 325 | + let id = new_id(); | |
| 326 | + tx.execute( | |
| 327 | + "INSERT INTO columns (id, board_id, name, position, is_done, created_at) \ | |
| 328 | + VALUES (?1, ?2, ?3, 0, 0, ?4)", | |
| 329 | + (id.clone(), board_id.to_owned(), name, now_stamp()), | |
| 330 | + ) | |
| 331 | + .await | |
| 332 | + .map_err(db_err)?; | |
| 333 | + order.insert(at, id.clone()); | |
| 334 | + renumber_columns(&tx, board_id, &order).await?; | |
| 335 | + column_in(&tx, board_id, &id) | |
| 336 | + .await? | |
| 337 | + .ok_or_else(|| Error::Database("column vanished after insert".into())) | |
| 338 | + } | |
| 339 | + .await; | |
| 340 | + finish(tx, outcome).await | |
| 341 | + } | |
| 342 | + | |
| 343 | + /// Renames a live column. Retired or foreign columns are `NotFound`. | |
| 344 | + pub async fn rename_column(&self, board_id: &str, column_id: &str, name: &str) -> Result<()> { | |
| 345 | + let name = clean_column_name(name)?; | |
| 346 | + let conn = self.inner.conn.lock().await; | |
| 347 | + let changed = conn | |
| 348 | + .execute( | |
| 349 | + "UPDATE columns SET name = ?3 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 350 | + (column_id.to_owned(), board_id.to_owned(), name), | |
| 351 | + ) | |
| 352 | + .await | |
| 353 | + .map_err(db_err)?; | |
| 354 | + if changed == 0 { | |
| 355 | + return Err(Error::NotFound); | |
| 356 | + } | |
| 357 | + Ok(()) | |
| 358 | + } | |
| 359 | + | |
| 360 | + /// Moves a live column one place. The done column cannot move, and no column moves past it. At | |
| 361 | + /// the ends of the board the call changes nothing. | |
| 362 | + pub async fn move_column( | |
| 363 | + &self, | |
| 364 | + board_id: &str, | |
| 365 | + column_id: &str, | |
| 366 | + direction: Direction, | |
| 367 | + ) -> Result<()> { | |
| 368 | + let conn = self.inner.conn.lock().await; | |
| 369 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 370 | + let outcome: Result<()> = async { | |
| 371 | + let live = live_columns(&tx, board_id).await?; | |
| 372 | + let index = live | |
| 373 | + .iter() | |
| 374 | + .position(|c| c.id == column_id) | |
| 375 | + .ok_or(Error::NotFound)?; | |
| 376 | + if live[index].is_done { | |
| 377 | + return Err(Error::Invalid("the done column stays last".into())); | |
| 378 | + } | |
| 379 | + let target = match direction { | |
| 380 | + Direction::Up => index.checked_sub(1), | |
| 381 | + Direction::Down => Some(index + 1).filter(|&i| i < live.len()), | |
| 382 | + }; | |
| 383 | + let Some(target) = target else { return Ok(()) }; | |
| 384 | + if live[target].is_done { | |
| 385 | + return Err(Error::Invalid("the done column stays last".into())); | |
| 386 | + } | |
| 387 | + let mut order: Vec<String> = live.iter().map(|c| c.id.clone()).collect(); | |
| 388 | + order.swap(index, target); | |
| 389 | + renumber_columns(&tx, board_id, &order).await | |
| 390 | + } | |
| 391 | + .await; | |
| 392 | + finish(tx, outcome).await | |
| 393 | + } | |
| 394 | + | |
| 395 | + /// Retires a live column. Refused for the done column, and while any live task is in it. | |
| 396 | + pub async fn retire_column(&self, board_id: &str, column_id: &str) -> Result<()> { | |
| 397 | + let conn = self.inner.conn.lock().await; | |
| 398 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 399 | + let outcome: Result<()> = async { | |
| 400 | + let live = live_columns(&tx, board_id).await?; | |
| 401 | + let column = live | |
| 402 | + .iter() | |
| 403 | + .find(|c| c.id == column_id) | |
| 404 | + .ok_or(Error::NotFound)?; | |
| 405 | + if column.is_done { | |
| 406 | + return Err(Error::Invalid("the done column cannot be retired".into())); | |
| 407 | + } | |
| 408 | + let holding = fetch_opt( | |
| 409 | + &tx, | |
| 410 | + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND column_id = ?2 AND deleted_at IS NULL", | |
| 411 | + (board_id.to_owned(), column_id.to_owned()), | |
| 412 | + |row| col_int(row, 0), | |
| 413 | + ) | |
| 414 | + .await? | |
| 415 | + .unwrap_or(0); | |
| 416 | + if holding > 0 { | |
| 417 | + return Err(Error::Conflict(format!( | |
| 418 | + "the column still holds {holding} tasks; move them first" | |
| 419 | + ))); | |
| 420 | + } | |
| 421 | + tx.execute( | |
| 422 | + "UPDATE columns SET deleted_at = ?3 WHERE id = ?1 AND board_id = ?2", | |
| 423 | + (column_id.to_owned(), board_id.to_owned(), now_stamp()), | |
| 424 | + ) | |
| 425 | + .await | |
| 426 | + .map_err(db_err)?; | |
| 427 | + let order: Vec<String> = live | |
| 428 | + .iter() | |
| 429 | + .filter(|c| c.id != column_id) | |
| 430 | + .map(|c| c.id.clone()) | |
| 431 | + .collect(); | |
| 432 | + renumber_columns(&tx, board_id, &order).await | |
| 433 | + } | |
| 434 | + .await; | |
| 435 | + finish(tx, outcome).await | |
| 436 | + } | |
| 437 | + | |
| 438 | + /// Every tag of a board, in order. | |
| 439 | + pub async fn tags(&self, board_id: &str) -> Result<Vec<Tag>> { | |
| 440 | + let conn = self.read_conn().await; | |
| 441 | + fetch_all( | |
| 442 | + &conn, | |
| 443 | + &format!("SELECT {TAG_COLS} FROM tags WHERE board_id = ?1 ORDER BY position, id"), | |
| 444 | + (board_id.to_owned(),), | |
| 445 | + map_tag, | |
| 446 | + ) | |
| 447 | + .await | |
| 448 | + } | |
| 449 | + | |
| 450 | + /// One tag of `board_id`, or `None`. | |
| 451 | + pub async fn tag(&self, board_id: &str, tag_id: &str) -> Result<Option<Tag>> { | |
| 452 | + let conn = self.read_conn().await; | |
| 453 | + fetch_opt( | |
| 454 | + &conn, | |
| 455 | + &format!("SELECT {TAG_COLS} FROM tags WHERE id = ?1 AND board_id = ?2"), | |
| 456 | + (tag_id.to_owned(), board_id.to_owned()), | |
| 457 | + map_tag, | |
| 458 | + ) | |
| 459 | + .await | |
| 460 | + } | |
| 461 | + | |
| 462 | + /// Adds a tag at the end. Names are unique per board, ignoring case. Returns the tag. | |
| 463 | + pub async fn add_tag(&self, board_id: &str, name: &str, color: Option<&str>) -> Result<Tag> { | |
| 464 | + let name = clean_tag_name(name)?; | |
| 465 | + let color = match color.map(str::trim).filter(|c| !c.is_empty()) { | |
| 466 | + Some(c) if c.chars().count() <= COLOR_MAX => Some(c.to_owned()), | |
| 467 | + Some(_) => return Err(Error::Invalid("colour name is too long".into())), | |
| 468 | + None => None, | |
| 469 | + }; | |
| 470 | + let conn = self.inner.conn.lock().await; | |
| 471 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 472 | + let outcome: Result<Tag> = | |
| 473 | + async { | |
| 474 | + let existing = all_tags(&tx, board_id).await?; | |
| 475 | + if existing | |
| 476 | + .iter() | |
| 477 | + .any(|t| t.name.to_lowercase() == name.to_lowercase()) | |
| 478 | + { | |
| 479 | + return Err(Error::Conflict( | |
| 480 | + "a project with that name already exists".into(), | |
| 481 | + )); | |
| 482 | + } | |
| 483 | + let position = existing.iter().map(|t| t.position).fold(0.0_f64, f64::max) + 1.0; | |
| 484 | + let id = new_id(); | |
| 485 | + tx.execute( | |
| 486 | + "INSERT INTO tags (id, board_id, name, position, is_default, color, created_at) \ | |
| 487 | + VALUES (?1, ?2, ?3, ?4, 0, ?5, ?6)", | |
| 488 | + (id.clone(), board_id.to_owned(), name, position, color, now_stamp()), | |
| 489 | + ) | |
| 490 | + .await | |
| 491 | + .map_err(db_err)?; | |
| 492 | + fetch_opt( | |
| 493 | + &tx, | |
| 494 | + &format!("SELECT {TAG_COLS} FROM tags WHERE id = ?1"), | |
| 495 | + (id,), | |
| 496 | + map_tag, | |
| 497 | + ) | |
| 498 | + .await? | |
| 499 | + .ok_or_else(|| Error::Database("tag vanished after insert".into())) | |
| 500 | + } | |
| 501 | + .await; | |
| 502 | + finish(tx, outcome).await | |
| 503 | + } | |
| 504 | + | |
| 505 | + /// Renames a tag. The new name must be unique per board, ignoring case. | |
| 506 | + pub async fn rename_tag(&self, board_id: &str, tag_id: &str, name: &str) -> Result<()> { | |
| 507 | + let name = clean_tag_name(name)?; | |
| 508 | + let conn = self.inner.conn.lock().await; | |
| 509 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 510 | + let outcome: Result<()> = async { | |
| 511 | + let existing = all_tags(&tx, board_id).await?; | |
| 512 | + if !existing.iter().any(|t| t.id == tag_id) { | |
| 513 | + return Err(Error::NotFound); | |
| 514 | + } | |
| 515 | + if existing | |
| 516 | + .iter() | |
| 517 | + .any(|t| t.id != tag_id && t.name.to_lowercase() == name.to_lowercase()) | |
| 518 | + { | |
| 519 | + return Err(Error::Conflict( | |
| 520 | + "a project with that name already exists".into(), | |
| 521 | + )); | |
| 522 | + } | |
| 523 | + tx.execute( | |
| 524 | + "UPDATE tags SET name = ?3 WHERE id = ?1 AND board_id = ?2", | |
| 525 | + (tag_id.to_owned(), board_id.to_owned(), name), | |
| 526 | + ) | |
| 527 | + .await | |
| 528 | + .map_err(db_err)?; | |
| 529 | + Ok(()) | |
| 530 | + } | |
| 531 | + .await; | |
| 532 | + finish(tx, outcome).await | |
| 533 | + } | |
| 534 | + | |
| 535 | + /// Deletes a tag. Refused for the default tag, and while a live task wears it. Trashed (deleted) | |
| 536 | + /// tasks that still name it are moved to the default tag in the same transaction. | |
| 537 | + pub async fn delete_tag(&self, board_id: &str, tag_id: &str) -> Result<()> { | |
| 538 | + let conn = self.inner.conn.lock().await; | |
| 539 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 540 | + let outcome: Result<()> = async { | |
| 541 | + let tags = all_tags(&tx, board_id).await?; | |
| 542 | + let tag = tags.iter().find(|t| t.id == tag_id).ok_or(Error::NotFound)?; | |
| 543 | + if tag.is_default { | |
| 544 | + return Err(Error::Invalid("the default project cannot be deleted".into())); | |
| 545 | + } | |
| 546 | + let in_use = fetch_opt( | |
| 547 | + &tx, | |
| 548 | + "SELECT COUNT(*) FROM tasks WHERE board_id = ?1 AND tag_id = ?2 AND deleted_at IS NULL", | |
| 549 | + (board_id.to_owned(), tag_id.to_owned()), | |
| 550 | + |row| col_int(row, 0), | |
| 551 | + ) | |
| 552 | + .await? | |
| 553 | + .unwrap_or(0); | |
| 554 | + if in_use > 0 { | |
| 555 | + return Err(Error::Conflict(format!( | |
| 556 | + "the project is used by {in_use} tasks; move them first" | |
| 557 | + ))); | |
| 558 | + } | |
| 559 | + let default_id = tags | |
| 560 | + .iter() | |
| 561 | + .find(|t| t.is_default) | |
| 562 | + .map(|t| t.id.clone()) | |
| 563 | + .ok_or_else(|| Error::Database("board has no default project".into()))?; | |
| 564 | + tx.execute( | |
| 565 | + "UPDATE tasks SET tag_id = ?3 WHERE board_id = ?1 AND tag_id = ?2 AND deleted_at IS NOT NULL", | |
| 566 | + (board_id.to_owned(), tag_id.to_owned(), default_id), | |
| 567 | + ) | |
| 568 | + .await | |
| 569 | + .map_err(db_err)?; | |
| 570 | + tx.execute( | |
| 571 | + "DELETE FROM tags WHERE id = ?1 AND board_id = ?2", | |
| 572 | + (tag_id.to_owned(), board_id.to_owned()), | |
| 573 | + ) | |
| 574 | + .await | |
| 575 | + .map_err(db_err)?; | |
| 576 | + let order: Vec<String> = tags | |
| 577 | + .iter() | |
| 578 | + .filter(|t| t.id != tag_id) | |
| 579 | + .map(|t| t.id.clone()) | |
| 580 | + .collect(); | |
| 581 | + renumber_tags(&tx, board_id, &order).await | |
| 582 | + } | |
| 583 | + .await; | |
| 584 | + finish(tx, outcome).await | |
| 585 | + } | |
| 586 | + | |
| 587 | + /// Moves a tag one place and renumbers all tags, so there are never gaps. At the ends, no change. | |
| 588 | + pub async fn move_tag(&self, board_id: &str, tag_id: &str, direction: Direction) -> Result<()> { | |
| 589 | + let conn = self.inner.conn.lock().await; | |
| 590 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 591 | + let outcome: Result<()> = async { | |
| 592 | + let tags = all_tags(&tx, board_id).await?; | |
| 593 | + let index = tags | |
| 594 | + .iter() | |
| 595 | + .position(|t| t.id == tag_id) | |
| 596 | + .ok_or(Error::NotFound)?; | |
| 597 | + let target = match direction { | |
| 598 | + Direction::Up => index.checked_sub(1), | |
| 599 | + Direction::Down => Some(index + 1).filter(|&i| i < tags.len()), | |
| 600 | + }; | |
| 601 | + let Some(target) = target else { return Ok(()) }; | |
| 602 | + let mut order: Vec<String> = tags.iter().map(|t| t.id.clone()).collect(); | |
| 603 | + order.swap(index, target); | |
| 604 | + renumber_tags(&tx, board_id, &order).await | |
| 605 | + } | |
| 606 | + .await; | |
| 607 | + finish(tx, outcome).await | |
| 608 | + } | |
| 609 | +} | |
| 610 | + | |
| 611 | +#[cfg(test)] | |
| 612 | +mod tests { | |
| 613 | + use super::*; | |
| 614 | + | |
| 615 | + #[test] | |
| 616 | + fn prefix_and_names_are_checked() { | |
| 617 | + assert!(valid_prefix("IZ")); | |
| 618 | + assert!(valid_prefix("ABCDEF")); | |
| 619 | + assert!(!valid_prefix("I")); | |
| 620 | + assert!(!valid_prefix("iz")); | |
| 621 | + assert!(!valid_prefix("IZ1")); | |
| 622 | + assert!(clean_column_name(" ").is_err()); | |
| 623 | + assert_eq!(clean_tag_name(" Home ").unwrap(), "Home"); | |
| 624 | + } | |
| 625 | +} |
crates/iz-core/src/store/comments.rsadded+333 -0
| @@ -0,0 +1,333 @@ | ||
| 1 | +//! Comments on tasks. Posting is the caller's check (a member, not a viewer). Editing and deleting are | |
| 2 | +//! checked here through `authz::authorize`, against the comment's own author, so the rule lives in one | |
| 3 | +//! place: an author edits or deletes their own comment, and an admin may delete any comment. Deletion is | |
| 4 | +//! soft: the row stays so the activity trail can name it, and lists skip it. | |
| 5 | + | |
| 6 | +use turso::Connection; | |
| 7 | + | |
| 8 | +use super::activity::{self, NewActivity}; | |
| 9 | +use super::{col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; | |
| 10 | +use crate::authz::{Action, Actor, authorize}; | |
| 11 | +use crate::error::{Error, Result}; | |
| 12 | +use crate::limits::COMMENT_MAX; | |
| 13 | +use crate::store::Store; | |
| 14 | +use crate::time::now_stamp; | |
| 15 | + | |
| 16 | +/// One comment as stored. | |
| 17 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 18 | +pub struct Comment { | |
| 19 | + /// Comment id (ULID). | |
| 20 | + pub id: String, | |
| 21 | + /// The task it belongs to. | |
| 22 | + pub task_id: String, | |
| 23 | + /// The author's member id. | |
| 24 | + pub author: String, | |
| 25 | + /// Plain text, 1 to 10 000 characters. | |
| 26 | + pub body: String, | |
| 27 | + /// UTC stamp. | |
| 28 | + pub created_at: String, | |
| 29 | + /// UTC stamp of the last edit, if edited. | |
| 30 | + pub edited_at: Option<String>, | |
| 31 | + /// UTC stamp of deletion, if deleted (such rows are not listed). | |
| 32 | + pub deleted_at: Option<String>, | |
| 33 | +} | |
| 34 | + | |
| 35 | +const COMMENT_COLS: &str = "id, task_id, author, body, created_at, edited_at, deleted_at"; | |
| 36 | + | |
| 37 | +fn map_comment(row: &turso::Row) -> Result<Comment> { | |
| 38 | + Ok(Comment { | |
| 39 | + id: col_text(row, 0)?, | |
| 40 | + task_id: col_text(row, 1)?, | |
| 41 | + author: col_text(row, 2)?, | |
| 42 | + body: col_text(row, 3)?, | |
| 43 | + created_at: col_text(row, 4)?, | |
| 44 | + edited_at: col_opt_text(row, 5)?, | |
| 45 | + deleted_at: col_opt_text(row, 6)?, | |
| 46 | + }) | |
| 47 | +} | |
| 48 | + | |
| 49 | +fn clean_body(body: &str) -> Result<String> { | |
| 50 | + let body = body.trim(); | |
| 51 | + if body.is_empty() || body.chars().count() > COMMENT_MAX { | |
| 52 | + return Err(Error::Invalid(format!( | |
| 53 | + "comment must be 1 to {COMMENT_MAX} characters" | |
| 54 | + ))); | |
| 55 | + } | |
| 56 | + Ok(body.to_owned()) | |
| 57 | +} | |
| 58 | + | |
| 59 | +/// The member id behind an actor that has already passed `authorize`. | |
| 60 | +fn member_sub(actor: &Actor) -> Result<&str> { | |
| 61 | + match actor { | |
| 62 | + Actor::Member { sub, .. } => Ok(sub), | |
| 63 | + Actor::Anonymous => Err(Error::Forbidden("sign in to continue".into())), | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +/// Reads a live comment of `board_id` with its task id and author. Missing or foreign: `NotFound`. | |
| 68 | +async fn live_comment(conn: &Connection, board_id: &str, comment_id: &str) -> Result<Comment> { | |
| 69 | + fetch_opt( | |
| 70 | + conn, | |
| 71 | + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ | |
| 72 | + JOIN tasks t ON t.id = c.task_id \ | |
| 73 | + WHERE c.id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL", | |
| 74 | + (comment_id.to_owned(), board_id.to_owned()), | |
| 75 | + map_comment, | |
| 76 | + ) | |
| 77 | + .await? | |
| 78 | + .ok_or(Error::NotFound) | |
| 79 | +} | |
| 80 | + | |
| 81 | +impl Store { | |
| 82 | + /// Posts a comment on a live task of `board_id`, with its `comment_added` activity row. | |
| 83 | + pub async fn add_comment( | |
| 84 | + &self, | |
| 85 | + board_id: &str, | |
| 86 | + task_id: &str, | |
| 87 | + author: &str, | |
| 88 | + body: &str, | |
| 89 | + ) -> Result<Comment> { | |
| 90 | + let body = clean_body(body)?; | |
| 91 | + let conn = self.inner.conn.lock().await; | |
| 92 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 93 | + let outcome: Result<Comment> = async { | |
| 94 | + let live = fetch_opt( | |
| 95 | + &tx, | |
| 96 | + "SELECT id FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 97 | + (task_id.to_owned(), board_id.to_owned()), | |
| 98 | + |row| col_text(row, 0), | |
| 99 | + ) | |
| 100 | + .await?; | |
| 101 | + if live.is_none() { | |
| 102 | + return Err(Error::NotFound); | |
| 103 | + } | |
| 104 | + let id = new_id(); | |
| 105 | + tx.execute( | |
| 106 | + "INSERT INTO comments (id, task_id, author, body, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 107 | + (id.clone(), task_id.to_owned(), author.to_owned(), body, now_stamp()), | |
| 108 | + ) | |
| 109 | + .await | |
| 110 | + .map_err(db_err)?; | |
| 111 | + activity::record( | |
| 112 | + &tx, | |
| 113 | + NewActivity { | |
| 114 | + task_id: Some(task_id), | |
| 115 | + actor: Some(author), | |
| 116 | + subject: None, | |
| 117 | + kind: "comment_added", | |
| 118 | + detail: serde_json::json!({ "comment": id }), | |
| 119 | + }, | |
| 120 | + ) | |
| 121 | + .await?; | |
| 122 | + fetch_opt( | |
| 123 | + &tx, | |
| 124 | + &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), | |
| 125 | + (id,), | |
| 126 | + map_comment, | |
| 127 | + ) | |
| 128 | + .await? | |
| 129 | + .ok_or_else(|| Error::Database("comment vanished after insert".into())) | |
| 130 | + } | |
| 131 | + .await; | |
| 132 | + finish(tx, outcome).await | |
| 133 | + } | |
| 134 | + | |
| 135 | + /// Live comments of a task of `board_id`, oldest first. | |
| 136 | + pub async fn list_comments(&self, board_id: &str, task_id: &str) -> Result<Vec<Comment>> { | |
| 137 | + let conn = self.read_conn().await; | |
| 138 | + fetch_all( | |
| 139 | + &conn, | |
| 140 | + "SELECT c.id, c.task_id, c.author, c.body, c.created_at, c.edited_at, c.deleted_at FROM comments c \ | |
| 141 | + JOIN tasks t ON t.id = c.task_id \ | |
| 142 | + WHERE c.task_id = ?1 AND t.board_id = ?2 AND c.deleted_at IS NULL ORDER BY c.created_at, c.id", | |
| 143 | + (task_id.to_owned(), board_id.to_owned()), | |
| 144 | + map_comment, | |
| 145 | + ) | |
| 146 | + .await | |
| 147 | + } | |
| 148 | + | |
| 149 | + /// Edits a comment. Only its author may, and only while still a member (`authz`). | |
| 150 | + pub async fn edit_comment( | |
| 151 | + &self, | |
| 152 | + board_id: &str, | |
| 153 | + comment_id: &str, | |
| 154 | + actor: &Actor, | |
| 155 | + body: &str, | |
| 156 | + ) -> Result<Comment> { | |
| 157 | + let body = clean_body(body)?; | |
| 158 | + let conn = self.inner.conn.lock().await; | |
| 159 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 160 | + let outcome: Result<Comment> = async { | |
| 161 | + let current = live_comment(&tx, board_id, comment_id).await?; | |
| 162 | + authorize( | |
| 163 | + actor, | |
| 164 | + &Action::EditComment { | |
| 165 | + author: current.author.clone(), | |
| 166 | + }, | |
| 167 | + )?; | |
| 168 | + let sub = member_sub(actor)?; | |
| 169 | + tx.execute( | |
| 170 | + "UPDATE comments SET body = ?2, edited_at = ?3 WHERE id = ?1", | |
| 171 | + (comment_id.to_owned(), body, now_stamp()), | |
| 172 | + ) | |
| 173 | + .await | |
| 174 | + .map_err(db_err)?; | |
| 175 | + activity::record( | |
| 176 | + &tx, | |
| 177 | + NewActivity { | |
| 178 | + task_id: Some(¤t.task_id), | |
| 179 | + actor: Some(sub), | |
| 180 | + subject: None, | |
| 181 | + kind: "comment_edited", | |
| 182 | + detail: serde_json::json!({ "comment": comment_id }), | |
| 183 | + }, | |
| 184 | + ) | |
| 185 | + .await?; | |
| 186 | + fetch_opt( | |
| 187 | + &tx, | |
| 188 | + &format!("SELECT {COMMENT_COLS} FROM comments WHERE id = ?1"), | |
| 189 | + (comment_id.to_owned(),), | |
| 190 | + map_comment, | |
| 191 | + ) | |
| 192 | + .await? | |
| 193 | + .ok_or(Error::NotFound) | |
| 194 | + } | |
| 195 | + .await; | |
| 196 | + finish(tx, outcome).await | |
| 197 | + } | |
| 198 | + | |
| 199 | + /// Soft-deletes a comment. Its author (while a member) or any admin may do it (`authz`). | |
| 200 | + pub async fn delete_comment( | |
| 201 | + &self, | |
| 202 | + board_id: &str, | |
| 203 | + comment_id: &str, | |
| 204 | + actor: &Actor, | |
| 205 | + ) -> Result<()> { | |
| 206 | + let conn = self.inner.conn.lock().await; | |
| 207 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 208 | + let outcome: Result<()> = async { | |
| 209 | + let current = live_comment(&tx, board_id, comment_id).await?; | |
| 210 | + authorize( | |
| 211 | + actor, | |
| 212 | + &Action::DeleteComment { | |
| 213 | + author: current.author.clone(), | |
| 214 | + }, | |
| 215 | + )?; | |
| 216 | + let sub = member_sub(actor)?; | |
| 217 | + tx.execute( | |
| 218 | + "UPDATE comments SET deleted_at = ?2 WHERE id = ?1", | |
| 219 | + (comment_id.to_owned(), now_stamp()), | |
| 220 | + ) | |
| 221 | + .await | |
| 222 | + .map_err(db_err)?; | |
| 223 | + activity::record( | |
| 224 | + &tx, | |
| 225 | + NewActivity { | |
| 226 | + task_id: Some(¤t.task_id), | |
| 227 | + actor: Some(sub), | |
| 228 | + subject: Some(¤t.author), | |
| 229 | + kind: "comment_deleted", | |
| 230 | + detail: serde_json::json!({ "comment": comment_id }), | |
| 231 | + }, | |
| 232 | + ) | |
| 233 | + .await | |
| 234 | + } | |
| 235 | + .await; | |
| 236 | + finish(tx, outcome).await | |
| 237 | + } | |
| 238 | +} | |
| 239 | + | |
| 240 | +#[cfg(test)] | |
| 241 | +mod tests { | |
| 242 | + use super::*; | |
| 243 | + use crate::authz::Role; | |
| 244 | + use crate::store::activity::ActivityFilter; | |
| 245 | + use crate::store::tasks::NewTask; | |
| 246 | + use crate::store::test_support::seeded; | |
| 247 | + | |
| 248 | + fn member(sub: &str, role: Role) -> Actor { | |
| 249 | + Actor::Member { | |
| 250 | + sub: sub.into(), | |
| 251 | + role, | |
| 252 | + im_admin: false, | |
| 253 | + disabled: false, | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + #[tokio::test] | |
| 258 | + async fn only_the_author_edits_and_admins_moderate() { | |
| 259 | + let (_dir, store, board) = seeded().await; | |
| 260 | + let tag = store.tags(&board).await.unwrap()[0].id.clone(); | |
| 261 | + let column = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 262 | + let task = store | |
| 263 | + .create_task( | |
| 264 | + &board, | |
| 265 | + NewTask { | |
| 266 | + title: "Talk".into(), | |
| 267 | + description: String::new(), | |
| 268 | + column_id: column, | |
| 269 | + tag_id: tag, | |
| 270 | + deadline: None, | |
| 271 | + meeting_at: None, | |
| 272 | + assignees: vec![], | |
| 273 | + parent_id: None, | |
| 274 | + link: None, | |
| 275 | + }, | |
| 276 | + "ada", | |
| 277 | + ) | |
| 278 | + .await | |
| 279 | + .unwrap(); | |
| 280 | + let comment = store | |
| 281 | + .add_comment(&board, &task.id, "bo", " hello ") | |
| 282 | + .await | |
| 283 | + .unwrap(); | |
| 284 | + assert_eq!(comment.body, "hello"); | |
| 285 | + // The admin cannot edit someone else's words, but can delete them. | |
| 286 | + let ada = member("ada", Role::Admin); | |
| 287 | + assert!(matches!( | |
| 288 | + store | |
| 289 | + .edit_comment(&board, &comment.id, &ada, "changed") | |
| 290 | + .await, | |
| 291 | + Err(Error::Forbidden(_)) | |
| 292 | + )); | |
| 293 | + let bo = member("bo", Role::Member); | |
| 294 | + let edited = store | |
| 295 | + .edit_comment(&board, &comment.id, &bo, "edited") | |
| 296 | + .await | |
| 297 | + .unwrap(); | |
| 298 | + assert!(edited.edited_at.is_some()); | |
| 299 | + store | |
| 300 | + .delete_comment(&board, &comment.id, &ada) | |
| 301 | + .await | |
| 302 | + .unwrap(); | |
| 303 | + assert!( | |
| 304 | + store | |
| 305 | + .list_comments(&board, &task.id) | |
| 306 | + .await | |
| 307 | + .unwrap() | |
| 308 | + .is_empty() | |
| 309 | + ); | |
| 310 | + // The activity trail pages newest first with a keyset cursor. | |
| 311 | + let page = store | |
| 312 | + .list_recent(&board, &ActivityFilter::default(), None, 2) | |
| 313 | + .await | |
| 314 | + .unwrap(); | |
| 315 | + assert_eq!(page.items.len(), 2); | |
| 316 | + let next = store | |
| 317 | + .list_recent( | |
| 318 | + &board, | |
| 319 | + &ActivityFilter::default(), | |
| 320 | + page.next_cursor.as_deref(), | |
| 321 | + 200, | |
| 322 | + ) | |
| 323 | + .await | |
| 324 | + .unwrap(); | |
| 325 | + assert!(next.items.iter().all(|a| !page.items.contains(a))); | |
| 326 | + assert!( | |
| 327 | + store | |
| 328 | + .list_recent(&board, &ActivityFilter::default(), None, 0) | |
| 329 | + .await | |
| 330 | + .is_err() | |
| 331 | + ); | |
| 332 | + } | |
| 333 | +} |
crates/iz-core/src/store/members.rsadded+412 -0
| @@ -0,0 +1,412 @@ | ||
| 1 | +//! Members: the mirror of the family directory (`im`) plus iz's own state (role, preferences). | |
| 2 | +//! Directory data is written by `apply_directory_member` (the roster and change stream) and by | |
| 3 | +//! `upsert_from_claims` (a sign-in, which also stamps `last_sign_in_at`). iz never invents a member: | |
| 4 | +//! people are added in `im`, and iz only assigns roles. | |
| 5 | +//! | |
| 6 | +//! Role changes that remove access also remove the member's assignments and pending reminders in the | |
| 7 | +//! same transaction, so a viewer or a removed member never keeps a card or a reminder. | |
| 8 | + | |
| 9 | +use turso::Connection; | |
| 10 | +use turso::transaction::Transaction; | |
| 11 | + | |
| 12 | +use super::{col_bool, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; | |
| 13 | +use crate::authz::Role; | |
| 14 | +use crate::error::{Error, Result}; | |
| 15 | +use crate::limits::DISPLAY_NAME_MAX; | |
| 16 | +use crate::store::Store; | |
| 17 | +use crate::time::now_stamp; | |
| 18 | +use crate::zones::parse_zone; | |
| 19 | + | |
| 20 | +/// Longest email address accepted from the directory, in characters (RFC 5321 path limit). | |
| 21 | +const EMAIL_MAX: usize = 320; | |
| 22 | +/// Theme choices, matching the CHECK constraint. | |
| 23 | +pub const THEMES: [&str; 3] = ["system", "light", "dark"]; | |
| 24 | +/// Layout choices, matching the CHECK constraint. | |
| 25 | +pub const UI_STYLES: [&str; 2] = ["instrument", "ledger"]; | |
| 26 | +/// Languages iz is translated into. | |
| 27 | +pub const LOCALES: [&str; 2] = ["en", "tr"]; | |
| 28 | + | |
| 29 | +/// One member as stored. | |
| 30 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 31 | +pub struct Member { | |
| 32 | + /// Stable id (the OIDC `sub`). | |
| 33 | + pub sub: String, | |
| 34 | + /// Address as the directory has it. | |
| 35 | + pub email: String, | |
| 36 | + /// Display name. | |
| 37 | + pub name: String, | |
| 38 | + /// Directory flag: this person is an administrator in `im`. | |
| 39 | + pub im_admin: bool, | |
| 40 | + /// Disabled in `im` or deleted. A disabled member has no access and is not mailed. | |
| 41 | + pub disabled: bool, | |
| 42 | + /// Language from the directory, if any. | |
| 43 | + pub locale: Option<String>, | |
| 44 | + /// Language chosen by the member in iz, if any. | |
| 45 | + pub locale_override: Option<String>, | |
| 46 | + /// IANA zone name, for example `Europe/Istanbul`. | |
| 47 | + pub zoneinfo: String, | |
| 48 | + /// Stored role. | |
| 49 | + pub role: Role, | |
| 50 | + /// `system`, `light` or `dark`. | |
| 51 | + pub theme: String, | |
| 52 | + /// `instrument` or `ledger`. | |
| 53 | + pub ui: String, | |
| 54 | + /// Bumped by the directory when the photo changes; used for avatar caching. | |
| 55 | + pub picture_version: i64, | |
| 56 | + /// UTC stamp of the first time the member was seen. | |
| 57 | + pub first_seen_at: String, | |
| 58 | + /// UTC stamp of the last sign-in, if any. | |
| 59 | + pub last_sign_in_at: Option<String>, | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// What the directory (or a sign-in) says about one person. Validated before it is stored. | |
| 63 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 64 | +pub struct DirectoryMember { | |
| 65 | + /// Stable id (the OIDC `sub`). | |
| 66 | + pub sub: String, | |
| 67 | + /// Address. | |
| 68 | + pub email: String, | |
| 69 | + /// Display name. | |
| 70 | + pub name: String, | |
| 71 | + /// Administrator flag in `im`. | |
| 72 | + pub im_admin: bool, | |
| 73 | + /// Disabled flag in `im`. | |
| 74 | + pub disabled: bool, | |
| 75 | + /// `en`, `tr`, or `None` for anything else. | |
| 76 | + pub locale: Option<String>, | |
| 77 | + /// IANA zone name. Must parse. | |
| 78 | + pub zoneinfo: String, | |
| 79 | + /// Photo version from `im`. | |
| 80 | + pub picture_version: i64, | |
| 81 | +} | |
| 82 | + | |
| 83 | +const MEMBER_COLS: &str = "sub, email, name, im_admin, disabled, locale, locale_override, zoneinfo, \ | |
| 84 | + role, theme, ui, picture_version, first_seen_at, last_sign_in_at"; | |
| 85 | + | |
| 86 | +fn map_member(row: &turso::Row) -> Result<Member> { | |
| 87 | + let role_text = col_text(row, 8)?; | |
| 88 | + let role = Role::parse(&role_text) | |
| 89 | + .ok_or_else(|| Error::Database(format!("unknown stored role: {role_text}")))?; | |
| 90 | + Ok(Member { | |
| 91 | + sub: col_text(row, 0)?, | |
| 92 | + email: col_text(row, 1)?, | |
| 93 | + name: col_text(row, 2)?, | |
| 94 | + im_admin: col_bool(row, 3)?, | |
| 95 | + disabled: col_bool(row, 4)?, | |
| 96 | + locale: col_opt_text(row, 5)?, | |
| 97 | + locale_override: col_opt_text(row, 6)?, | |
| 98 | + zoneinfo: col_text(row, 7)?, | |
| 99 | + role, | |
| 100 | + theme: col_text(row, 9)?, | |
| 101 | + ui: col_text(row, 10)?, | |
| 102 | + picture_version: col_int(row, 11)?, | |
| 103 | + first_seen_at: col_text(row, 12)?, | |
| 104 | + last_sign_in_at: col_opt_text(row, 13)?, | |
| 105 | + }) | |
| 106 | +} | |
| 107 | + | |
| 108 | +/// Checks a directory record and returns the normalised copy to store. | |
| 109 | +fn validate(m: &DirectoryMember) -> Result<DirectoryMember> { | |
| 110 | + let sub = m.sub.trim(); | |
| 111 | + let email = m.email.trim(); | |
| 112 | + let name = m.name.trim(); | |
| 113 | + if sub.is_empty() || sub.len() > 64 { | |
| 114 | + return Err(Error::Invalid( | |
| 115 | + "member id must be 1 to 64 characters".into(), | |
| 116 | + )); | |
| 117 | + } | |
| 118 | + if email.is_empty() || email.chars().count() > EMAIL_MAX { | |
| 119 | + return Err(Error::Invalid( | |
| 120 | + "member email must be 1 to 320 characters".into(), | |
| 121 | + )); | |
| 122 | + } | |
| 123 | + if name.is_empty() || name.chars().count() > DISPLAY_NAME_MAX { | |
| 124 | + return Err(Error::Invalid( | |
| 125 | + "member name must be 1 to 100 characters".into(), | |
| 126 | + )); | |
| 127 | + } | |
| 128 | + if m.picture_version < 0 { | |
| 129 | + return Err(Error::Invalid( | |
| 130 | + "picture version must not be negative".into(), | |
| 131 | + )); | |
| 132 | + } | |
| 133 | + let zone = parse_zone(&m.zoneinfo)?; | |
| 134 | + let zoneinfo = zone | |
| 135 | + .iana_name() | |
| 136 | + .map(str::to_owned) | |
| 137 | + .unwrap_or_else(|| m.zoneinfo.trim().to_owned()); | |
| 138 | + Ok(DirectoryMember { | |
| 139 | + sub: sub.to_owned(), | |
| 140 | + email: email.to_owned(), | |
| 141 | + name: name.to_owned(), | |
| 142 | + im_admin: m.im_admin, | |
| 143 | + disabled: m.disabled, | |
| 144 | + locale: m.locale.clone().filter(|l| LOCALES.contains(&l.as_str())), | |
| 145 | + zoneinfo, | |
| 146 | + picture_version: m.picture_version, | |
| 147 | + }) | |
| 148 | +} | |
| 149 | + | |
| 150 | +async fn select_member(conn: &Connection, sub: &str) -> Result<Option<Member>> { | |
| 151 | + fetch_opt( | |
| 152 | + conn, | |
| 153 | + &format!("SELECT {MEMBER_COLS} FROM members WHERE sub = ?1"), | |
| 154 | + (sub.to_owned(),), | |
| 155 | + map_member, | |
| 156 | + ) | |
| 157 | + .await | |
| 158 | +} | |
| 159 | + | |
| 160 | +/// Removes a member's assignments and pending (unsent) reminders, inside `tx`. | |
| 161 | +async fn drop_assignments(tx: &Transaction<'_>, sub: &str) -> Result<()> { | |
| 162 | + tx.execute( | |
| 163 | + "DELETE FROM task_assignees WHERE sub = ?1", | |
| 164 | + (sub.to_owned(),), | |
| 165 | + ) | |
| 166 | + .await | |
| 167 | + .map_err(db_err)?; | |
| 168 | + tx.execute( | |
| 169 | + "DELETE FROM reminders WHERE sub = ?1 AND sent_at IS NULL", | |
| 170 | + (sub.to_owned(),), | |
| 171 | + ) | |
| 172 | + .await | |
| 173 | + .map_err(db_err)?; | |
| 174 | + Ok(()) | |
| 175 | +} | |
| 176 | + | |
| 177 | +impl Store { | |
| 178 | + /// Creates or refreshes a member from the directory. A new member gets `default_role`; an | |
| 179 | + /// existing member keeps their role and preferences. Returns the stored row. | |
| 180 | + pub async fn apply_directory_member( | |
| 181 | + &self, | |
| 182 | + member: &DirectoryMember, | |
| 183 | + default_role: Role, | |
| 184 | + ) -> Result<Member> { | |
| 185 | + self.upsert_member(member, default_role, false).await | |
| 186 | + } | |
| 187 | + | |
| 188 | + /// Creates or refreshes a member at sign-in (from the ID token claims) and stamps the sign-in time. | |
| 189 | + pub async fn upsert_from_claims( | |
| 190 | + &self, | |
| 191 | + member: &DirectoryMember, | |
| 192 | + default_role: Role, | |
| 193 | + ) -> Result<Member> { | |
| 194 | + self.upsert_member(member, default_role, true).await | |
| 195 | + } | |
| 196 | + | |
| 197 | + async fn upsert_member( | |
| 198 | + &self, | |
| 199 | + member: &DirectoryMember, | |
| 200 | + default_role: Role, | |
| 201 | + signed_in: bool, | |
| 202 | + ) -> Result<Member> { | |
| 203 | + let m = validate(member)?; | |
| 204 | + let now = now_stamp(); | |
| 205 | + let conn = self.inner.conn.lock().await; | |
| 206 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 207 | + let outcome: Result<Member> = async { | |
| 208 | + tx.execute( | |
| 209 | + "INSERT INTO members (sub, email, name, im_admin, disabled, locale, zoneinfo, \ | |
| 210 | + picture_version, im_updated_at, role, first_seen_at) \ | |
| 211 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?9) \ | |
| 212 | + ON CONFLICT(sub) DO UPDATE SET email = excluded.email, name = excluded.name, \ | |
| 213 | + im_admin = excluded.im_admin, disabled = excluded.disabled, \ | |
| 214 | + locale = excluded.locale, zoneinfo = excluded.zoneinfo, \ | |
| 215 | + picture_version = excluded.picture_version, im_updated_at = excluded.im_updated_at", | |
| 216 | + ( | |
| 217 | + m.sub.clone(), | |
| 218 | + m.email.clone(), | |
| 219 | + m.name.clone(), | |
| 220 | + i64::from(m.im_admin), | |
| 221 | + i64::from(m.disabled), | |
| 222 | + m.locale.clone(), | |
| 223 | + m.zoneinfo.clone(), | |
| 224 | + m.picture_version, | |
| 225 | + now.clone(), | |
| 226 | + default_role.as_str(), | |
| 227 | + ), | |
| 228 | + ) | |
| 229 | + .await | |
| 230 | + .map_err(db_err)?; | |
| 231 | + if signed_in { | |
| 232 | + tx.execute( | |
| 233 | + "UPDATE members SET last_sign_in_at = ?2 WHERE sub = ?1", | |
| 234 | + (m.sub.clone(), now.clone()), | |
| 235 | + ) | |
| 236 | + .await | |
| 237 | + .map_err(db_err)?; | |
| 238 | + } | |
| 239 | + select_member(&tx, &m.sub) | |
| 240 | + .await? | |
| 241 | + .ok_or_else(|| Error::Database("member vanished after upsert".into())) | |
| 242 | + } | |
| 243 | + .await; | |
| 244 | + finish(tx, outcome).await | |
| 245 | + } | |
| 246 | + | |
| 247 | + /// Marks a member as deleted in the directory: disabled, role `none`. Their assignments and pending | |
| 248 | + /// reminders are removed in the same transaction. Unknown members are `NotFound`. | |
| 249 | + pub async fn mark_deleted(&self, sub: &str) -> Result<()> { | |
| 250 | + let conn = self.inner.conn.lock().await; | |
| 251 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 252 | + let outcome: Result<()> = async { | |
| 253 | + let changed = tx | |
| 254 | + .execute( | |
| 255 | + "UPDATE members SET disabled = 1, role = 'none' WHERE sub = ?1", | |
| 256 | + (sub.to_owned(),), | |
| 257 | + ) | |
| 258 | + .await | |
| 259 | + .map_err(db_err)?; | |
| 260 | + if changed == 0 { | |
| 261 | + return Err(Error::NotFound); | |
| 262 | + } | |
| 263 | + drop_assignments(&tx, sub).await | |
| 264 | + } | |
| 265 | + .await; | |
| 266 | + finish(tx, outcome).await | |
| 267 | + } | |
| 268 | + | |
| 269 | + /// One member by id, or `None`. | |
| 270 | + pub async fn member(&self, sub: &str) -> Result<Option<Member>> { | |
| 271 | + let conn = self.read_conn().await; | |
| 272 | + select_member(&conn, sub).await | |
| 273 | + } | |
| 274 | + | |
| 275 | + /// Every member, by name. | |
| 276 | + pub async fn list_members(&self) -> Result<Vec<Member>> { | |
| 277 | + let conn = self.read_conn().await; | |
| 278 | + fetch_all( | |
| 279 | + &conn, | |
| 280 | + &format!("SELECT {MEMBER_COLS} FROM members ORDER BY name COLLATE NOCASE, sub"), | |
| 281 | + (), | |
| 282 | + map_member, | |
| 283 | + ) | |
| 284 | + .await | |
| 285 | + } | |
| 286 | + | |
| 287 | + /// Sets a member's role. Refuses to remove the last active administrator: an administrator is a | |
| 288 | + /// member with role `admin` or the directory admin flag, who is not disabled. The check is part | |
| 289 | + /// of the same conditional UPDATE, so two demotions cannot both pass. | |
| 290 | + /// | |
| 291 | + /// Moving to `viewer` or `none` also removes the member's assignments and pending reminders. | |
| 292 | + pub async fn set_role(&self, sub: &str, role: Role) -> Result<()> { | |
| 293 | + let conn = self.inner.conn.lock().await; | |
| 294 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 295 | + let outcome: Result<()> = async { | |
| 296 | + let changed = tx | |
| 297 | + .execute( | |
| 298 | + "UPDATE members SET role = ?2 WHERE sub = ?1 AND (?2 = 'admin' OR EXISTS ( \ | |
| 299 | + SELECT 1 FROM members other WHERE other.sub <> ?1 AND other.disabled = 0 \ | |
| 300 | + AND (other.im_admin = 1 OR other.role = 'admin')))", | |
| 301 | + (sub.to_owned(), role.as_str()), | |
| 302 | + ) | |
| 303 | + .await | |
| 304 | + .map_err(db_err)?; | |
| 305 | + if changed == 0 { | |
| 306 | + if select_member(&tx, sub).await?.is_none() { | |
| 307 | + return Err(Error::NotFound); | |
| 308 | + } | |
| 309 | + return Err(Error::Conflict( | |
| 310 | + "the last administrator cannot be demoted".into(), | |
| 311 | + )); | |
| 312 | + } | |
| 313 | + if matches!(role, Role::Viewer | Role::NoAccess) { | |
| 314 | + drop_assignments(&tx, sub).await?; | |
| 315 | + } | |
| 316 | + Ok(()) | |
| 317 | + } | |
| 318 | + .await; | |
| 319 | + finish(tx, outcome).await | |
| 320 | + } | |
| 321 | + | |
| 322 | + /// Stores a member's own preferences. Values are checked here as well as by the schema, so the | |
| 323 | + /// user gets a message instead of a constraint error. | |
| 324 | + pub async fn set_preferences( | |
| 325 | + &self, | |
| 326 | + sub: &str, | |
| 327 | + theme: &str, | |
| 328 | + ui: &str, | |
| 329 | + locale_override: Option<&str>, | |
| 330 | + ) -> Result<()> { | |
| 331 | + if !THEMES.contains(&theme) { | |
| 332 | + return Err(Error::Invalid(format!("unknown theme: {theme}"))); | |
| 333 | + } | |
| 334 | + if !UI_STYLES.contains(&ui) { | |
| 335 | + return Err(Error::Invalid(format!("unknown layout: {ui}"))); | |
| 336 | + } | |
| 337 | + if let Some(locale) = locale_override.filter(|l| !LOCALES.contains(l)) { | |
| 338 | + return Err(Error::Invalid(format!("unknown language: {locale}"))); | |
| 339 | + } | |
| 340 | + let conn = self.inner.conn.lock().await; | |
| 341 | + let changed = conn | |
| 342 | + .execute( | |
| 343 | + "UPDATE members SET theme = ?2, ui = ?3, locale_override = ?4 WHERE sub = ?1", | |
| 344 | + ( | |
| 345 | + sub.to_owned(), | |
| 346 | + theme.to_owned(), | |
| 347 | + ui.to_owned(), | |
| 348 | + locale_override.map(str::to_owned), | |
| 349 | + ), | |
| 350 | + ) | |
| 351 | + .await | |
| 352 | + .map_err(db_err)?; | |
| 353 | + if changed == 0 { | |
| 354 | + return Err(Error::NotFound); | |
| 355 | + } | |
| 356 | + Ok(()) | |
| 357 | + } | |
| 358 | +} | |
| 359 | + | |
| 360 | +#[cfg(test)] | |
| 361 | +mod tests { | |
| 362 | + use super::*; | |
| 363 | + | |
| 364 | + #[test] | |
| 365 | + fn validation_normalises_zone_and_drops_unknown_locale() { | |
| 366 | + let raw = DirectoryMember { | |
| 367 | + sub: " u1 ".into(), | |
| 368 | + email: "a@example.com".into(), | |
| 369 | + name: " Ada ".into(), | |
| 370 | + im_admin: false, | |
| 371 | + disabled: false, | |
| 372 | + locale: Some("de".into()), | |
| 373 | + zoneinfo: "Europe/Istanbul".into(), | |
| 374 | + picture_version: 0, | |
| 375 | + }; | |
| 376 | + let v = validate(&raw).unwrap(); | |
| 377 | + assert_eq!(v.sub, "u1"); | |
| 378 | + assert_eq!(v.name, "Ada"); | |
| 379 | + assert_eq!(v.locale, None); | |
| 380 | + assert_eq!(v.zoneinfo, "Europe/Istanbul"); | |
| 381 | + let bad = DirectoryMember { | |
| 382 | + zoneinfo: "Mars/Base".into(), | |
| 383 | + ..raw | |
| 384 | + }; | |
| 385 | + assert!(validate(&bad).is_err()); | |
| 386 | + } | |
| 387 | + | |
| 388 | + #[tokio::test] | |
| 389 | + async fn last_administrator_cannot_be_demoted() { | |
| 390 | + let (_dir, store, _board) = crate::store::test_support::seeded().await; | |
| 391 | + // `ada` is the only admin, so she cannot step down; `bo` is a member and can be promoted. | |
| 392 | + assert!(matches!( | |
| 393 | + store.set_role("ada", Role::Viewer).await, | |
| 394 | + Err(Error::Conflict(_)) | |
| 395 | + )); | |
| 396 | + store.set_role("bo", Role::Admin).await.unwrap(); | |
| 397 | + store.set_role("ada", Role::Viewer).await.unwrap(); | |
| 398 | + assert_eq!( | |
| 399 | + store.member("ada").await.unwrap().unwrap().role, | |
| 400 | + Role::Viewer | |
| 401 | + ); | |
| 402 | + // Now `bo` is the last one. | |
| 403 | + assert!(matches!( | |
| 404 | + store.set_role("bo", Role::Member).await, | |
| 405 | + Err(Error::Conflict(_)) | |
| 406 | + )); | |
| 407 | + assert!(matches!( | |
| 408 | + store.set_role("nobody", Role::Member).await, | |
| 409 | + Err(Error::NotFound) | |
| 410 | + )); | |
| 411 | + } | |
| 412 | +} |
crates/iz-core/src/store/mod.rsmodified+80 -2
| @@ -1,21 +1,30 @@ | ||
| 1 | -//! Turso-backed storage. All metadata lives here. Only the settings functions exist so far; the | |
| 2 | -//! table modules come with the features that use them. | |
| 1 | +//! Turso-backed storage. All metadata lives here: members and sessions, the board (columns, tags), | |
| 2 | +//! tasks with their links, comments and activity. Each table group is a child module; this file has | |
| 3 | +//! the connections, the settings, and the helpers every module uses. | |
| 3 | 4 | //! |
| 4 | 5 | //! Connections: `conn` is the single writer. Every write, every transaction and every |
| 5 | 6 | //! read-then-write sequence runs on it behind its tokio mutex, so transactions never interleave. |
| 6 | 7 | //! `readers` is a small pool of `query_only` connections on the same database (WAL), so pure |
| 7 | 8 | //! SELECTs run in parallel with each other and with the writer. |
| 8 | 9 | |
| 10 | +pub mod activity; | |
| 11 | +pub mod board; | |
| 12 | +pub mod comments; | |
| 13 | +pub mod members; | |
| 9 | 14 | pub mod migrate; |
| 15 | +pub mod sessions; | |
| 10 | 16 | pub mod snapshot; |
| 17 | +pub mod tasks; | |
| 11 | 18 | |
| 12 | 19 | use std::path::Path; |
| 13 | 20 | use std::sync::Arc; |
| 14 | 21 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 15 | 22 | use std::time::Duration; |
| 16 | 23 | |
| 24 | +use time::OffsetDateTime; | |
| 17 | 25 | use tokio::sync::{Mutex, MutexGuard}; |
| 18 | 26 | use turso::{Builder, Connection, Database, IntoParams, Row, Value}; |
| 27 | +use ulid::Ulid; | |
| 19 | 28 | |
| 20 | 29 | use crate::error::{Error, Result}; |
| 21 | 30 | use crate::time::now_stamp; |
| @@ -214,6 +223,45 @@ where | ||
| 214 | 223 | } |
| 215 | 224 | } |
| 216 | 225 | |
| 226 | +/// A fresh ULID as text: 48 bits of millisecond time, then 80 random bits. Sorts by creation time. | |
| 227 | +pub fn new_id() -> String { | |
| 228 | + let millis = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000; | |
| 229 | + let millis = u64::try_from(millis).unwrap_or(0); | |
| 230 | + let mut buf = [0u8; 16]; | |
| 231 | + rand::fill(&mut buf); | |
| 232 | + let random = u128::from_le_bytes(buf) & ((1u128 << 80) - 1); | |
| 233 | + Ulid::from_parts(millis, random).to_string() | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// A nullable text column: `None` for NULL. | |
| 237 | +pub fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> { | |
| 238 | + match row.get_value(i).map_err(db_err)? { | |
| 239 | + Value::Null => Ok(None), | |
| 240 | + Value::Text(s) => Ok(Some(s)), | |
| 241 | + _ => Err(Error::Database(format!("column {i} is not text"))), | |
| 242 | + } | |
| 243 | +} | |
| 244 | + | |
| 245 | +/// A 0/1 integer column as a bool. Any other value is a database error. | |
| 246 | +pub fn col_bool(row: &Row, i: usize) -> Result<bool> { | |
| 247 | + match col_int(row, i)? { | |
| 248 | + 0 => Ok(false), | |
| 249 | + 1 => Ok(true), | |
| 250 | + other => Err(Error::Database(format!( | |
| 251 | + "column {i} is {other}, not 0 or 1" | |
| 252 | + ))), | |
| 253 | + } | |
| 254 | +} | |
| 255 | + | |
| 256 | +/// A REAL (floating point) column. Integers are accepted and widened, as SQLite allows either. | |
| 257 | +pub fn col_real(row: &Row, i: usize) -> Result<f64> { | |
| 258 | + match row.get_value(i).map_err(db_err)? { | |
| 259 | + Value::Real(f) => Ok(f), | |
| 260 | + Value::Integer(n) => Ok(n as f64), | |
| 261 | + _ => Err(Error::Database(format!("column {i} is not a number"))), | |
| 262 | + } | |
| 263 | +} | |
| 264 | + | |
| 217 | 265 | /// A text column. NULL and other types are a database error here; use a nullable reader for NULLs. |
| 218 | 266 | pub fn col_text(row: &Row, i: usize) -> Result<String> { |
| 219 | 267 | match row.get_value(i).map_err(db_err)? { |
| @@ -241,6 +289,36 @@ pub fn col_to_string(row: &Row, i: usize) -> Result<String> { | ||
| 241 | 289 | } |
| 242 | 290 | } |
| 243 | 291 | |
| 292 | +/// Test fixtures shared by the store modules: a fresh database in a temp dir, one board, and two members. | |
| 293 | +#[cfg(test)] | |
| 294 | +pub(crate) mod test_support { | |
| 295 | + use super::Store; | |
| 296 | + use super::members::DirectoryMember; | |
| 297 | + use crate::authz::Role; | |
| 298 | + | |
| 299 | + /// A store with a board and two members: `ada` (admin) and `bo` (member). Keep the returned temp dir | |
| 300 | + /// alive for as long as the store is used. | |
| 301 | + pub(crate) async fn seeded() -> (tempfile::TempDir, Store, String) { | |
| 302 | + let dir = tempfile::tempdir().unwrap(); | |
| 303 | + let store = Store::open(&dir.path().join("iz.db")).await.unwrap(); | |
| 304 | + let board = store.ensure_board("IZ").await.unwrap(); | |
| 305 | + for (sub, role) in [("ada", Role::Admin), ("bo", Role::Member)] { | |
| 306 | + let member = DirectoryMember { | |
| 307 | + sub: sub.into(), | |
| 308 | + email: format!("{sub}@example.com"), | |
| 309 | + name: sub.into(), | |
| 310 | + im_admin: false, | |
| 311 | + disabled: false, | |
| 312 | + locale: None, | |
| 313 | + zoneinfo: "UTC".into(), | |
| 314 | + picture_version: 0, | |
| 315 | + }; | |
| 316 | + store.apply_directory_member(&member, role).await.unwrap(); | |
| 317 | + } | |
| 318 | + (dir, store, board.id) | |
| 319 | + } | |
| 320 | +} | |
| 321 | + | |
| 244 | 322 | #[cfg(test)] |
| 245 | 323 | mod tests { |
| 246 | 324 | use super::*; |
crates/iz-core/src/store/sessions.rsadded+245 -0
| @@ -0,0 +1,245 @@ | ||
| 1 | +//! Local sessions (docs/contracts.md 2.4) and the replay guard for back-channel logout tokens. | |
| 2 | +//! | |
| 3 | +//! The cookie token is random; only its SHA-256 is stored, so a leaked table cannot be replayed. | |
| 4 | +//! A session is valid only while it is unexpired and its member is enabled and has a role other than | |
| 5 | +//! `none`. Lookups repeat those checks in SQL, so disabling a member takes effect on the next request | |
| 6 | +//! even if the back-channel message was lost. | |
| 7 | + | |
| 8 | +use std::time::Duration; | |
| 9 | + | |
| 10 | +use super::{col_opt_text, col_text, db_err, fetch_opt, new_id}; | |
| 11 | +use crate::error::{Error, Result}; | |
| 12 | +use crate::store::Store; | |
| 13 | +use crate::time::{now_stamp, stamp_after}; | |
| 14 | +use crate::token::{generate_token, hash_token}; | |
| 15 | + | |
| 16 | +/// A session as the web layer needs it after a lookup. | |
| 17 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 18 | +pub struct SessionRecord { | |
| 19 | + /// Session id (ULID). | |
| 20 | + pub id: String, | |
| 21 | + /// The member the session belongs to. | |
| 22 | + pub sub: String, | |
| 23 | + /// The per-session CSRF token that every state-changing form must carry. | |
| 24 | + pub csrf_token: String, | |
| 25 | + /// The im browser session id, used by back-channel logout. | |
| 26 | + pub sid: Option<String>, | |
| 27 | + /// UTC stamp after which the session is refused. | |
| 28 | + pub expires_at: String, | |
| 29 | + /// UTC stamp of the last request that used the session. | |
| 30 | + pub last_seen: String, | |
| 31 | +} | |
| 32 | + | |
| 33 | +/// A freshly created session. `token` goes into the cookie and is never stored. | |
| 34 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 35 | +pub struct IssuedSession { | |
| 36 | + /// Session id. | |
| 37 | + pub id: String, | |
| 38 | + /// Cookie value (43 characters). Shown once. | |
| 39 | + pub token: String, | |
| 40 | + /// CSRF token for forms in this session. | |
| 41 | + pub csrf_token: String, | |
| 42 | +} | |
| 43 | + | |
| 44 | +const SESSION_COLS: &str = "s.id, s.sub, s.csrf_token, s.sid, s.expires_at, s.last_seen"; | |
| 45 | + | |
| 46 | +fn map_session(row: &turso::Row) -> Result<SessionRecord> { | |
| 47 | + Ok(SessionRecord { | |
| 48 | + id: col_text(row, 0)?, | |
| 49 | + sub: col_text(row, 1)?, | |
| 50 | + csrf_token: col_text(row, 2)?, | |
| 51 | + sid: col_opt_text(row, 3)?, | |
| 52 | + expires_at: col_text(row, 4)?, | |
| 53 | + last_seen: col_text(row, 5)?, | |
| 54 | + }) | |
| 55 | +} | |
| 56 | + | |
| 57 | +impl Store { | |
| 58 | + /// Creates a session for `sub` that lasts `lifetime`. The member must be enabled and have a role | |
| 59 | + /// other than `none`; otherwise nothing is written and the result is `Forbidden`. | |
| 60 | + pub async fn create_session( | |
| 61 | + &self, | |
| 62 | + sub: &str, | |
| 63 | + sid: Option<&str>, | |
| 64 | + lifetime: Duration, | |
| 65 | + user_agent: Option<&str>, | |
| 66 | + ip: Option<&str>, | |
| 67 | + ) -> Result<IssuedSession> { | |
| 68 | + let token = generate_token(); | |
| 69 | + let csrf_token = generate_token(); | |
| 70 | + let id = new_id(); | |
| 71 | + let now = now_stamp(); | |
| 72 | + let conn = self.inner.conn.lock().await; | |
| 73 | + let changed = conn | |
| 74 | + .execute( | |
| 75 | + "INSERT INTO sessions (id, sub, token_hash, csrf_token, sid, created_at, expires_at, \ | |
| 76 | + last_seen, user_agent, ip) \ | |
| 77 | + SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?6, ?8, ?9 FROM members \ | |
| 78 | + WHERE sub = ?2 AND disabled = 0 AND role <> 'none'", | |
| 79 | + ( | |
| 80 | + id.clone(), | |
| 81 | + sub.to_owned(), | |
| 82 | + hash_token(&token), | |
| 83 | + csrf_token.clone(), | |
| 84 | + sid.map(str::to_owned), | |
| 85 | + now, | |
| 86 | + stamp_after(lifetime), | |
| 87 | + user_agent.map(str::to_owned), | |
| 88 | + ip.map(str::to_owned), | |
| 89 | + ), | |
| 90 | + ) | |
| 91 | + .await | |
| 92 | + .map_err(db_err)?; | |
| 93 | + if changed == 0 { | |
| 94 | + return Err(Error::Forbidden("this account cannot sign in".into())); | |
| 95 | + } | |
| 96 | + Ok(IssuedSession { | |
| 97 | + id, | |
| 98 | + token, | |
| 99 | + csrf_token, | |
| 100 | + }) | |
| 101 | + } | |
| 102 | + | |
| 103 | + /// The live session for a cookie token: unexpired, member enabled, role not `none`. `None` otherwise, | |
| 104 | + /// with no hint about which check failed. | |
| 105 | + pub async fn session_by_token(&self, token: &str) -> Result<Option<SessionRecord>> { | |
| 106 | + let conn = self.read_conn().await; | |
| 107 | + fetch_opt( | |
| 108 | + &conn, | |
| 109 | + &format!( | |
| 110 | + "SELECT {SESSION_COLS} FROM sessions s JOIN members m ON m.sub = s.sub \ | |
| 111 | + WHERE s.token_hash = ?1 AND s.expires_at > ?2 AND m.disabled = 0 AND m.role <> 'none'" | |
| 112 | + ), | |
| 113 | + (hash_token(token), now_stamp()), | |
| 114 | + map_session, | |
| 115 | + ) | |
| 116 | + .await | |
| 117 | + } | |
| 118 | + | |
| 119 | + /// Records that a session was used now. | |
| 120 | + pub async fn touch_session(&self, id: &str) -> Result<()> { | |
| 121 | + let conn = self.inner.conn.lock().await; | |
| 122 | + conn.execute( | |
| 123 | + "UPDATE sessions SET last_seen = ?2 WHERE id = ?1", | |
| 124 | + (id.to_owned(), now_stamp()), | |
| 125 | + ) | |
| 126 | + .await | |
| 127 | + .map_err(db_err)?; | |
| 128 | + Ok(()) | |
| 129 | + } | |
| 130 | + | |
| 131 | + /// Deletes one session. Returns whether a row was removed. | |
| 132 | + pub async fn delete_session(&self, id: &str) -> Result<bool> { | |
| 133 | + let conn = self.inner.conn.lock().await; | |
| 134 | + let removed = conn | |
| 135 | + .execute("DELETE FROM sessions WHERE id = ?1", (id.to_owned(),)) | |
| 136 | + .await | |
| 137 | + .map_err(db_err)?; | |
| 138 | + Ok(removed > 0) | |
| 139 | + } | |
| 140 | + | |
| 141 | + /// Deletes every session that belongs to the im browser session `sid` (back-channel logout). | |
| 142 | + /// Returns how many were removed. | |
| 143 | + pub async fn delete_sessions_by_sid(&self, sid: &str) -> Result<u64> { | |
| 144 | + let conn = self.inner.conn.lock().await; | |
| 145 | + conn.execute("DELETE FROM sessions WHERE sid = ?1", (sid.to_owned(),)) | |
| 146 | + .await | |
| 147 | + .map_err(db_err) | |
| 148 | + } | |
| 149 | + | |
| 150 | + /// Deletes every session of one member (disabled, deleted, or password changed). Returns the count. | |
| 151 | + pub async fn delete_sessions_by_sub(&self, sub: &str) -> Result<u64> { | |
| 152 | + let conn = self.inner.conn.lock().await; | |
| 153 | + conn.execute("DELETE FROM sessions WHERE sub = ?1", (sub.to_owned(),)) | |
| 154 | + .await | |
| 155 | + .map_err(db_err) | |
| 156 | + } | |
| 157 | + | |
| 158 | + /// Deletes sessions whose expiry has passed. Returns the count. | |
| 159 | + pub async fn sweep_sessions(&self) -> Result<u64> { | |
| 160 | + let conn = self.inner.conn.lock().await; | |
| 161 | + conn.execute( | |
| 162 | + "DELETE FROM sessions WHERE expires_at <= ?1", | |
| 163 | + (now_stamp(),), | |
| 164 | + ) | |
| 165 | + .await | |
| 166 | + .map_err(db_err) | |
| 167 | + } | |
| 168 | + | |
| 169 | + /// Records a logout-token id. Returns `true` when the id was already recorded (a replay, which the | |
| 170 | + /// caller must refuse) and `false` when this is its first use. The record lives for `lifetime`. | |
| 171 | + pub async fn seen_jti(&self, jti: &str, lifetime: Duration) -> Result<bool> { | |
| 172 | + let conn = self.inner.conn.lock().await; | |
| 173 | + let inserted = conn | |
| 174 | + .execute( | |
| 175 | + "INSERT INTO seen_logout_jti (jti, expires_at) VALUES (?1, ?2) ON CONFLICT(jti) DO NOTHING", | |
| 176 | + (jti.to_owned(), stamp_after(lifetime)), | |
| 177 | + ) | |
| 178 | + .await | |
| 179 | + .map_err(db_err)?; | |
| 180 | + Ok(inserted == 0) | |
| 181 | + } | |
| 182 | + | |
| 183 | + /// Deletes replay records whose lifetime has passed. Returns the count. | |
| 184 | + pub async fn sweep_jti(&self) -> Result<u64> { | |
| 185 | + let conn = self.inner.conn.lock().await; | |
| 186 | + conn.execute( | |
| 187 | + "DELETE FROM seen_logout_jti WHERE expires_at <= ?1", | |
| 188 | + (now_stamp(),), | |
| 189 | + ) | |
| 190 | + .await | |
| 191 | + .map_err(db_err) | |
| 192 | + } | |
| 193 | +} | |
| 194 | + | |
| 195 | +#[cfg(test)] | |
| 196 | +mod tests { | |
| 197 | + use super::*; | |
| 198 | + use crate::store::test_support::seeded; | |
| 199 | + | |
| 200 | + #[tokio::test] | |
| 201 | + async fn sessions_follow_member_state_and_jti_is_single_use() { | |
| 202 | + let (_dir, store, _board) = seeded().await; | |
| 203 | + let issued = store | |
| 204 | + .create_session("bo", Some("sid-1"), Duration::from_secs(3600), None, None) | |
| 205 | + .await | |
| 206 | + .unwrap(); | |
| 207 | + let found = store | |
| 208 | + .session_by_token(&issued.token) | |
| 209 | + .await | |
| 210 | + .unwrap() | |
| 211 | + .unwrap(); | |
| 212 | + assert_eq!(found.sub, "bo"); | |
| 213 | + assert_eq!(found.csrf_token, issued.csrf_token); | |
| 214 | + // Back-channel logout by sid removes the session. | |
| 215 | + assert_eq!(store.delete_sessions_by_sid("sid-1").await.unwrap(), 1); | |
| 216 | + assert!( | |
| 217 | + store | |
| 218 | + .session_by_token(&issued.token) | |
| 219 | + .await | |
| 220 | + .unwrap() | |
| 221 | + .is_none() | |
| 222 | + ); | |
| 223 | + // A member with role none cannot start a session at all. | |
| 224 | + store.mark_deleted("bo").await.unwrap(); | |
| 225 | + assert!(matches!( | |
| 226 | + store | |
| 227 | + .create_session("bo", None, Duration::from_secs(60), None, None) | |
| 228 | + .await, | |
| 229 | + Err(Error::Forbidden(_)) | |
| 230 | + )); | |
| 231 | + // A logout token id is accepted once; the replay is reported. | |
| 232 | + assert!( | |
| 233 | + !store | |
| 234 | + .seen_jti("jti-1", Duration::from_secs(600)) | |
| 235 | + .await | |
| 236 | + .unwrap() | |
| 237 | + ); | |
| 238 | + assert!( | |
| 239 | + store | |
| 240 | + .seen_jti("jti-1", Duration::from_secs(600)) | |
| 241 | + .await | |
| 242 | + .unwrap() | |
| 243 | + ); | |
| 244 | + } | |
| 245 | +} |
crates/iz-core/src/store/tasks.rsadded+1585 -0
| @@ -0,0 +1,1585 @@ | ||
| 1 | +//! Tasks: creation, edits, moves through columns, deletion, assignees, one level of subtasks, | |
| 2 | +//! dependencies, and the board and task reads. | |
| 3 | +//! | |
| 4 | +//! Every write that touches more than one row runs in one transaction with its activity rows and, | |
| 5 | +//! for a move, its transition row. Board scope is part of every `WHERE` (`board_id = ?`), so a task id | |
| 6 | +//! from another board is simply not found. Reminders (inventory 2.4) are rebuilt inside the same | |
| 7 | +//! transaction whenever the meeting time, the assignees, the done state or the deletion changes. | |
| 8 | + | |
| 9 | +use std::collections::{HashMap, HashSet}; | |
| 10 | + | |
| 11 | +use jiff::Timestamp; | |
| 12 | +use jiff::civil::Date; | |
| 13 | +use jiff::tz::TimeZone; | |
| 14 | +use turso::Connection; | |
| 15 | +use turso::transaction::Transaction; | |
| 16 | + | |
| 17 | +use super::activity::{self, NewActivity}; | |
| 18 | +use super::board::{Column, Tag, column_in, live_columns}; | |
| 19 | +use super::{ | |
| 20 | + col_int, col_opt_text, col_real, col_text, db_err, fetch_all, fetch_opt, finish, new_id, | |
| 21 | +}; | |
| 22 | +use crate::board::{fold_for_search, format_key, is_overdue, position_between, would_cycle}; | |
| 23 | +use crate::clock::{reminder_due, timestamp_of}; | |
| 24 | +use crate::error::{Error, Result}; | |
| 25 | +use crate::limits::{DESCRIPTION_MAX, TITLE_MAX}; | |
| 26 | +use crate::store::Store; | |
| 27 | +use crate::time::now_stamp; | |
| 28 | + | |
| 29 | +/// A task row as read back. Deadline and meeting are typed; the rest is text or numbers. | |
| 30 | +#[derive(Debug, Clone, PartialEq)] | |
| 31 | +pub struct Task { | |
| 32 | + /// Task id (ULID). | |
| 33 | + pub id: String, | |
| 34 | + /// Board the task belongs to. | |
| 35 | + pub board_id: String, | |
| 36 | + /// Readable key `PREFIX-n`, unique per board, never reused. | |
| 37 | + pub key: String, | |
| 38 | + /// The parent task, for a subtask. | |
| 39 | + pub parent_id: Option<String>, | |
| 40 | + /// Title, 1 to 200 characters. | |
| 41 | + pub title: String, | |
| 42 | + /// Free text, at most 20 000 characters. | |
| 43 | + pub description: String, | |
| 44 | + /// The column the task is in. | |
| 45 | + pub column_id: String, | |
| 46 | + /// The project (tag) the task wears. | |
| 47 | + pub tag_id: String, | |
| 48 | + /// The deadline day, if any. | |
| 49 | + pub deadline: Option<Date>, | |
| 50 | + /// The meeting instant as a UTC stamp, if any. | |
| 51 | + pub meeting_at: Option<String>, | |
| 52 | + /// Order within the column. | |
| 53 | + pub position: f64, | |
| 54 | + /// Who created the task. | |
| 55 | + pub created_by: String, | |
| 56 | + /// UTC stamp. | |
| 57 | + pub created_at: String, | |
| 58 | + /// UTC stamp of the last change. | |
| 59 | + pub updated_at: String, | |
| 60 | + /// UTC stamp of entering the done column; cleared on leaving it. | |
| 61 | + pub done_at: Option<String>, | |
| 62 | + /// UTC stamp of deletion (soft delete). Deleted tasks are hidden everywhere. | |
| 63 | + pub deleted_at: Option<String>, | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// A person assigned to a task. | |
| 67 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 68 | +pub struct Assignee { | |
| 69 | + /// The member's id. | |
| 70 | + pub sub: String, | |
| 71 | + /// The member's display name. | |
| 72 | + pub name: String, | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// Which way a dependency link points, seen from the new task. | |
| 76 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 77 | +pub enum LinkDirection { | |
| 78 | + /// The new task waits for the other task. | |
| 79 | + BlockedBy, | |
| 80 | + /// The other task waits for the new task. | |
| 81 | + Blocks, | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// Everything needed to create a task. Deadline and meeting are already resolved (see `clock.rs`). | |
| 85 | +#[derive(Debug, Clone, PartialEq)] | |
| 86 | +pub struct NewTask { | |
| 87 | + /// Title (trimmed, 1 to 200 characters). | |
| 88 | + pub title: String, | |
| 89 | + /// Description (at most 20 000 characters). | |
| 90 | + pub description: String, | |
| 91 | + /// Column to place the task in. Must be live on this board. | |
| 92 | + pub column_id: String, | |
| 93 | + /// Project. Must belong to this board. | |
| 94 | + pub tag_id: String, | |
| 95 | + /// Deadline day. | |
| 96 | + pub deadline: Option<Date>, | |
| 97 | + /// Meeting instant (UTC stamp). | |
| 98 | + pub meeting_at: Option<String>, | |
| 99 | + /// Assignees. Each must be an enabled admin or member. | |
| 100 | + pub assignees: Vec<String>, | |
| 101 | + /// Parent task, for a subtask. Must be a live top-level task on this board. | |
| 102 | + pub parent_id: Option<String>, | |
| 103 | + /// Optional dependency link to another task of this board. | |
| 104 | + pub link: Option<(String, LinkDirection)>, | |
| 105 | +} | |
| 106 | + | |
| 107 | +/// The editable fields of a task. The form sends all of them, so each is replaced as a whole. | |
| 108 | +#[derive(Debug, Clone, PartialEq)] | |
| 109 | +pub struct TaskEdit { | |
| 110 | + /// New title. | |
| 111 | + pub title: String, | |
| 112 | + /// New description. | |
| 113 | + pub description: String, | |
| 114 | + /// New project. | |
| 115 | + pub tag_id: String, | |
| 116 | + /// New deadline day. | |
| 117 | + pub deadline: Option<Date>, | |
| 118 | + /// New meeting instant (UTC stamp). | |
| 119 | + pub meeting_at: Option<String>, | |
| 120 | +} | |
| 121 | + | |
| 122 | +/// The result of a move. Only `Moved` changes anything. | |
| 123 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 124 | +pub enum MoveOutcome { | |
| 125 | + /// The task is now in the target column. | |
| 126 | + Moved, | |
| 127 | + /// The task was already in the target column. | |
| 128 | + Unchanged, | |
| 129 | + /// The task is no longer in the column the client last saw; someone else moved it. | |
| 130 | + Stale, | |
| 131 | + /// The target is the done column and the task has subtasks that are not done. | |
| 132 | + SubtasksOpen, | |
| 133 | +} | |
| 134 | + | |
| 135 | +/// Sorting of the board's cards. | |
| 136 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | |
| 137 | +pub enum SortBy { | |
| 138 | + /// Earliest deadline first; tasks without a deadline last. | |
| 139 | + #[default] | |
| 140 | + Deadline, | |
| 141 | + /// Newest first. | |
| 142 | + Created, | |
| 143 | + /// Alphabetical by title, ignoring case and Turkish dotted/dotless i. | |
| 144 | + Title, | |
| 145 | +} | |
| 146 | + | |
| 147 | +/// Who a board filter means when it names an assignee. | |
| 148 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 149 | +pub enum AssigneeFilter { | |
| 150 | + /// Tasks with nobody assigned. | |
| 151 | + Nobody, | |
| 152 | + /// Tasks assigned to this member. | |
| 153 | + Member(String), | |
| 154 | +} | |
| 155 | + | |
| 156 | +/// Filters and sorting for the board. Every field is optional; the default shows everything. | |
| 157 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | |
| 158 | +pub struct BoardFilter { | |
| 159 | + /// Only this project. | |
| 160 | + pub tag_id: Option<String>, | |
| 161 | + /// Only this assignee (or nobody). | |
| 162 | + pub assignee: Option<AssigneeFilter>, | |
| 163 | + /// Text to search for in key, title and description (case and Turkish-i insensitive). | |
| 164 | + pub query: Option<String>, | |
| 165 | + /// Card order. | |
| 166 | + pub sort: SortBy, | |
| 167 | +} | |
| 168 | + | |
| 169 | +/// One card on the board. | |
| 170 | +#[derive(Debug, Clone, PartialEq)] | |
| 171 | +pub struct Card { | |
| 172 | + /// The task. | |
| 173 | + pub task: Task, | |
| 174 | + /// The project's name. | |
| 175 | + pub tag_name: String, | |
| 176 | + /// Not done, and waiting for a blocker that is not done. | |
| 177 | + pub blocked: bool, | |
| 178 | + /// Overdue for the viewer (see `board::is_overdue`). | |
| 179 | + pub overdue: bool, | |
| 180 | + /// Subtasks that are done. | |
| 181 | + pub subtasks_done: i64, | |
| 182 | + /// Subtasks in total (live ones). | |
| 183 | + pub subtasks_total: i64, | |
| 184 | + /// Live comments. | |
| 185 | + pub comments: i64, | |
| 186 | + /// Assignees, by name. | |
| 187 | + pub assignees: Vec<Assignee>, | |
| 188 | +} | |
| 189 | + | |
| 190 | +/// One column with its cards in order. | |
| 191 | +#[derive(Debug, Clone, PartialEq)] | |
| 192 | +pub struct ColumnCards { | |
| 193 | + /// The live column. | |
| 194 | + pub column: Column, | |
| 195 | + /// Its cards, sorted by the filter's order. | |
| 196 | + pub cards: Vec<Card>, | |
| 197 | +} | |
| 198 | + | |
| 199 | +/// The whole board for one viewer. | |
| 200 | +#[derive(Debug, Clone, PartialEq)] | |
| 201 | +pub struct BoardView { | |
| 202 | + /// Live columns in order. | |
| 203 | + pub columns: Vec<ColumnCards>, | |
| 204 | + /// Overdue cards among those shown. | |
| 205 | + pub overdue: usize, | |
| 206 | + /// Blocked cards among those shown. | |
| 207 | + pub blocked: usize, | |
| 208 | +} | |
| 209 | + | |
| 210 | +/// One task with its context, for the task modal. | |
| 211 | +#[derive(Debug, Clone, PartialEq)] | |
| 212 | +pub struct TaskDetail { | |
| 213 | + /// The task. | |
| 214 | + pub task: Task, | |
| 215 | + /// Its project. | |
| 216 | + pub tag: Tag, | |
| 217 | + /// Its assignees, by name. | |
| 218 | + pub assignees: Vec<Assignee>, | |
| 219 | + /// Its live subtasks, in position order. | |
| 220 | + pub subtasks: Vec<Task>, | |
| 221 | + /// Live tasks it waits for (uncleared links). | |
| 222 | + pub blocked_by: Vec<Task>, | |
| 223 | + /// Live tasks waiting for it (uncleared links). | |
| 224 | + pub blocks: Vec<Task>, | |
| 225 | +} | |
| 226 | + | |
| 227 | +const TASK_COLS: &str = "id, board_id, key, parent_id, title, description, column_id, tag_id, \ | |
| 228 | + deadline, meeting_at, position, created_by, created_at, updated_at, done_at, deleted_at"; | |
| 229 | + | |
| 230 | +/// The same columns qualified with the alias `t`, for joins. | |
| 231 | +const TASK_COLS_T: &str = "t.id, t.board_id, t.key, t.parent_id, t.title, t.description, t.column_id, \ | |
| 232 | + t.tag_id, t.deadline, t.meeting_at, t.position, t.created_by, t.created_at, t.updated_at, \ | |
| 233 | + t.done_at, t.deleted_at"; | |
| 234 | + | |
| 235 | +fn parse_date(text: &str) -> Result<Date> { | |
| 236 | + text.parse::<Date>() | |
| 237 | + .map_err(|e| Error::Database(format!("stored deadline is not a date: {e}"))) | |
| 238 | +} | |
| 239 | + | |
| 240 | +fn map_task(row: &turso::Row) -> Result<Task> { | |
| 241 | + let deadline = col_opt_text(row, 8)? | |
| 242 | + .as_deref() | |
| 243 | + .map(parse_date) | |
| 244 | + .transpose()?; | |
| 245 | + Ok(Task { | |
| 246 | + id: col_text(row, 0)?, | |
| 247 | + board_id: col_text(row, 1)?, | |
| 248 | + key: col_text(row, 2)?, | |
| 249 | + parent_id: col_opt_text(row, 3)?, | |
| 250 | + title: col_text(row, 4)?, | |
| 251 | + description: col_text(row, 5)?, | |
| 252 | + column_id: col_text(row, 6)?, | |
| 253 | + tag_id: col_text(row, 7)?, | |
| 254 | + deadline, | |
| 255 | + meeting_at: col_opt_text(row, 9)?, | |
| 256 | + position: col_real(row, 10)?, | |
| 257 | + created_by: col_text(row, 11)?, | |
| 258 | + created_at: col_text(row, 12)?, | |
| 259 | + updated_at: col_text(row, 13)?, | |
| 260 | + done_at: col_opt_text(row, 14)?, | |
| 261 | + deleted_at: col_opt_text(row, 15)?, | |
| 262 | + }) | |
| 263 | +} | |
| 264 | + | |
| 265 | +fn map_assignee(row: &turso::Row) -> Result<(String, Assignee)> { | |
| 266 | + Ok(( | |
| 267 | + col_text(row, 0)?, | |
| 268 | + Assignee { | |
| 269 | + sub: col_text(row, 1)?, | |
| 270 | + name: col_text(row, 2)?, | |
| 271 | + }, | |
| 272 | + )) | |
| 273 | +} | |
| 274 | + | |
| 275 | +fn clean_title(title: &str) -> Result<String> { | |
| 276 | + let title = title.trim(); | |
| 277 | + if title.is_empty() || title.chars().count() > TITLE_MAX { | |
| 278 | + return Err(Error::Invalid(format!( | |
| 279 | + "title must be 1 to {TITLE_MAX} characters" | |
| 280 | + ))); | |
| 281 | + } | |
| 282 | + Ok(title.to_owned()) | |
| 283 | +} | |
| 284 | + | |
| 285 | +fn clean_description(description: &str) -> Result<String> { | |
| 286 | + if description.chars().count() > DESCRIPTION_MAX { | |
| 287 | + return Err(Error::Invalid(format!( | |
| 288 | + "description must be at most {DESCRIPTION_MAX} characters" | |
| 289 | + ))); | |
| 290 | + } | |
| 291 | + Ok(description.to_owned()) | |
| 292 | +} | |
| 293 | + | |
| 294 | +/// Removes repeats while keeping the first occurrence of each id. | |
| 295 | +fn unique(ids: &[String]) -> Vec<String> { | |
| 296 | + let mut seen = HashSet::new(); | |
| 297 | + ids.iter() | |
| 298 | + .filter(|id| seen.insert(id.as_str())) | |
| 299 | + .cloned() | |
| 300 | + .collect() | |
| 301 | +} | |
| 302 | + | |
| 303 | +/// A live task of `board_id`, or `NotFound`. Deleted and foreign tasks are both `NotFound`. | |
| 304 | +async fn live_task(conn: &Connection, board_id: &str, task_id: &str) -> Result<Task> { | |
| 305 | + fetch_opt( | |
| 306 | + conn, | |
| 307 | + &format!( | |
| 308 | + "SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL" | |
| 309 | + ), | |
| 310 | + (task_id.to_owned(), board_id.to_owned()), | |
| 311 | + map_task, | |
| 312 | + ) | |
| 313 | + .await? | |
| 314 | + .ok_or(Error::NotFound) | |
| 315 | +} | |
| 316 | + | |
| 317 | +/// Any task of `board_id`, deleted or not. | |
| 318 | +async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result<Option<Task>> { | |
| 319 | + fetch_opt( | |
| 320 | + conn, | |
| 321 | + &format!("SELECT {TASK_COLS} FROM tasks WHERE id = ?1 AND board_id = ?2"), | |
| 322 | + (task_id.to_owned(), board_id.to_owned()), | |
| 323 | + map_task, | |
| 324 | + ) | |
| 325 | + .await | |
| 326 | +} | |
| 327 | + | |
| 328 | +/// Whether a member may be assigned: enabled, and role `admin` or `member`. | |
| 329 | +async fn assignable(conn: &Connection, sub: &str) -> Result<bool> { | |
| 330 | + let found = fetch_opt( | |
| 331 | + conn, | |
| 332 | + "SELECT 1 FROM members WHERE sub = ?1 AND disabled = 0 AND role IN ('admin', 'member')", | |
| 333 | + (sub.to_owned(),), | |
| 334 | + |row| col_int(row, 0), | |
| 335 | + ) | |
| 336 | + .await?; | |
| 337 | + Ok(found.is_some()) | |
| 338 | +} | |
| 339 | + | |
| 340 | +async fn tag_in_board(conn: &Connection, board_id: &str, tag_id: &str) -> Result<bool> { | |
| 341 | + let found = fetch_opt( | |
| 342 | + conn, | |
| 343 | + "SELECT 1 FROM tags WHERE id = ?1 AND board_id = ?2", | |
| 344 | + (tag_id.to_owned(), board_id.to_owned()), | |
| 345 | + |row| col_int(row, 0), | |
| 346 | + ) | |
| 347 | + .await?; | |
| 348 | + Ok(found.is_some()) | |
| 349 | +} | |
| 350 | + | |
| 351 | +/// Uncleared links between live tasks of the board, as `(blocked, blocking)`. | |
| 352 | +async fn live_edges(conn: &Connection, board_id: &str) -> Result<Vec<(String, String)>> { | |
| 353 | + fetch_all( | |
| 354 | + conn, | |
| 355 | + "SELECT d.blocked_id, d.blocking_id FROM dependencies d \ | |
| 356 | + JOIN tasks blocked ON blocked.id = d.blocked_id \ | |
| 357 | + JOIN tasks blocking ON blocking.id = d.blocking_id \ | |
| 358 | + WHERE blocked.board_id = ?1 AND d.cleared_at IS NULL \ | |
| 359 | + AND blocked.deleted_at IS NULL AND blocking.deleted_at IS NULL", | |
| 360 | + (board_id.to_owned(),), | |
| 361 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 362 | + ) | |
| 363 | + .await | |
| 364 | +} | |
| 365 | + | |
| 366 | +/// Position for a task appended to the end of a column: after the largest live position there. | |
| 367 | +async fn next_position(conn: &Connection, column_id: &str) -> Result<f64> { | |
| 368 | + let positions = fetch_all( | |
| 369 | + conn, | |
| 370 | + "SELECT position FROM tasks WHERE column_id = ?1 AND deleted_at IS NULL", | |
| 371 | + (column_id.to_owned(),), | |
| 372 | + |row| col_real(row, 0), | |
| 373 | + ) | |
| 374 | + .await?; | |
| 375 | + let last = positions.into_iter().reduce(f64::max); | |
| 376 | + Ok(position_between(last, None)) | |
| 377 | +} | |
| 378 | + | |
| 379 | +/// Appends a row to the transitions table. `from` is `None` for the first placement. | |
| 380 | +async fn record_transition( | |
| 381 | + tx: &Transaction<'_>, | |
| 382 | + task_id: &str, | |
| 383 | + from: Option<&str>, | |
| 384 | + to: &str, | |
| 385 | + actor: &str, | |
| 386 | +) -> Result<()> { | |
| 387 | + tx.execute( | |
| 388 | + "INSERT INTO transitions (id, task_id, from_column, to_column, actor, at) \ | |
| 389 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | |
| 390 | + ( | |
| 391 | + new_id(), | |
| 392 | + task_id.to_owned(), | |
| 393 | + from.map(str::to_owned), | |
| 394 | + to.to_owned(), | |
| 395 | + actor.to_owned(), | |
| 396 | + now_stamp(), | |
| 397 | + ), | |
| 398 | + ) | |
| 399 | + .await | |
| 400 | + .map_err(db_err)?; | |
| 401 | + Ok(()) | |
| 402 | +} | |
| 403 | + | |
| 404 | +/// Writes one task-scoped activity row. | |
| 405 | +async fn log( | |
| 406 | + tx: &Transaction<'_>, | |
| 407 | + task_id: &str, | |
| 408 | + actor: &str, | |
| 409 | + kind: &'static str, | |
| 410 | + subject: Option<&str>, | |
| 411 | + detail: serde_json::Value, | |
| 412 | +) -> Result<()> { | |
| 413 | + activity::record( | |
| 414 | + tx, | |
| 415 | + NewActivity { | |
| 416 | + task_id: Some(task_id), | |
| 417 | + actor: Some(actor), | |
| 418 | + subject, | |
| 419 | + kind, | |
| 420 | + detail, | |
| 421 | + }, | |
| 422 | + ) | |
| 423 | + .await | |
| 424 | +} | |
| 425 | + | |
| 426 | +/// Rebuilds the pending reminders of one task (inventory 2.4): one per assignee, due a fixed lead time | |
| 427 | +/// before the meeting. Sent reminders are kept. None are made when the task is done, deleted, has no | |
| 428 | +/// meeting, or its meeting is in the past. | |
| 429 | +async fn sync_reminders(tx: &Transaction<'_>, task_id: &str) -> Result<()> { | |
| 430 | + tx.execute( | |
| 431 | + "DELETE FROM reminders WHERE task_id = ?1 AND sent_at IS NULL", | |
| 432 | + (task_id.to_owned(),), | |
| 433 | + ) | |
| 434 | + .await | |
| 435 | + .map_err(db_err)?; | |
| 436 | + let state = fetch_opt( | |
| 437 | + tx, | |
| 438 | + "SELECT meeting_at, done_at, deleted_at FROM tasks WHERE id = ?1", | |
| 439 | + (task_id.to_owned(),), | |
| 440 | + |row| { | |
| 441 | + Ok(( | |
| 442 | + col_opt_text(row, 0)?, | |
| 443 | + col_opt_text(row, 1)?, | |
| 444 | + col_opt_text(row, 2)?, | |
| 445 | + )) | |
| 446 | + }, | |
| 447 | + ) | |
| 448 | + .await?; | |
| 449 | + let Some((Some(meeting), None, None)) = state else { | |
| 450 | + return Ok(()); | |
| 451 | + }; | |
| 452 | + let at = timestamp_of(&meeting)?; | |
| 453 | + if at <= Timestamp::now() { | |
| 454 | + return Ok(()); | |
| 455 | + } | |
| 456 | + let due = reminder_due(at)?; | |
| 457 | + tx.execute( | |
| 458 | + "INSERT INTO reminders (task_id, sub, due_at, sent_at) \ | |
| 459 | + SELECT a.task_id, a.sub, ?2, NULL FROM task_assignees a \ | |
| 460 | + WHERE a.task_id = ?1 AND EXISTS ( \ | |
| 461 | + SELECT 1 FROM members m WHERE m.sub = a.sub AND m.disabled = 0 AND m.role IN ('admin', 'member')) \ | |
| 462 | + ON CONFLICT(task_id, sub) DO NOTHING", | |
| 463 | + (task_id.to_owned(), due), | |
| 464 | + ) | |
| 465 | + .await | |
| 466 | + .map_err(db_err)?; | |
| 467 | + Ok(()) | |
| 468 | +} | |
| 469 | + | |
| 470 | +impl Store { | |
| 471 | + /// Creates a task with everything it starts with, in one transaction: the key (from the board's | |
| 472 | + /// counter, never reused), the placement, the assignees, the optional subtask parent and the optional | |
| 473 | + /// dependency link, with their activity rows and the first transition. Any refusal rolls all of it back, | |
| 474 | + /// so no half-made card is left behind. A link that would close a cycle is refused. | |
| 475 | + pub async fn create_task(&self, board_id: &str, new: NewTask, actor: &str) -> Result<Task> { | |
| 476 | + let title = clean_title(&new.title)?; | |
| 477 | + let description = clean_description(&new.description)?; | |
| 478 | + let assignees = unique(&new.assignees); | |
| 479 | + let conn = self.inner.conn.lock().await; | |
| 480 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 481 | + let outcome: Result<Task> = async { | |
| 482 | + let column = column_in(&tx, board_id, &new.column_id) | |
| 483 | + .await? | |
| 484 | + .filter(|c| c.deleted_at.is_none()) | |
| 485 | + .ok_or_else(|| Error::Invalid("that column does not exist".into()))?; | |
| 486 | + if !tag_in_board(&tx, board_id, &new.tag_id).await? { | |
| 487 | + return Err(Error::Invalid("that project does not exist".into())); | |
| 488 | + } | |
| 489 | + if let Some(parent) = &new.parent_id { | |
| 490 | + let row = task_row(&tx, board_id, parent) | |
| 491 | + .await? | |
| 492 | + .filter(|p| p.deleted_at.is_none()) | |
| 493 | + .ok_or_else(|| Error::Invalid("the parent task does not exist".into()))?; | |
| 494 | + if row.parent_id.is_some() { | |
| 495 | + return Err(Error::Invalid("subtasks may only be one level deep".into())); | |
| 496 | + } | |
| 497 | + } | |
| 498 | + for sub in &assignees { | |
| 499 | + if !assignable(&tx, sub).await? { | |
| 500 | + return Err(Error::Invalid("that person cannot be assigned".into())); | |
| 501 | + } | |
| 502 | + } | |
| 503 | + let (prefix, number) = fetch_opt( | |
| 504 | + &tx, | |
| 505 | + "SELECT key_prefix, next_task_number FROM boards WHERE id = ?1", | |
| 506 | + (board_id.to_owned(),), | |
| 507 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | |
| 508 | + ) | |
| 509 | + .await? | |
| 510 | + .ok_or(Error::NotFound)?; | |
| 511 | + tx.execute( | |
| 512 | + "UPDATE boards SET next_task_number = ?2 WHERE id = ?1", | |
| 513 | + (board_id.to_owned(), number + 1), | |
| 514 | + ) | |
| 515 | + .await | |
| 516 | + .map_err(db_err)?; | |
| 517 | + let key = format_key(&prefix, u64::try_from(number).unwrap_or(0)); | |
| 518 | + let id = new_id(); | |
| 519 | + let now = now_stamp(); | |
| 520 | + let done_at = column.is_done.then(|| now.clone()); | |
| 521 | + let position = next_position(&tx, &column.id).await?; | |
| 522 | + tx.execute( | |
| 523 | + "INSERT INTO tasks (id, board_id, key, parent_id, title, description, column_id, tag_id, \ | |
| 524 | + deadline, meeting_at, position, created_by, created_at, updated_at, done_at) \ | |
| 525 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?13, ?14)", | |
| 526 | + ( | |
| 527 | + id.clone(), | |
| 528 | + board_id.to_owned(), | |
| 529 | + key.clone(), | |
| 530 | + new.parent_id.clone(), | |
| 531 | + title.clone(), | |
| 532 | + description, | |
| 533 | + column.id.clone(), | |
| 534 | + new.tag_id.clone(), | |
| 535 | + new.deadline.map(|d| d.to_string()), | |
| 536 | + new.meeting_at.clone(), | |
| 537 | + position, | |
| 538 | + actor.to_owned(), | |
| 539 | + now, | |
| 540 | + done_at, | |
| 541 | + ), | |
| 542 | + ) | |
| 543 | + .await | |
| 544 | + .map_err(db_err)?; | |
| 545 | + if let Some((other, direction)) = &new.link { | |
| 546 | + if live_task(&tx, board_id, other).await.is_err() { | |
| 547 | + return Err(Error::Invalid("the linked task does not exist".into())); | |
| 548 | + } | |
| 549 | + let (blocked, blocking) = match direction { | |
| 550 | + LinkDirection::BlockedBy => (id.as_str(), other.as_str()), | |
| 551 | + LinkDirection::Blocks => (other.as_str(), id.as_str()), | |
| 552 | + }; | |
| 553 | + let edges = live_edges(&tx, board_id).await?; | |
| 554 | + let refs: Vec<(&str, &str)> = | |
| 555 | + edges.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect(); | |
| 556 | + if would_cycle(&refs, (blocked, blocking)) { | |
| 557 | + return Err(Error::Conflict("this link would make a dependency cycle".into())); | |
| 558 | + } | |
| 559 | + tx.execute( | |
| 560 | + "INSERT INTO dependencies (blocked_id, blocking_id, created_at) VALUES (?1, ?2, ?3)", | |
| 561 | + (blocked.to_owned(), blocking.to_owned(), now_stamp()), | |
| 562 | + ) | |
| 563 | + .await | |
| 564 | + .map_err(db_err)?; | |
| 565 | + let direction_text = match direction { | |
| 566 | + LinkDirection::BlockedBy => "blocked_by", | |
| 567 | + LinkDirection::Blocks => "blocks", | |
| 568 | + }; | |
| 569 | + log( | |
| 570 | + &tx, | |
| 571 | + &id, | |
| 572 | + actor, | |
| 573 | + "link_added", | |
| 574 | + None, | |
| 575 | + serde_json::json!({ "other": other, "direction": direction_text }), | |
| 576 | + ) | |
| 577 | + .await?; | |
| 578 | + } | |
| 579 | + for sub in &assignees { | |
| 580 | + tx.execute( | |
| 581 | + "INSERT INTO task_assignees (task_id, sub, assigned_at) VALUES (?1, ?2, ?3)", | |
| 582 | + (id.clone(), sub.clone(), now_stamp()), | |
| 583 | + ) | |
| 584 | + .await | |
| 585 | + .map_err(db_err)?; | |
| 586 | + log(&tx, &id, actor, "assigned", Some(sub), serde_json::json!({})).await?; | |
| 587 | + } | |
| 588 | + log( | |
| 589 | + &tx, | |
| 590 | + &id, | |
| 591 | + actor, | |
| 592 | + "task_created", | |
| 593 | + None, | |
| 594 | + serde_json::json!({ "key": key, "title": title }), | |
| 595 | + ) | |
| 596 | + .await?; | |
| 597 | + record_transition(&tx, &id, None, &column.id, actor).await?; | |
| 598 | + sync_reminders(&tx, &id).await?; | |
| 599 | + live_task(&tx, board_id, &id).await | |
| 600 | + } | |
| 601 | + .await; | |
| 602 | + finish(tx, outcome).await | |
| 603 | + } | |
| 604 | + | |
| 605 | + /// Edits a task's title, description, project, deadline and meeting time. Writes one activity row per | |
| 606 | + /// kind of change (`task_edited`, `tag_changed`, `deadline_set`, `deadline_cleared`, `clock_set`, | |
| 607 | + /// `clock_cleared`). Reminders are rebuilt when the meeting time changes. | |
| 608 | + pub async fn edit_task( | |
| 609 | + &self, | |
| 610 | + board_id: &str, | |
| 611 | + task_id: &str, | |
| 612 | + edit: TaskEdit, | |
| 613 | + actor: &str, | |
| 614 | + ) -> Result<Task> { | |
| 615 | + let title = clean_title(&edit.title)?; | |
| 616 | + let description = clean_description(&edit.description)?; | |
| 617 | + let conn = self.inner.conn.lock().await; | |
| 618 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 619 | + let outcome: Result<Task> = async { | |
| 620 | + let before = live_task(&tx, board_id, task_id).await?; | |
| 621 | + if !tag_in_board(&tx, board_id, &edit.tag_id).await? { | |
| 622 | + return Err(Error::Invalid("that project does not exist".into())); | |
| 623 | + } | |
| 624 | + let deadline = edit.deadline.map(|d| d.to_string()); | |
| 625 | + tx.execute( | |
| 626 | + "UPDATE tasks SET title = ?3, description = ?4, tag_id = ?5, deadline = ?6, meeting_at = ?7, \ | |
| 627 | + updated_at = ?8 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 628 | + ( | |
| 629 | + task_id.to_owned(), | |
| 630 | + board_id.to_owned(), | |
| 631 | + title.clone(), | |
| 632 | + description.clone(), | |
| 633 | + edit.tag_id.clone(), | |
| 634 | + deadline.clone(), | |
| 635 | + edit.meeting_at.clone(), | |
| 636 | + now_stamp(), | |
| 637 | + ), | |
| 638 | + ) | |
| 639 | + .await | |
| 640 | + .map_err(db_err)?; | |
| 641 | + if before.title != title { | |
| 642 | + log(&tx, task_id, actor, "task_edited", None, serde_json::json!({ "field": "title" })).await?; | |
| 643 | + } | |
| 644 | + if before.description != description { | |
| 645 | + log(&tx, task_id, actor, "task_edited", None, serde_json::json!({ "field": "description" })).await?; | |
| 646 | + } | |
| 647 | + if before.tag_id != edit.tag_id { | |
| 648 | + log( | |
| 649 | + &tx, | |
| 650 | + task_id, | |
| 651 | + actor, | |
| 652 | + "tag_changed", | |
| 653 | + None, | |
| 654 | + serde_json::json!({ "from": before.tag_id, "to": edit.tag_id }), | |
| 655 | + ) | |
| 656 | + .await?; | |
| 657 | + } | |
| 658 | + if before.deadline != edit.deadline { | |
| 659 | + match (before.deadline, edit.deadline) { | |
| 660 | + (_, None) => log(&tx, task_id, actor, "deadline_cleared", None, serde_json::json!({})).await?, | |
| 661 | + (_, Some(day)) => { | |
| 662 | + log(&tx, task_id, actor, "deadline_set", None, serde_json::json!({ "day": day.to_string() })).await? | |
| 663 | + } | |
| 664 | + } | |
| 665 | + } | |
| 666 | + if before.meeting_at != edit.meeting_at { | |
| 667 | + match edit.meeting_at.as_deref() { | |
| 668 | + None => log(&tx, task_id, actor, "clock_cleared", None, serde_json::json!({})).await?, | |
| 669 | + Some(at) => log(&tx, task_id, actor, "clock_set", None, serde_json::json!({ "at": at })).await?, | |
| 670 | + } | |
| 671 | + sync_reminders(&tx, task_id).await?; | |
| 672 | + } | |
| 673 | + live_task(&tx, board_id, task_id).await | |
| 674 | + } | |
| 675 | + .await; | |
| 676 | + finish(tx, outcome).await | |
| 677 | + } | |
| 678 | + | |
| 679 | + /// Moves a task to `to_column` if it is still in `expected_from`. Entering the done column stamps | |
| 680 | + /// `done_at` and is refused while subtasks are open; leaving it clears `done_at`. Each real move writes | |
| 681 | + /// one transition and one `task_moved` activity row. | |
| 682 | + pub async fn move_task( | |
| 683 | + &self, | |
| 684 | + board_id: &str, | |
| 685 | + task_id: &str, | |
| 686 | + expected_from: &str, | |
| 687 | + to_column: &str, | |
| 688 | + actor: &str, | |
| 689 | + ) -> Result<MoveOutcome> { | |
| 690 | + let conn = self.inner.conn.lock().await; | |
| 691 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 692 | + let outcome: Result<MoveOutcome> = async { | |
| 693 | + let task = live_task(&tx, board_id, task_id).await?; | |
| 694 | + let target = column_in(&tx, board_id, to_column) | |
| 695 | + .await? | |
| 696 | + .filter(|c| c.deleted_at.is_none()) | |
| 697 | + .ok_or_else(|| Error::Invalid("that column does not exist".into()))?; | |
| 698 | + if task.column_id != expected_from { | |
| 699 | + return Ok(MoveOutcome::Stale); | |
| 700 | + } | |
| 701 | + if task.column_id == target.id { | |
| 702 | + return Ok(MoveOutcome::Unchanged); | |
| 703 | + } | |
| 704 | + if target.is_done { | |
| 705 | + let open = fetch_opt( | |
| 706 | + &tx, | |
| 707 | + "SELECT COUNT(*) FROM tasks WHERE parent_id = ?1 AND deleted_at IS NULL AND done_at IS NULL", | |
| 708 | + (task_id.to_owned(),), | |
| 709 | + |row| col_int(row, 0), | |
| 710 | + ) | |
| 711 | + .await? | |
| 712 | + .unwrap_or(0); | |
| 713 | + if open > 0 { | |
| 714 | + return Ok(MoveOutcome::SubtasksOpen); | |
| 715 | + } | |
| 716 | + } | |
| 717 | + let position = next_position(&tx, &target.id).await?; | |
| 718 | + let now = now_stamp(); | |
| 719 | + let done_at = target.is_done.then(|| now.clone()); | |
| 720 | + tx.execute( | |
| 721 | + "UPDATE tasks SET column_id = ?3, position = ?4, done_at = ?5, updated_at = ?6 \ | |
| 722 | + WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 723 | + ( | |
| 724 | + task_id.to_owned(), | |
| 725 | + board_id.to_owned(), | |
| 726 | + target.id.clone(), | |
| 727 | + position, | |
| 728 | + done_at, | |
| 729 | + now, | |
| 730 | + ), | |
| 731 | + ) | |
| 732 | + .await | |
| 733 | + .map_err(db_err)?; | |
| 734 | + record_transition(&tx, task_id, Some(&task.column_id), &target.id, actor).await?; | |
| 735 | + log( | |
| 736 | + &tx, | |
| 737 | + task_id, | |
| 738 | + actor, | |
| 739 | + "task_moved", | |
| 740 | + None, | |
| 741 | + serde_json::json!({ "from": task.column_id, "to": target.id }), | |
| 742 | + ) | |
| 743 | + .await?; | |
| 744 | + if task.done_at.is_some() != target.is_done { | |
| 745 | + sync_reminders(&tx, task_id).await?; | |
| 746 | + } | |
| 747 | + Ok(MoveOutcome::Moved) | |
| 748 | + } | |
| 749 | + .await; | |
| 750 | + finish(tx, outcome).await | |
| 751 | + } | |
| 752 | + | |
| 753 | + /// Soft-deletes a task and its direct subtasks. Every live link that points at a deleted task is | |
| 754 | + /// cleared; the tasks that were waiting for a deleted blocker are returned (they are freed), and each | |
| 755 | + /// gets an `unblocked` activity row. Pending reminders of the deleted tasks are removed. | |
| 756 | + pub async fn delete_task( | |
| 757 | + &self, | |
| 758 | + board_id: &str, | |
| 759 | + task_id: &str, | |
| 760 | + actor: &str, | |
| 761 | + ) -> Result<Vec<String>> { | |
| 762 | + let conn = self.inner.conn.lock().await; | |
| 763 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 764 | + let outcome: Result<Vec<String>> = async { | |
| 765 | + live_task(&tx, board_id, task_id).await?; | |
| 766 | + let children = fetch_all( | |
| 767 | + &tx, | |
| 768 | + "SELECT id FROM tasks WHERE parent_id = ?1 AND board_id = ?2 AND deleted_at IS NULL ORDER BY position, id", | |
| 769 | + (task_id.to_owned(), board_id.to_owned()), | |
| 770 | + |row| col_text(row, 0), | |
| 771 | + ) | |
| 772 | + .await?; | |
| 773 | + let mut doomed = vec![task_id.to_owned()]; | |
| 774 | + doomed.extend(children); | |
| 775 | + let now = now_stamp(); | |
| 776 | + for id in &doomed { | |
| 777 | + tx.execute( | |
| 778 | + "UPDATE tasks SET deleted_at = ?3, updated_at = ?3 \ | |
| 779 | + WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 780 | + (id.clone(), board_id.to_owned(), now.clone()), | |
| 781 | + ) | |
| 782 | + .await | |
| 783 | + .map_err(db_err)?; | |
| 784 | + log(&tx, id, actor, "task_deleted", None, serde_json::json!({})).await?; | |
| 785 | + } | |
| 786 | + let doomed_set: HashSet<&str> = doomed.iter().map(String::as_str).collect(); | |
| 787 | + let mut edges: Vec<(String, String)> = Vec::new(); | |
| 788 | + for id in &doomed { | |
| 789 | + edges.extend(fetch_all( | |
| 790 | + &tx, | |
| 791 | + "SELECT blocked_id, blocking_id FROM dependencies \ | |
| 792 | + WHERE (blocked_id = ?1 OR blocking_id = ?1) AND cleared_at IS NULL", | |
| 793 | + (id.clone(),), | |
| 794 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 795 | + ) | |
| 796 | + .await?); | |
| 797 | + } | |
| 798 | + let mut freed = Vec::new(); | |
| 799 | + for (blocked, blocking) in unique_pairs(edges) { | |
| 800 | + tx.execute( | |
| 801 | + "UPDATE dependencies SET cleared_at = ?3 WHERE blocked_id = ?1 AND blocking_id = ?2", | |
| 802 | + (blocked.clone(), blocking.clone(), now.clone()), | |
| 803 | + ) | |
| 804 | + .await | |
| 805 | + .map_err(db_err)?; | |
| 806 | + if doomed_set.contains(blocking.as_str()) && !doomed_set.contains(blocked.as_str()) { | |
| 807 | + let still_live = fetch_opt( | |
| 808 | + &tx, | |
| 809 | + "SELECT id FROM tasks WHERE id = ?1 AND deleted_at IS NULL", | |
| 810 | + (blocked.clone(),), | |
| 811 | + |row| col_text(row, 0), | |
| 812 | + ) | |
| 813 | + .await?; | |
| 814 | + if still_live.is_some() { | |
| 815 | + log( | |
| 816 | + &tx, | |
| 817 | + &blocked, | |
| 818 | + actor, | |
| 819 | + "unblocked", | |
| 820 | + None, | |
| 821 | + serde_json::json!({ "blocker": blocking }), | |
| 822 | + ) | |
| 823 | + .await?; | |
| 824 | + freed.push(blocked); | |
| 825 | + } | |
| 826 | + } | |
| 827 | + } | |
| 828 | + for id in &doomed { | |
| 829 | + sync_reminders(&tx, id).await?; | |
| 830 | + } | |
| 831 | + Ok(unique(&freed)) | |
| 832 | + } | |
| 833 | + .await; | |
| 834 | + finish(tx, outcome).await | |
| 835 | + } | |
| 836 | + | |
| 837 | + /// Assigns members to a task, all or nothing: if any of them cannot be assigned, nothing changes. | |
| 838 | + pub async fn assign( | |
| 839 | + &self, | |
| 840 | + board_id: &str, | |
| 841 | + task_id: &str, | |
| 842 | + subs: &[String], | |
| 843 | + actor: &str, | |
| 844 | + ) -> Result<()> { | |
| 845 | + let subs = unique(subs); | |
| 846 | + let conn = self.inner.conn.lock().await; | |
| 847 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 848 | + let outcome: Result<()> = async { | |
| 849 | + live_task(&tx, board_id, task_id).await?; | |
| 850 | + for sub in &subs { | |
| 851 | + if !assignable(&tx, sub).await? { | |
| 852 | + return Err(Error::Invalid("that person cannot be assigned".into())); | |
| 853 | + } | |
| 854 | + } | |
| 855 | + for sub in &subs { | |
| 856 | + let added = tx | |
| 857 | + .execute( | |
| 858 | + "INSERT INTO task_assignees (task_id, sub, assigned_at) VALUES (?1, ?2, ?3) \ | |
| 859 | + ON CONFLICT(task_id, sub) DO NOTHING", | |
| 860 | + (task_id.to_owned(), sub.clone(), now_stamp()), | |
| 861 | + ) | |
| 862 | + .await | |
| 863 | + .map_err(db_err)?; | |
| 864 | + if added > 0 { | |
| 865 | + log(&tx, task_id, actor, "assigned", Some(sub), serde_json::json!({})).await?; | |
| 866 | + } | |
| 867 | + } | |
| 868 | + sync_reminders(&tx, task_id).await | |
| 869 | + } | |
| 870 | + .await; | |
| 871 | + finish(tx, outcome).await | |
| 872 | + } | |
| 873 | + | |
| 874 | + /// Removes assignees from a task. People who were not assigned are skipped without an error. | |
| 875 | + pub async fn unassign( | |
| 876 | + &self, | |
| 877 | + board_id: &str, | |
| 878 | + task_id: &str, | |
| 879 | + subs: &[String], | |
| 880 | + actor: &str, | |
| 881 | + ) -> Result<()> { | |
| 882 | + let subs = unique(subs); | |
| 883 | + let conn = self.inner.conn.lock().await; | |
| 884 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 885 | + let outcome: Result<()> = async { | |
| 886 | + live_task(&tx, board_id, task_id).await?; | |
| 887 | + for sub in &subs { | |
| 888 | + let removed = tx | |
| 889 | + .execute( | |
| 890 | + "DELETE FROM task_assignees WHERE task_id = ?1 AND sub = ?2", | |
| 891 | + (task_id.to_owned(), sub.clone()), | |
| 892 | + ) | |
| 893 | + .await | |
| 894 | + .map_err(db_err)?; | |
| 895 | + if removed > 0 { | |
| 896 | + log( | |
| 897 | + &tx, | |
| 898 | + task_id, | |
| 899 | + actor, | |
| 900 | + "unassigned", | |
| 901 | + Some(sub), | |
| 902 | + serde_json::json!({}), | |
| 903 | + ) | |
| 904 | + .await?; | |
| 905 | + } | |
| 906 | + } | |
| 907 | + sync_reminders(&tx, task_id).await | |
| 908 | + } | |
| 909 | + .await; | |
| 910 | + finish(tx, outcome).await | |
| 911 | + } | |
| 912 | + | |
| 913 | + /// Makes `task_id` a subtask of `parent_id`, or a top-level task when `parent_id` is `None`. One level | |
| 914 | + /// only: the parent must be top-level, and a task with subtasks of its own cannot become one. | |
| 915 | + pub async fn set_parent( | |
| 916 | + &self, | |
| 917 | + board_id: &str, | |
| 918 | + task_id: &str, | |
| 919 | + parent_id: Option<&str>, | |
| 920 | + actor: &str, | |
| 921 | + ) -> Result<()> { | |
| 922 | + let conn = self.inner.conn.lock().await; | |
| 923 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 924 | + let outcome: Result<()> = async { | |
| 925 | + let task = live_task(&tx, board_id, task_id).await?; | |
| 926 | + let new_parent = match parent_id { | |
| 927 | + None => None, | |
| 928 | + Some(p) => { | |
| 929 | + if p == task_id { | |
| 930 | + return Err(Error::Invalid("a task cannot be its own subtask".into())); | |
| 931 | + } | |
| 932 | + let parent = live_task(&tx, board_id, p) | |
| 933 | + .await | |
| 934 | + .map_err(|_| Error::Invalid("the parent task does not exist".into()))?; | |
| 935 | + if parent.parent_id.is_some() { | |
| 936 | + return Err(Error::Invalid("subtasks may only be one level deep".into())); | |
| 937 | + } | |
| 938 | + let children = fetch_opt( | |
| 939 | + &tx, | |
| 940 | + "SELECT COUNT(*) FROM tasks WHERE parent_id = ?1", | |
| 941 | + (task_id.to_owned(),), | |
| 942 | + |row| col_int(row, 0), | |
| 943 | + ) | |
| 944 | + .await? | |
| 945 | + .unwrap_or(0); | |
| 946 | + if children > 0 { | |
| 947 | + return Err(Error::Conflict( | |
| 948 | + "a task with subtasks cannot become a subtask".into(), | |
| 949 | + )); | |
| 950 | + } | |
| 951 | + Some(parent) | |
| 952 | + } | |
| 953 | + }; | |
| 954 | + tx.execute( | |
| 955 | + "UPDATE tasks SET parent_id = ?3, updated_at = ?4 WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL", | |
| 956 | + ( | |
| 957 | + task_id.to_owned(), | |
| 958 | + board_id.to_owned(), | |
| 959 | + new_parent.as_ref().map(|p| p.id.clone()), | |
| 960 | + now_stamp(), | |
| 961 | + ), | |
| 962 | + ) | |
| 963 | + .await | |
| 964 | + .map_err(db_err)?; | |
| 965 | + if task.parent_id.as_deref() != new_parent.as_ref().map(|p| p.id.as_str()) { | |
| 966 | + log( | |
| 967 | + &tx, | |
| 968 | + task_id, | |
| 969 | + actor, | |
| 970 | + "parent_changed", | |
| 971 | + None, | |
| 972 | + serde_json::json!({ "parent": new_parent.as_ref().map(|p| p.key.clone()) }), | |
| 973 | + ) | |
| 974 | + .await?; | |
| 975 | + } | |
| 976 | + Ok(()) | |
| 977 | + } | |
| 978 | + .await; | |
| 979 | + finish(tx, outcome).await | |
| 980 | + } | |
| 981 | + | |
| 982 | + /// Adds "`blocked` waits for `blocking`". Refused for self-links and for links that close a cycle over | |
| 983 | + /// live edges. Re-adding a cleared link reactivates it; adding a live one changes nothing. | |
| 984 | + pub async fn add_dependency( | |
| 985 | + &self, | |
| 986 | + board_id: &str, | |
| 987 | + blocked_id: &str, | |
| 988 | + blocking_id: &str, | |
| 989 | + actor: &str, | |
| 990 | + ) -> Result<()> { | |
| 991 | + if blocked_id == blocking_id { | |
| 992 | + return Err(Error::Invalid("a task cannot wait for itself".into())); | |
| 993 | + } | |
| 994 | + let conn = self.inner.conn.lock().await; | |
| 995 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 996 | + let outcome: Result<()> = async { | |
| 997 | + let blocked = live_task(&tx, board_id, blocked_id).await?; | |
| 998 | + let blocking = live_task(&tx, board_id, blocking_id).await?; | |
| 999 | + let existing = fetch_opt( | |
| 1000 | + &tx, | |
| 1001 | + "SELECT cleared_at FROM dependencies WHERE blocked_id = ?1 AND blocking_id = ?2", | |
| 1002 | + (blocked_id.to_owned(), blocking_id.to_owned()), | |
| 1003 | + |row| col_opt_text(row, 0), | |
| 1004 | + ) | |
| 1005 | + .await?; | |
| 1006 | + if existing.as_ref().is_some_and(Option::is_none) { | |
| 1007 | + return Ok(()); | |
| 1008 | + } | |
| 1009 | + let edges = live_edges(&tx, board_id).await?; | |
| 1010 | + let refs: Vec<(&str, &str)> = edges.iter().map(|(a, b)| (a.as_str(), b.as_str())).collect(); | |
| 1011 | + if would_cycle(&refs, (blocked_id, blocking_id)) { | |
| 1012 | + return Err(Error::Conflict("this link would make a dependency cycle".into())); | |
| 1013 | + } | |
| 1014 | + let now = now_stamp(); | |
| 1015 | + if existing.is_some() { | |
| 1016 | + tx.execute( | |
| 1017 | + "UPDATE dependencies SET cleared_at = NULL, created_at = ?3 \ | |
| 1018 | + WHERE blocked_id = ?1 AND blocking_id = ?2", | |
| 1019 | + (blocked_id.to_owned(), blocking_id.to_owned(), now), | |
| 1020 | + ) | |
| 1021 | + .await | |
| 1022 | + .map_err(db_err)?; | |
| 1023 | + } else { | |
| 1024 | + tx.execute( | |
| 1025 | + "INSERT INTO dependencies (blocked_id, blocking_id, created_at) VALUES (?1, ?2, ?3)", | |
| 1026 | + (blocked_id.to_owned(), blocking_id.to_owned(), now), | |
| 1027 | + ) | |
| 1028 | + .await | |
| 1029 | + .map_err(db_err)?; | |
| 1030 | + } | |
| 1031 | + log( | |
| 1032 | + &tx, | |
| 1033 | + blocked_id, | |
| 1034 | + actor, | |
| 1035 | + "link_added", | |
| 1036 | + None, | |
| 1037 | + serde_json::json!({ "blocking": blocking.key, "blocked": blocked.key }), | |
| 1038 | + ) | |
| 1039 | + .await | |
| 1040 | + } | |
| 1041 | + .await; | |
| 1042 | + finish(tx, outcome).await | |
| 1043 | + } | |
| 1044 | + | |
| 1045 | + /// Clears a dependency (soft: the row stays with `cleared_at`, and it stops counting). | |
| 1046 | + pub async fn clear_dependency( | |
| 1047 | + &self, | |
| 1048 | + board_id: &str, | |
| 1049 | + blocked_id: &str, | |
| 1050 | + blocking_id: &str, | |
| 1051 | + actor: &str, | |
| 1052 | + ) -> Result<()> { | |
| 1053 | + let conn = self.inner.conn.lock().await; | |
| 1054 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | |
| 1055 | + let outcome: Result<()> = async { | |
| 1056 | + let blocked = live_task(&tx, board_id, blocked_id).await?; | |
| 1057 | + let changed = tx | |
| 1058 | + .execute( | |
| 1059 | + "UPDATE dependencies SET cleared_at = ?3 WHERE blocked_id = ?1 AND blocking_id = ?2 \ | |
| 1060 | + AND cleared_at IS NULL", | |
| 1061 | + (blocked_id.to_owned(), blocking_id.to_owned(), now_stamp()), | |
| 1062 | + ) | |
| 1063 | + .await | |
| 1064 | + .map_err(db_err)?; | |
| 1065 | + if changed == 0 { | |
| 1066 | + return Err(Error::NotFound); | |
| 1067 | + } | |
| 1068 | + log( | |
| 1069 | + &tx, | |
| 1070 | + blocked_id, | |
| 1071 | + actor, | |
| 1072 | + "link_removed", | |
| 1073 | + None, | |
| 1074 | + serde_json::json!({ "blocked": blocked.key }), | |
| 1075 | + ) | |
| 1076 | + .await | |
| 1077 | + } | |
| 1078 | + .await; | |
| 1079 | + finish(tx, outcome).await | |
| 1080 | + } | |
| 1081 | + | |
| 1082 | + /// The board for one viewer: live columns with their top-level cards, after the filter and sort. | |
| 1083 | + /// Overdue uses `viewer_zone` for day-only deadlines. Blocked means not done with an uncleared blocker | |
| 1084 | + /// that is itself not done and not deleted. The search folds Turkish i (see `board::fold_for_search`). | |
| 1085 | + pub async fn board_view( | |
| 1086 | + &self, | |
| 1087 | + board_id: &str, | |
| 1088 | + filter: &BoardFilter, | |
| 1089 | + viewer_zone: &TimeZone, | |
| 1090 | + ) -> Result<BoardView> { | |
| 1091 | + let now = Timestamp::now(); | |
| 1092 | + let conn = self.read_conn().await; | |
| 1093 | + let columns = live_columns(&conn, board_id).await?; | |
| 1094 | + let tasks = fetch_all( | |
| 1095 | + &conn, | |
| 1096 | + &format!( | |
| 1097 | + "SELECT {TASK_COLS} FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL AND parent_id IS NULL" | |
| 1098 | + ), | |
| 1099 | + (board_id.to_owned(),), | |
| 1100 | + map_task, | |
| 1101 | + ) | |
| 1102 | + .await?; | |
| 1103 | + let tags: HashMap<String, String> = fetch_all( | |
| 1104 | + &conn, | |
| 1105 | + "SELECT id, name FROM tags WHERE board_id = ?1", | |
| 1106 | + (board_id.to_owned(),), | |
| 1107 | + |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), | |
| 1108 | + ) | |
| 1109 | + .await? | |
| 1110 | + .into_iter() | |
| 1111 | + .collect(); | |
| 1112 | + let mut assignees: HashMap<String, Vec<Assignee>> = HashMap::new(); | |
| 1113 | + for (task_id, assignee) in fetch_all( | |
| 1114 | + &conn, | |
| 1115 | + "SELECT a.task_id, m.sub, m.name FROM task_assignees a \ | |
| 1116 | + JOIN tasks t ON t.id = a.task_id JOIN members m ON m.sub = a.sub \ | |
| 1117 | + WHERE t.board_id = ?1 AND t.deleted_at IS NULL ORDER BY m.name, m.sub", | |
| 1118 | + (board_id.to_owned(),), | |
| 1119 | + map_assignee, | |
| 1120 | + ) | |
| 1121 | + .await? | |
| 1122 | + { | |
| 1123 | + assignees.entry(task_id).or_default().push(assignee); | |
| 1124 | + } | |
| 1125 | + let mut subtask_counts: HashMap<String, (i64, i64)> = HashMap::new(); | |
| 1126 | + for (parent, total, done) in fetch_all( | |
| 1127 | + &conn, | |
| 1128 | + "SELECT parent_id, COUNT(*), COALESCE(SUM(CASE WHEN done_at IS NULL THEN 0 ELSE 1 END), 0) \ | |
| 1129 | + FROM tasks WHERE board_id = ?1 AND deleted_at IS NULL AND parent_id IS NOT NULL GROUP BY parent_id", | |
| 1130 | + (board_id.to_owned(),), | |
| 1131 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?, col_int(row, 2)?)), | |
| 1132 | + ) | |
| 1133 | + .await? | |
| 1134 | + { | |
| 1135 | + subtask_counts.insert(parent, (done, total)); | |
| 1136 | + } | |
| 1137 | + let comment_counts: HashMap<String, i64> = fetch_all( | |
| 1138 | + &conn, | |
| 1139 | + "SELECT c.task_id, COUNT(*) FROM comments c JOIN tasks t ON t.id = c.task_id \ | |
| 1140 | + WHERE t.board_id = ?1 AND c.deleted_at IS NULL GROUP BY c.task_id", | |
| 1141 | + (board_id.to_owned(),), | |
| 1142 | + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), | |
| 1143 | + ) | |
| 1144 | + .await? | |
| 1145 | + .into_iter() | |
| 1146 | + .collect(); | |
| 1147 | + let blocked: HashSet<String> = fetch_all( | |
| 1148 | + &conn, | |
| 1149 | + "SELECT d.blocked_id FROM dependencies d \ | |
| 1150 | + JOIN tasks t ON t.id = d.blocked_id JOIN tasks b ON b.id = d.blocking_id \ | |
| 1151 | + WHERE t.board_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL \ | |
| 1152 | + AND b.deleted_at IS NULL AND b.done_at IS NULL", | |
| 1153 | + (board_id.to_owned(),), | |
| 1154 | + |row| col_text(row, 0), | |
| 1155 | + ) | |
| 1156 | + .await? | |
| 1157 | + .into_iter() | |
| 1158 | + .collect(); | |
| 1159 | + drop(conn); | |
| 1160 | + | |
| 1161 | + let query = filter | |
| 1162 | + .query | |
| 1163 | + .as_deref() | |
| 1164 | + .map(str::trim) | |
| 1165 | + .filter(|q| !q.is_empty()) | |
| 1166 | + .map(fold_for_search); | |
| 1167 | + let mut cards = Vec::new(); | |
| 1168 | + for task in tasks { | |
| 1169 | + if filter.tag_id.as_deref().is_some_and(|t| t != task.tag_id) { | |
| 1170 | + continue; | |
| 1171 | + } | |
| 1172 | + let task_assignees = assignees.get(&task.id).cloned().unwrap_or_default(); | |
| 1173 | + match &filter.assignee { | |
| 1174 | + Some(AssigneeFilter::Nobody) if !task_assignees.is_empty() => continue, | |
| 1175 | + Some(AssigneeFilter::Member(sub)) | |
| 1176 | + if !task_assignees.iter().any(|a| &a.sub == sub) => | |
| 1177 | + { | |
| 1178 | + continue; | |
| 1179 | + } | |
| 1180 | + _ => {} | |
| 1181 | + } | |
| 1182 | + if let Some(q) = &query { | |
| 1183 | + let hit = fold_for_search(&task.key).contains(q.as_str()) | |
| 1184 | + || fold_for_search(&task.title).contains(q.as_str()) | |
| 1185 | + || fold_for_search(&task.description).contains(q.as_str()); | |
| 1186 | + if !hit { | |
| 1187 | + continue; | |
| 1188 | + } | |
| 1189 | + } | |
| 1190 | + let done = task.done_at.is_some(); | |
| 1191 | + let meeting = task.meeting_at.as_deref().map(timestamp_of).transpose()?; | |
| 1192 | + let overdue = is_overdue(done, task.deadline, meeting, now, viewer_zone); | |
| 1193 | + let (subtasks_done, subtasks_total) = | |
| 1194 | + subtask_counts.get(&task.id).copied().unwrap_or((0, 0)); | |
| 1195 | + cards.push(Card { | |
| 1196 | + tag_name: tags.get(&task.tag_id).cloned().unwrap_or_default(), | |
| 1197 | + blocked: !done && blocked.contains(&task.id), | |
| 1198 | + overdue, | |
| 1199 | + subtasks_done, | |
| 1200 | + subtasks_total, | |
| 1201 | + comments: comment_counts.get(&task.id).copied().unwrap_or(0), | |
| 1202 | + assignees: task_assignees, | |
| 1203 | + task, | |
| 1204 | + }); | |
| 1205 | + } | |
| 1206 | + match filter.sort { | |
| 1207 | + SortBy::Deadline => cards.sort_by(|a, b| { | |
| 1208 | + a.task | |
| 1209 | + .deadline | |
| 1210 | + .is_none() | |
| 1211 | + .cmp(&b.task.deadline.is_none()) | |
| 1212 | + .then(a.task.deadline.cmp(&b.task.deadline)) | |
| 1213 | + .then(a.task.id.cmp(&b.task.id)) | |
| 1214 | + }), | |
| 1215 | + SortBy::Created => cards.sort_by(|a, b| { | |
| 1216 | + b.task | |
| 1217 | + .created_at | |
| 1218 | + .cmp(&a.task.created_at) | |
| 1219 | + .then(b.task.id.cmp(&a.task.id)) | |
| 1220 | + }), | |
| 1221 | + SortBy::Title => cards.sort_by(|a, b| { | |
| 1222 | + fold_for_search(&a.task.title) | |
| 1223 | + .cmp(&fold_for_search(&b.task.title)) | |
| 1224 | + .then(a.task.id.cmp(&b.task.id)) | |
| 1225 | + }), | |
| 1226 | + } | |
| 1227 | + let overdue = cards.iter().filter(|c| c.overdue).count(); | |
| 1228 | + let blocked_count = cards.iter().filter(|c| c.blocked).count(); | |
| 1229 | + let columns = columns | |
| 1230 | + .into_iter() | |
| 1231 | + .map(|column| { | |
| 1232 | + let mine = cards | |
| 1233 | + .iter() | |
| 1234 | + .filter(|c| c.task.column_id == column.id) | |
| 1235 | + .cloned() | |
| 1236 | + .collect(); | |
| 1237 | + ColumnCards { | |
| 1238 | + column, | |
| 1239 | + cards: mine, | |
| 1240 | + } | |
| 1241 | + }) | |
| 1242 | + .collect(); | |
| 1243 | + Ok(BoardView { | |
| 1244 | + columns, | |
| 1245 | + overdue, | |
| 1246 | + blocked: blocked_count, | |
| 1247 | + }) | |
| 1248 | + } | |
| 1249 | + | |
| 1250 | + /// One task with its project, assignees, live subtasks and live links. `key_or_id` is the readable key | |
| 1251 | + /// (`IZ-42`) or the id. Deleted or foreign tasks are `NotFound`. | |
| 1252 | + pub async fn task_detail(&self, board_id: &str, key_or_id: &str) -> Result<TaskDetail> { | |
| 1253 | + let conn = self.read_conn().await; | |
| 1254 | + let task = fetch_opt( | |
| 1255 | + &conn, | |
| 1256 | + &format!( | |
| 1257 | + "SELECT {TASK_COLS} FROM tasks WHERE board_id = ?1 AND (id = ?2 OR key = ?2) AND deleted_at IS NULL" | |
| 1258 | + ), | |
| 1259 | + (board_id.to_owned(), key_or_id.to_owned()), | |
| 1260 | + map_task, | |
| 1261 | + ) | |
| 1262 | + .await? | |
| 1263 | + .ok_or(Error::NotFound)?; | |
| 1264 | + let tag = fetch_opt( | |
| 1265 | + &conn, | |
| 1266 | + "SELECT id, board_id, name, position, is_default, color FROM tags WHERE id = ?1", | |
| 1267 | + (task.tag_id.clone(),), | |
| 1268 | + |row| { | |
| 1269 | + Ok(Tag { | |
| 1270 | + id: col_text(row, 0)?, | |
| 1271 | + board_id: col_text(row, 1)?, | |
| 1272 | + name: col_text(row, 2)?, | |
| 1273 | + position: col_real(row, 3)?, | |
| 1274 | + is_default: super::col_bool(row, 4)?, | |
| 1275 | + color: col_opt_text(row, 5)?, | |
| 1276 | + }) | |
| 1277 | + }, | |
| 1278 | + ) | |
| 1279 | + .await? | |
| 1280 | + .ok_or_else(|| Error::Database("task has no project".into()))?; | |
| 1281 | + let assignees = fetch_all( | |
| 1282 | + &conn, | |
| 1283 | + "SELECT a.task_id, m.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \ | |
| 1284 | + WHERE a.task_id = ?1 ORDER BY m.name, m.sub", | |
| 1285 | + (task.id.clone(),), | |
| 1286 | + map_assignee, | |
| 1287 | + ) | |
| 1288 | + .await? | |
| 1289 | + .into_iter() | |
| 1290 | + .map(|(_, a)| a) | |
| 1291 | + .collect(); | |
| 1292 | + let subtasks = fetch_all( | |
| 1293 | + &conn, | |
| 1294 | + &format!( | |
| 1295 | + "SELECT {TASK_COLS} FROM tasks WHERE parent_id = ?1 AND board_id = ?2 AND deleted_at IS NULL \ | |
| 1296 | + ORDER BY position, id" | |
| 1297 | + ), | |
| 1298 | + (task.id.clone(), board_id.to_owned()), | |
| 1299 | + map_task, | |
| 1300 | + ) | |
| 1301 | + .await?; | |
| 1302 | + let blocked_by = fetch_all( | |
| 1303 | + &conn, | |
| 1304 | + &format!( | |
| 1305 | + "SELECT {TASK_COLS_T} FROM dependencies d JOIN tasks t ON t.id = d.blocking_id \ | |
| 1306 | + WHERE d.blocked_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL ORDER BY t.key" | |
| 1307 | + ), | |
| 1308 | + (task.id.clone(),), | |
| 1309 | + map_task, | |
| 1310 | + ) | |
| 1311 | + .await?; | |
| 1312 | + let blocks = fetch_all( | |
| 1313 | + &conn, | |
| 1314 | + &format!( | |
| 1315 | + "SELECT {TASK_COLS_T} FROM dependencies d JOIN tasks t ON t.id = d.blocked_id \ | |
| 1316 | + WHERE d.blocking_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL ORDER BY t.key" | |
| 1317 | + ), | |
| 1318 | + (task.id.clone(),), | |
| 1319 | + map_task, | |
| 1320 | + ) | |
| 1321 | + .await?; | |
| 1322 | + Ok(TaskDetail { | |
| 1323 | + task, | |
| 1324 | + tag, | |
| 1325 | + assignees, | |
| 1326 | + subtasks, | |
| 1327 | + blocked_by, | |
| 1328 | + blocks, | |
| 1329 | + }) | |
| 1330 | + } | |
| 1331 | +} | |
| 1332 | + | |
| 1333 | +/// Removes repeated `(blocked, blocking)` pairs, keeping the first. | |
| 1334 | +fn unique_pairs(pairs: Vec<(String, String)>) -> Vec<(String, String)> { | |
| 1335 | + let mut seen = HashSet::new(); | |
| 1336 | + pairs | |
| 1337 | + .into_iter() | |
| 1338 | + .filter(|p| seen.insert(p.clone())) | |
| 1339 | + .collect() | |
| 1340 | +} | |
| 1341 | + | |
| 1342 | +#[cfg(test)] | |
| 1343 | +mod tests { | |
| 1344 | + use super::*; | |
| 1345 | + use crate::store::test_support::seeded; | |
| 1346 | + | |
| 1347 | + fn new_task(title: &str, column: &str, tag: &str) -> NewTask { | |
| 1348 | + NewTask { | |
| 1349 | + title: title.into(), | |
| 1350 | + description: String::new(), | |
| 1351 | + column_id: column.into(), | |
| 1352 | + tag_id: tag.into(), | |
| 1353 | + deadline: None, | |
| 1354 | + meeting_at: None, | |
| 1355 | + assignees: vec![], | |
| 1356 | + parent_id: None, | |
| 1357 | + link: None, | |
| 1358 | + } | |
| 1359 | + } | |
| 1360 | + | |
| 1361 | + async fn default_tag(store: &Store, board: &str) -> String { | |
| 1362 | + store | |
| 1363 | + .tags(board) | |
| 1364 | + .await | |
| 1365 | + .unwrap() | |
| 1366 | + .into_iter() | |
| 1367 | + .find(|t| t.is_default) | |
| 1368 | + .unwrap() | |
| 1369 | + .id | |
| 1370 | + } | |
| 1371 | + | |
| 1372 | + async fn column_named(store: &Store, board: &str, is_done: bool) -> Column { | |
| 1373 | + store | |
| 1374 | + .columns(board) | |
| 1375 | + .await | |
| 1376 | + .unwrap() | |
| 1377 | + .into_iter() | |
| 1378 | + .find(|c| c.is_done == is_done) | |
| 1379 | + .unwrap() | |
| 1380 | + } | |
| 1381 | + | |
| 1382 | + async fn live_count(store: &Store, board: &str) -> usize { | |
| 1383 | + let view = store | |
| 1384 | + .board_view(board, &BoardFilter::default(), &TimeZone::UTC) | |
| 1385 | + .await | |
| 1386 | + .unwrap(); | |
| 1387 | + view.columns.iter().map(|c| c.cards.len()).sum() | |
| 1388 | + } | |
| 1389 | + | |
| 1390 | + #[tokio::test] | |
| 1391 | + async fn refused_link_leaves_no_task_row() { | |
| 1392 | + let (_dir, store, board) = seeded().await; | |
| 1393 | + let tag = default_tag(&store, &board).await; | |
| 1394 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1395 | + store | |
| 1396 | + .create_task(&board, new_task("First", &backlog, &tag), "ada") | |
| 1397 | + .await | |
| 1398 | + .unwrap(); | |
| 1399 | + // The link names a task that is not on this board: the whole create is refused. | |
| 1400 | + let mut bad = new_task("Second", &backlog, &tag); | |
| 1401 | + bad.link = Some(("no-such-task".into(), LinkDirection::BlockedBy)); | |
| 1402 | + assert!(matches!( | |
| 1403 | + store.create_task(&board, bad, "ada").await, | |
| 1404 | + Err(Error::Invalid(_)) | |
| 1405 | + )); | |
| 1406 | + assert_eq!(live_count(&store, &board).await, 1); | |
| 1407 | + } | |
| 1408 | + | |
| 1409 | + #[tokio::test] | |
| 1410 | + async fn dependency_cycle_is_refused() { | |
| 1411 | + let (_dir, store, board) = seeded().await; | |
| 1412 | + let tag = default_tag(&store, &board).await; | |
| 1413 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1414 | + let a = store | |
| 1415 | + .create_task(&board, new_task("A", &backlog, &tag), "ada") | |
| 1416 | + .await | |
| 1417 | + .unwrap(); | |
| 1418 | + let b = store | |
| 1419 | + .create_task(&board, new_task("B", &backlog, &tag), "ada") | |
| 1420 | + .await | |
| 1421 | + .unwrap(); | |
| 1422 | + store | |
| 1423 | + .add_dependency(&board, &a.id, &b.id, "ada") | |
| 1424 | + .await | |
| 1425 | + .unwrap(); | |
| 1426 | + assert!(matches!( | |
| 1427 | + store.add_dependency(&board, &b.id, &a.id, "ada").await, | |
| 1428 | + Err(Error::Conflict(_)) | |
| 1429 | + )); | |
| 1430 | + } | |
| 1431 | + | |
| 1432 | + #[tokio::test] | |
| 1433 | + async fn move_into_done_with_open_subtask_is_refused() { | |
| 1434 | + let (_dir, store, board) = seeded().await; | |
| 1435 | + let tag = default_tag(&store, &board).await; | |
| 1436 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1437 | + let done = column_named(&store, &board, true).await; | |
| 1438 | + let parent = store | |
| 1439 | + .create_task(&board, new_task("Parent", &backlog, &tag), "ada") | |
| 1440 | + .await | |
| 1441 | + .unwrap(); | |
| 1442 | + let child = store | |
| 1443 | + .create_task(&board, new_task("Child", &backlog, &tag), "ada") | |
| 1444 | + .await | |
| 1445 | + .unwrap(); | |
| 1446 | + store | |
| 1447 | + .set_parent(&board, &child.id, Some(&parent.id), "ada") | |
| 1448 | + .await | |
| 1449 | + .unwrap(); | |
| 1450 | + let outcome = store | |
| 1451 | + .move_task(&board, &parent.id, &backlog, &done.id, "ada") | |
| 1452 | + .await | |
| 1453 | + .unwrap(); | |
| 1454 | + assert_eq!(outcome, MoveOutcome::SubtasksOpen); | |
| 1455 | + // Finishing the subtask first lets the parent through. | |
| 1456 | + store | |
| 1457 | + .move_task(&board, &child.id, &backlog, &done.id, "ada") | |
| 1458 | + .await | |
| 1459 | + .unwrap(); | |
| 1460 | + let outcome = store | |
| 1461 | + .move_task(&board, &parent.id, &backlog, &done.id, "ada") | |
| 1462 | + .await | |
| 1463 | + .unwrap(); | |
| 1464 | + assert_eq!(outcome, MoveOutcome::Moved); | |
| 1465 | + let moved = store.task_detail(&board, &parent.key).await.unwrap().task; | |
| 1466 | + assert!(moved.done_at.is_some()); | |
| 1467 | + } | |
| 1468 | + | |
| 1469 | + #[tokio::test] | |
| 1470 | + async fn stale_move_is_refused() { | |
| 1471 | + let (_dir, store, board) = seeded().await; | |
| 1472 | + let tag = default_tag(&store, &board).await; | |
| 1473 | + let columns = store.columns(&board).await.unwrap(); | |
| 1474 | + let (backlog, progress) = (columns[0].id.clone(), columns[1].id.clone()); | |
| 1475 | + let task = store | |
| 1476 | + .create_task(&board, new_task("Move me", &backlog, &tag), "ada") | |
| 1477 | + .await | |
| 1478 | + .unwrap(); | |
| 1479 | + // Someone else already moved it, so the client's view of "from" is out of date. | |
| 1480 | + store | |
| 1481 | + .move_task(&board, &task.id, &backlog, &progress, "bo") | |
| 1482 | + .await | |
| 1483 | + .unwrap(); | |
| 1484 | + let stale = store | |
| 1485 | + .move_task(&board, &task.id, &backlog, &columns[2].id, "ada") | |
| 1486 | + .await | |
| 1487 | + .unwrap(); | |
| 1488 | + assert_eq!(stale, MoveOutcome::Stale); | |
| 1489 | + let same = store | |
| 1490 | + .move_task(&board, &task.id, &progress, &progress, "ada") | |
| 1491 | + .await | |
| 1492 | + .unwrap(); | |
| 1493 | + assert_eq!(same, MoveOutcome::Unchanged); | |
| 1494 | + } | |
| 1495 | + | |
| 1496 | + #[tokio::test] | |
| 1497 | + async fn deleting_a_blocker_frees_the_dependent() { | |
| 1498 | + let (_dir, store, board) = seeded().await; | |
| 1499 | + let tag = default_tag(&store, &board).await; | |
| 1500 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1501 | + let blocker = store | |
| 1502 | + .create_task(&board, new_task("Blocker", &backlog, &tag), "ada") | |
| 1503 | + .await | |
| 1504 | + .unwrap(); | |
| 1505 | + let mut dependent = new_task("Dependent", &backlog, &tag); | |
| 1506 | + dependent.link = Some((blocker.id.clone(), LinkDirection::BlockedBy)); | |
| 1507 | + let dependent = store.create_task(&board, dependent, "ada").await.unwrap(); | |
| 1508 | + let before = store | |
| 1509 | + .board_view(&board, &BoardFilter::default(), &TimeZone::UTC) | |
| 1510 | + .await | |
| 1511 | + .unwrap(); | |
| 1512 | + assert_eq!(before.blocked, 1); | |
| 1513 | + let freed = store.delete_task(&board, &blocker.id, "ada").await.unwrap(); | |
| 1514 | + assert_eq!(freed, vec![dependent.id.clone()]); | |
| 1515 | + let after = store | |
| 1516 | + .board_view(&board, &BoardFilter::default(), &TimeZone::UTC) | |
| 1517 | + .await | |
| 1518 | + .unwrap(); | |
| 1519 | + assert_eq!(after.blocked, 0); | |
| 1520 | + } | |
| 1521 | + | |
| 1522 | + #[tokio::test] | |
| 1523 | + async fn search_folds_turkish_dotted_and_dotless_i() { | |
| 1524 | + let (_dir, store, board) = seeded().await; | |
| 1525 | + let tag = default_tag(&store, &board).await; | |
| 1526 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1527 | + store | |
| 1528 | + .create_task(&board, new_task("İSTANBUL görüşme", &backlog, &tag), "ada") | |
| 1529 | + .await | |
| 1530 | + .unwrap(); | |
| 1531 | + store | |
| 1532 | + .create_task(&board, new_task("Ankara", &backlog, &tag), "ada") | |
| 1533 | + .await | |
| 1534 | + .unwrap(); | |
| 1535 | + for query in ["istanbul", "ıstanbul", "ISTANBUL", "İstanbul"] { | |
| 1536 | + let filter = BoardFilter { | |
| 1537 | + query: Some(query.into()), | |
| 1538 | + ..BoardFilter::default() | |
| 1539 | + }; | |
| 1540 | + let view = store | |
| 1541 | + .board_view(&board, &filter, &TimeZone::UTC) | |
| 1542 | + .await | |
| 1543 | + .unwrap(); | |
| 1544 | + let titles: Vec<&str> = view | |
| 1545 | + .columns | |
| 1546 | + .iter() | |
| 1547 | + .flat_map(|c| c.cards.iter().map(|card| card.task.title.as_str())) | |
| 1548 | + .collect(); | |
| 1549 | + assert_eq!(titles, vec!["İSTANBUL görüşme"], "query {query}"); | |
| 1550 | + } | |
| 1551 | + } | |
| 1552 | + | |
| 1553 | + #[tokio::test] | |
| 1554 | + async fn tag_delete_refused_while_in_use() { | |
| 1555 | + let (_dir, store, board) = seeded().await; | |
| 1556 | + let general = default_tag(&store, &board).await; | |
| 1557 | + let work = store.add_tag(&board, "Work", None).await.unwrap(); | |
| 1558 | + let backlog = store.columns(&board).await.unwrap()[0].id.clone(); | |
| 1559 | + let task = store | |
| 1560 | + .create_task(&board, new_task("Report", &backlog, &work.id), "ada") | |
| 1561 | + .await | |
| 1562 | + .unwrap(); | |
| 1563 | + assert!(matches!( | |
| 1564 | + store.delete_tag(&board, &work.id).await, | |
| 1565 | + Err(Error::Conflict(_)) | |
| 1566 | + )); | |
| 1567 | + assert!(matches!( | |
| 1568 | + store.delete_tag(&board, &general).await, | |
| 1569 | + Err(Error::Invalid(_)) | |
| 1570 | + )); | |
| 1571 | + // Once the only task is deleted, the tag goes and the trashed task is re-pointed to General. | |
| 1572 | + store.delete_task(&board, &task.id, "ada").await.unwrap(); | |
| 1573 | + store.delete_tag(&board, &work.id).await.unwrap(); | |
| 1574 | + assert!(store.tag(&board, &work.id).await.unwrap().is_none()); | |
| 1575 | + let trashed = fetch_opt( | |
| 1576 | + &*store.read_conn().await, | |
| 1577 | + "SELECT tag_id FROM tasks WHERE id = ?1", | |
| 1578 | + (task.id.clone(),), | |
| 1579 | + |row| col_text(row, 0), | |
| 1580 | + ) | |
| 1581 | + .await | |
| 1582 | + .unwrap(); | |
| 1583 | + assert_eq!(trashed, Some(general)); | |
| 1584 | + } | |
| 1585 | +} |