1use super::{Brain, ReportView};
4use crate::api::ApiError;
5use crate::export;
6use crate::model::{
7 Asked, Author, Comment, DecisionState, Kind, RepoLink, Status, Task, now, one_line, sanitize_comment,
8 sanitize_description,
9};
10use crate::projects;
11use anyhow::Result;
12use std::path::PathBuf;
13
14const DECISION_TEMPLATE: &str = "### Context\n\nWhat forces us to decide, and what we know.\n\n\
16 ### Decision\n\nWhat we chose.\n\n\
17 ### Consequences\n\nWhat becomes easier or harder, and what we gave up.";
18
19#[derive(Debug, Default)]
21pub struct NewEntry {
22 pub kind: Kind,
24 pub title: String,
26 pub tags: Vec<String>,
28 pub links: Vec<u32>,
30 pub repo_links: Vec<RepoLink>,
32 pub description: Option<String>,
34 pub start: bool,
36}
37
38impl Brain {
39 fn task_index(&self, id: u32) -> Result<usize, ApiError> {
41 let index = self.index_of(id)?;
42 match self.tasks[index].kind {
43 Kind::Task => Ok(index),
44 kind => Err(ApiError::NotATask(id, kind)),
45 }
46 }
47
48 pub fn set_status(&mut self, id: u32, status: Status) -> Result<bool> {
52 let index = self.task_index(id)?;
53 if status == Status::Doing {
54 return self.start_task(index);
55 }
56 if !self.tasks[index].set_status(status, now(), self.author) {
57 return Ok(false);
58 }
59 self.store.save(&mut self.tasks[index])?;
60 Ok(true)
61 }
62
63 fn start_task(&mut self, index: usize) -> Result<bool> {
66 if self.tasks[index].is_running() {
67 return Ok(false);
68 }
69 if self.tasks[index].status != Status::Doing {
70 self.check_doing_room(self.author)?;
71 }
72 let now = now();
73 self.tasks[index].set_status(Status::Doing, now, self.author);
74 self.tasks[index].start_session(now);
75 self.store.save(&mut self.tasks[index])?;
76 Ok(true)
77 }
78
79 pub fn set_project_description(&mut self, text: &str) -> Result<()> {
81 let (Some(project), Some(central)) = (&mut self.project, &self.central) else {
82 anyhow::bail!("only a project's repository has a project description");
83 };
84 project.description = text.trim().to_string();
85 projects::write_description(central, &project.name, &project.description)
86 }
87
88 pub fn set_repo_notes(&mut self, text: &str) -> Result<()> {
90 let Some(project) = &mut self.project else { anyhow::bail!("the central brain isn't a project's repository") };
91 project.notes = text.trim().to_string();
92 let repo = projects::read_repo_card(self.store.dir()).and_then(|card| card.repo);
93 let card = projects::RepoCard { project: project.name.clone(), repo, notes: project.notes.clone() };
94 projects::write_repo_card(self.store.dir(), &card)
95 }
96
97 fn check_doing_room(&self, by: Author) -> Result<(), ApiError> {
100 match self.person_doing() {
101 Some(doing) if by == Author::Human => Err(ApiError::DoingFull(doing)),
102 _ => Ok(()),
103 }
104 }
105
106 pub fn park_people_running(&mut self) -> Result<()> {
109 let now = now();
110 for task in self.tasks.iter_mut().filter(|t| t.is_running() && t.started_by() == Author::Human) {
111 task.set_status(Status::Parked, now, self.author);
112 self.store.save(task)?;
113 }
114 Ok(())
115 }
116
117 pub(crate) fn create(&mut self, new: NewEntry) -> Result<u32> {
121 if new.start && new.kind == Kind::Task {
123 self.check_doing_room(self.author)?;
124 }
125 let mut task = Task::new(self.take_id()?, new.title, now());
126 task.kind = new.kind;
127 task.description = match new.description {
128 Some(text) => sanitize_description(&text).0,
129 None if task.kind == Kind::Decision => DECISION_TEMPLATE.to_string(),
130 None => String::new(),
131 };
132 task.tags = new.tags;
133 task.links = new.links;
134 task.repo_links = new.repo_links;
135 self.store.save(&mut task)?;
136 let id = task.id;
137 self.tasks.push(task);
138 self.sync_tag_colors()?;
139 if new.start && new.kind == Kind::Task {
140 self.set_status(id, Status::Doing)?;
141 }
142 Ok(id)
143 }
144
145 pub fn update(&mut self, id: u32, title: &str, tags: Vec<String>) -> Result<()> {
147 let title = &one_line(title);
148 if title.is_empty() {
149 return Err(ApiError::Empty("title").into());
150 }
151 let index = self.index_of(id)?;
152 title.clone_into(&mut self.tasks[index].title);
153 self.tasks[index].tags = tags;
154 self.store.save(&mut self.tasks[index])?;
155 self.sync_tag_colors()
156 }
157
158 pub fn delete(&mut self, id: u32) -> Result<()> {
161 let index = self.index_of(id)?;
162 for task in self.tasks.iter_mut().filter(|t| t.links.contains(&id)) {
163 task.links.retain(|&link| link != id);
164 self.store.save(task)?;
165 }
166 self.store.delete(&self.tasks[index])?;
167 self.tasks.remove(index);
168 Ok(())
169 }
170
171 pub fn move_to(&mut self, id: u32, to: &mut Brain) -> Result<u32> {
180 let index = self.index_of(id)?;
181 if projects::same_dir(self.store.dir(), to.store.dir()) {
182 anyhow::bail!("#{id} is already there");
183 }
184 if self.tasks[index].status == Status::Doing {
185 to.check_doing_room(self.tasks[index].started_by())?;
186 }
187 let mut entry = Task {
188 id: to.take_id()?,
189 links: Vec::new(),
190 repo_links: Vec::new(),
191 path: None,
192 ..self.tasks[index].clone()
193 };
194 entry.unknown.links.clear();
195 to.store.save(&mut entry)?;
196 let new_id = entry.id;
197 to.tasks.push(entry);
198 to.sync_tag_colors()?;
199 self.delete(id)?;
200 Ok(new_id)
201 }
202
203 pub fn drop_repo_links_to(&mut self, link: &RepoLink) -> Result<()> {
205 for task in self.tasks.iter_mut().filter(|t| t.repo_links.contains(link)) {
206 task.repo_links.retain(|l| l != link);
207 self.store.save(task)?;
208 }
209 Ok(())
210 }
211
212 pub fn toggle_repo_link(&mut self, id: u32, other: &mut Brain, other_id: u32) -> Result<bool> {
216 let (Some(here), Some(there)) = (&self.project, &other.project) else {
217 return Err(ApiError::NoRepo(other.store.dir().display().to_string()).into());
218 };
219 if here.name != there.name || here.repo == there.repo {
220 return Err(ApiError::NoRepo(there.repo.clone()).into());
221 }
222 let to = RepoLink { repo: there.repo.clone(), id: other_id };
223 let back = RepoLink { repo: here.repo.clone(), id };
224 let index = self.index_of(id)?;
225 let other_index = other.find(other_id).ok_or_else(|| ApiError::NotFoundIn(to.clone()))?;
226 let related = self.tasks[index].repo_links.contains(&to) || other.tasks[other_index].repo_links.contains(&back);
227 if !related {
228 self.tasks[index].repo_links.push(to);
229 self.store.save(&mut self.tasks[index])?;
230 return Ok(true);
231 }
232 for (brain, index, link) in [(&mut *self, index, &to), (&mut *other, other_index, &back)] {
233 let task = &mut brain.tasks[index];
234 if task.repo_links.contains(link) {
235 task.repo_links.retain(|l| l != link);
236 brain.store.save(task)?;
237 }
238 }
239 Ok(false)
240 }
241
242 pub fn toggle_link(&mut self, id: u32, other: u32) -> Result<bool> {
245 if id == other {
246 return Err(ApiError::SelfLink(id).into());
247 }
248 for side in [id, other] {
249 self.find(side).ok_or(ApiError::NotFound(side))?;
250 }
251 let related = self.are_related(id, other);
252 for (from, to) in [(id, other), (other, id)] {
253 let Some(index) = self.find(from) else { continue };
254 let task = &mut self.tasks[index];
255 let before = task.links.len();
256 if related {
257 task.links.retain(|&l| l != to);
258 } else if from == id {
259 task.links.push(to);
260 }
261 if task.links.len() != before {
262 self.store.save(task)?;
263 }
264 }
265 Ok(!related)
266 }
267
268 pub fn set_description(&mut self, id: u32, text: &str) -> Result<bool> {
270 let index = self.index_of(id)?;
271 let (text, demoted) = sanitize_description(text);
272 self.tasks[index].description = text;
273 self.store.save(&mut self.tasks[index])?;
274 Ok(demoted)
275 }
276
277 pub fn add_comment(&mut self, id: u32, text: &str) -> Result<bool> {
279 self.push_comment(id, text, Said::Comment)
280 }
281
282 pub fn ask(&mut self, id: u32, question: &str) -> Result<bool> {
285 let index = self.task_index(id)?;
286 let demoted = self.push_comment(id, question, Said::Question)?;
287 if self.tasks[index].set_status(Status::Parked, now(), self.author) {
288 self.store.save(&mut self.tasks[index])?;
289 }
290 Ok(demoted)
291 }
292
293 pub fn propose(&mut self, id: u32, decision: NewEntry) -> Result<u32> {
297 self.task_index(id)?;
298 let mut links = decision.links;
299 if !links.contains(&id) {
300 links.insert(0, id);
301 }
302 let title = one_line(&decision.title);
303 let new = NewEntry { kind: Kind::Decision, title: title.clone(), links, start: false, ..decision };
304 let decision = self.add(new)?;
305 let index = self.index_of(decision)?;
306 self.tasks[index].decision = DecisionState::Proposed;
307 self.store.save(&mut self.tasks[index])?;
308 self.ask(id, &format!("Proposed decision #{decision}, {title}: accept or reject it."))?;
309 Ok(decision)
310 }
311
312 pub fn resolve(&mut self, id: u32, state: DecisionState, reason: &str) -> Result<bool> {
316 let index = self.index_of(id)?;
317 let decision = &self.tasks[index];
318 if decision.kind != Kind::Decision {
319 return Err(ApiError::NotADecision(id, decision.kind).into());
320 }
321 if decision.decision == state {
322 return Ok(false);
323 }
324 if state == DecisionState::Rejected && reason.trim().is_empty() {
325 return Err(ApiError::Empty("reason").into());
326 }
327 let title = decision.title.clone();
328 let verdict = match state {
329 DecisionState::Accepted => "Accepted",
330 DecisionState::Rejected => "Rejected",
331 DecisionState::Proposed => "Proposed again",
332 };
333 let said = |what: &str| match reason.trim() {
334 "" => format!("{what}."),
335 reason => format!("{what}: {reason}"),
336 };
337 self.tasks[index].decision = state;
338 self.store.save(&mut self.tasks[index])?;
339 self.push_comment(id, &said(verdict), Said::Comment)?;
340 let about = format!("#{id}");
343 let waiting: Vec<u32> = self
344 .tasks
345 .iter()
346 .filter(|t| match t.asked() {
347 Some(Asked::Waiting(question)) => {
348 self.are_related(t.id, id)
349 && question
351 .body
352 .split(|c: char| !(c.is_alphanumeric() || matches!(c, '#' | '-' | '_')))
353 .any(|w| w == about)
354 }
355 _ => false,
356 })
357 .map(|t| t.id)
358 .collect();
359 for task in waiting {
360 self.push_comment(task, &said(&format!("{verdict} decision #{id}, {title}")), Said::Answer)?;
361 }
362 Ok(true)
363 }
364
365 fn push_comment(&mut self, id: u32, text: &str, said: Said) -> Result<bool> {
368 let index = self.index_of(id)?;
369 let (body, demoted) = sanitize_comment(text);
370 if body.is_empty() {
371 return Err(ApiError::Empty(if said == Said::Question { "question" } else { "comment" }).into());
372 }
373 let (question, answer) = (said == Said::Question, said == Said::Answer);
374 let comment = Comment { question, answer, ..Comment::new(now(), body, self.author) };
375 self.tasks[index].comments.push(comment);
376 self.store.save(&mut self.tasks[index])?;
377 Ok(demoted)
378 }
379
380 pub fn update_comment(&mut self, id: u32, comment: usize, text: &str) -> Result<bool> {
383 let index = self.index_of(id)?;
384 let (body, demoted) = sanitize_comment(text);
385 if body.is_empty() {
386 return Err(ApiError::Empty("comment").into());
387 }
388 let task = &mut self.tasks[index];
389 let Some(existing) = task.comments.get_mut(comment) else {
390 return Err(ApiError::NoComment(id, comment).into());
391 };
392 if existing.body != body {
393 existing.body = body;
394 existing.edited = Some(now());
395 self.store.save(task)?;
396 }
397 Ok(demoted)
398 }
399
400 pub fn delete_comment(&mut self, id: u32, comment: usize) -> Result<()> {
402 let index = self.index_of(id)?;
403 let task = &mut self.tasks[index];
404 if comment >= task.comments.len() {
405 return Err(ApiError::NoComment(id, comment).into());
406 }
407 task.comments.remove(comment);
408 self.store.save(task)
409 }
410
411 pub fn report_path(&self, view: &ReportView) -> PathBuf {
413 self.store.reports_dir().join(export::file_name(view))
414 }
415
416 pub fn export_report(&self, view: &ReportView) -> Result<PathBuf> {
418 self.write_report(&self.report(view), view)
419 }
420
421 pub fn write_report(&self, report: &super::Report, view: &ReportView) -> Result<PathBuf> {
424 let markdown = export::to_markdown(report, view, now());
425 let path = self.report_path(view);
426 crate::store::write_file(&path, &markdown)?;
427 Ok(path)
428 }
429}
430
431#[derive(Clone, Copy, PartialEq, Eq)]
433enum Said {
434 Comment,
436 Question,
438 Answer,
440}