OXYGENHUB
# 17dc8de4fca8 oxygenhub / crates / hub / src / web / projects.rs
35.2 KiB · Rust · last changed Boards keep the last fortnight of finished work (refs #293) 10 days ago source blame history raw
e1ec9fbf Andy McCall ↶ 1
//! Projects (hub spec §8.2): boards of issues, proposals and notes across
2
//! the repositories of one person or organisation.
3
4
use super::settings::csrf;
5
use super::{filters, Error, Page, Shell};
6
use crate::auth::{roles, Access, Viewer};
6a306cd0 Andy McCall ↶ 7
use crate::db::{self, issues as idb, projects as pdb};
e1ec9fbf Andy McCall ↶ 8
use crate::Shared;
9
use askama::Template;
7b26e611 Andy McCall ↶ 10
use axum::extract::{Form, Path, Query, State};
e1ec9fbf Andy McCall ↶ 11
use axum::response::{IntoResponse, Redirect, Response};
12
use serde::Deserialize;
13
ef20fdc1 Andy McCall ↶ 14
/// What a caller may do with an owner's projects.
15
pub struct Rights {
e1ec9fbf Andy McCall ↶ 16
    /// Sees private projects.
ef20fdc1 Andy McCall ↶ 17
    pub member: bool,
e1ec9fbf Andy McCall ↶ 18
    /// Creates and changes projects.
ef20fdc1 Andy McCall ↶ 19
    pub edit: bool,
e1ec9fbf Andy McCall ↶ 20
}
21
ef20fdc1 Andy McCall ↶ 22
/// Rights of `account` (anonymous when `None`) over `owner`'s projects;
23
/// `None` when there is no such person or organisation.
24
pub async fn rights_of(app: &Shared, account: Option<&db::accounts::Account>, owner: &str) -> sqlx::Result<Option<Rights>> {
25
    let admin = account.is_some_and(|a| a.is_admin);
26
    if let Some(a) = db::accounts::account_by_name(&app.db, owner).await? {
27
        let me = account.is_some_and(|v| v.id == a.id);
28
        return Ok(Some(Rights { member: me || admin, edit: me || admin }));
e1ec9fbf Andy McCall ↶ 29
    }
ef20fdc1 Andy McCall ↶ 30
    if let Some(o) = db::accounts::org_by_name(&app.db, owner).await? {
31
        let member = match account {
32
            Some(v) => db::accounts::org_role(&app.db, o.id, v.id).await?.is_some(),
e1ec9fbf Andy McCall ↶ 33
            None => false,
34
        };
ef20fdc1 Andy McCall ↶ 35
        return Ok(Some(Rights { member: member || admin, edit: member || admin }));
e1ec9fbf Andy McCall ↶ 36
    }
ef20fdc1 Andy McCall ↶ 37
    Ok(None)
38
}
39
40
async fn rights(app: &Shared, shell: &Shell, viewer: &Viewer, owner: &str) -> Result<Rights, Error> {
41
    rights_of(app, viewer.account(), owner)
42
        .await
43
        .map_err(|e| Error::from_db(shell.clone(), e))?
44
        .ok_or_else(|| Error::not_found(shell.clone()))
e1ec9fbf Andy McCall ↶ 45
}
46
47
#[derive(Template)]
48
#[template(path = "projects.html")]
49
pub struct ProjectsPage {
50
    shell: Shell,
51
    owner: String,
7b26e611 Andy McCall ↶ 52
    /// The projects shown: open or closed as `closed` says, matching `q`.
e1ec9fbf Andy McCall ↶ 53
    projects: Vec<pdb::Project>,
54
    can_edit: bool,
55
    error: Option<String>,
a024e800 Andy McCall ↶ 56
    /// On your own page, the organisations you belong to: their boards
57
    /// are one click away, and where a board for one is made (#119).
58
    orgs: Vec<String>,
7b26e611 Andy McCall ↶ 59
    /// The title filter, and whether the closed ones are shown (#124).
60
    q: String,
61
    closed: bool,
62
    open_count: usize,
63
    closed_count: usize,
e1ec9fbf Andy McCall ↶ 64
}
65
7b26e611 Andy McCall ↶ 66
impl ProjectsPage {
67
    /// The page for `all` the projects the viewer may see: counted open
68
    /// and closed among those matching `q`, then the ones asked for.
69
    #[allow(clippy::too_many_arguments)]
70
    fn build(
71
        shell: Shell,
72
        owner: String,
73
        all: Vec<pdb::Project>,
74
        can_edit: bool,
75
        error: Option<String>,
76
        orgs: Vec<String>,
77
        q: Option<String>,
78
        closed: bool,
79
    ) -> ProjectsPage {
80
        let q = q.unwrap_or_default().trim().to_string();
81
        let needle = q.to_lowercase();
82
        let matching: Vec<pdb::Project> = all
83
            .into_iter()
84
            .filter(|p| needle.is_empty() || p.title.to_lowercase().contains(&needle) || p.description.to_lowercase().contains(&needle))
85
            .collect();
86
        let closed_count = matching.iter().filter(|p| p.closed).count();
87
        let open_count = matching.len() - closed_count;
88
        let projects = matching.into_iter().filter(|p| p.closed == closed).collect();
89
        ProjectsPage { shell, owner, projects, can_edit, error, orgs, q, closed, open_count, closed_count }
90
    }
91
}
92
93
/// `?q=TEXT&state=open|closed` on the Projects page (#124).
94
#[derive(Deserialize, Default)]
95
pub struct ProjectsQuery {
96
    #[serde(default)]
97
    q: Option<String>,
98
    #[serde(default)]
99
    state: Option<String>,
100
}
101
a024e800 Andy McCall ↶ 102
/// The organisations the viewer belongs to, when `owner` is the viewer.
103
async fn own_orgs(app: &Shared, viewer: &Viewer, owner: &str) -> Vec<String> {
104
    match viewer.account() {
105
        Some(a) if a.username == owner => {
106
            crate::db::accounts::orgs_of(&app.db, a.id).await.map(|v| v.into_iter().map(|(o, _)| o.name).collect()).unwrap_or_default()
107
        }
108
        _ => vec![],
109
    }
110
}
111
7b26e611 Andy McCall ↶ 112
pub async fn list(
113
    State(app): State<Shared>,
114
    viewer: Viewer,
115
    Path(owner): Path<String>,
116
    Query(query): Query<ProjectsQuery>,
117
) -> Result<Page<ProjectsPage>, Error> {
e1ec9fbf Andy McCall ↶ 118
    let shell = Shell::new(&app, &format!("/projects/{owner}"), &viewer);
119
    let r = rights(&app, &shell, &viewer, &owner).await?;
120
    let projects = pdb::of_owner(&app.db, &owner)
121
        .await
122
        .map_err(|e| Error::from_db(shell.clone(), e))?
123
        .into_iter()
124
        .filter(|p| p.public || r.member)
125
        .collect();
a024e800 Andy McCall ↶ 126
    let orgs = own_orgs(&app, &viewer, &owner).await;
7b26e611 Andy McCall ↶ 127
    let closed = query.state.as_deref() == Some("closed");
128
    Ok(Page(ProjectsPage::build(shell, owner, projects, r.edit, None, orgs, query.q, closed)))
e1ec9fbf Andy McCall ↶ 129
}
130
131
#[derive(Deserialize)]
132
pub struct NewProjectForm {
133
    #[serde(rename = "_csrf")]
134
    csrf_token: String,
135
    title: String,
136
    #[serde(default)]
137
    description: String,
138
    #[serde(default)]
139
    private: Option<String>,
140
}
141
142
pub async fn create(
143
    State(app): State<Shared>,
144
    viewer: Viewer,
145
    Path(owner): Path<String>,
146
    Form(f): Form<NewProjectForm>,
147
) -> Result<Response, Error> {
148
    let shell = Shell::new(&app, &format!("/projects/{owner}"), &viewer);
149
    csrf(&viewer, &f.csrf_token, &shell)?;
150
    let r = rights(&app, &shell, &viewer, &owner).await?;
151
    if !r.edit {
152
        return Err(Error::not_found(shell));
153
    }
154
    let title = f.title.trim();
155
    if title.is_empty() || title.len() > 100 {
156
        let projects = pdb::of_owner(&app.db, &owner).await.map_err(|e| Error::from_db(shell.clone(), e))?;
a024e800 Andy McCall ↶ 157
        let orgs = own_orgs(&app, &viewer, &owner).await;
7b26e611 Andy McCall ↶ 158
        return Ok(Page(ProjectsPage::build(
e1ec9fbf Andy McCall ↶ 159
            shell,
160
            owner,
161
            projects,
7b26e611 Andy McCall ↶ 162
            true,
163
            Some("A project needs a title of up to 100 characters.".into()),
a024e800 Andy McCall ↶ 164
            orgs,
7b26e611 Andy McCall ↶ 165
            None,
166
            false,
167
        ))
e1ec9fbf Andy McCall ↶ 168
        .into_response());
169
    }
170
    let p = pdb::create(&app.db, &owner, title, f.description.trim(), f.private.is_none())
171
        .await
172
        .map_err(|e| Error::from_db(shell.clone(), e))?;
173
    db::accounts::audit(&app.db, viewer.account(), "project.created", &format!("{owner}/{}", p.number), title).await.ok();
174
    Ok(Redirect::to(&format!("/projects/{owner}/{}", p.number)).into_response())
175
}
176
177
/// A card as the board shows it.
178
pub struct CardView {
179
    pub card: pdb::Card,
180
    /// `owner/name#N`, for issue and proposal cards.
181
    pub reference: String,
182
    pub url: String,
183
    pub title: String,
184
    /// `open`, `closed`, `landed`, `draft`… for issues and proposals.
185
    pub state: String,
6a306cd0 Andy McCall ↶ 186
    /// The issue's or proposal's labels, and an issue's assignees (#293).
187
    pub labels: Vec<idb::Label>,
188
    pub assignees: Vec<String>,
e1ec9fbf Andy McCall ↶ 189
}
190
191
pub struct ColumnView {
192
    pub column: pdb::Column,
193
    pub cards: Vec<CardView>,
657e7d5c Andy McCall ↶ 194
    /// Cards the page leaves out (#293): the oldest of a long column, or
195
    /// those a filter does not match; `total` is how many it holds.
196
    pub hidden: usize,
197
    pub total: usize,
439ecd87 Andy McCall ↶ 198
    /// Its archived cards (#293), shown on the archive view.
199
    pub archived: usize,
946fe7a0 Andy McCall ↶ 200
    /// Its cards are all finished work (a Done column): its note says
201
    /// they are archived after a fortnight unless it says otherwise.
202
    pub finished: bool,
e1ec9fbf Andy McCall ↶ 203
}
204
657e7d5c Andy McCall ↶ 205
/// A column longer than this shows its newest cards only, with "show all"
206
/// (#293): a board's Done column otherwise grows without end.
207
pub const COLUMN_SHOWN: usize = 30;
208
209
/// How the board page shows its cards (#293).
210
#[derive(Deserialize, Default)]
211
pub struct BoardQuery {
212
    /// The column shown whole.
213
    #[serde(default)]
214
    all: Option<i64>,
6a306cd0 Andy McCall ↶ 215
    /// Only cards whose title or reference holds these words, and with
216
    /// `label:NAME`, `assignee:NAME` or `state:STATE` as the issue list takes.
657e7d5c Andy McCall ↶ 217
    #[serde(default)]
218
    q: Option<String>,
219
    /// Only cards in this state (`open`, `closed`, `landed`…).
220
    #[serde(default)]
221
    state: Option<String>,
439ecd87 Andy McCall ↶ 222
    /// The archived cards instead (`?archived=1`).
223
    #[serde(default)]
224
    archived: Option<String>,
657e7d5c Andy McCall ↶ 225
}
226
227
impl BoardQuery {
228
    fn text(&self) -> String {
229
        self.q.as_deref().map(str::trim).unwrap_or("").to_string()
230
    }
231
    fn state(&self) -> String {
232
        self.state.as_deref().map(str::trim).unwrap_or("").to_ascii_lowercase()
439ecd87 Andy McCall ↶ 233
    }
234
    fn archived(&self) -> bool {
235
        self.archived.as_deref().is_some_and(|a| !a.is_empty() && a != "0")
657e7d5c Andy McCall ↶ 236
    }
237
}
238
6a306cd0 Andy McCall ↶ 239
/// The board filter's `label:`, `assignee:` and `state:` terms, and its words.
240
#[derive(Default)]
241
struct CardFilter {
242
    labels: Vec<String>,
243
    assignees: Vec<String>,
244
    state: String,
245
    words: Vec<String>,
246
}
247
248
impl CardFilter {
249
    fn of(view: &BoardQuery) -> CardFilter {
250
        let mut f = CardFilter { state: view.state(), ..Default::default() };
251
        for tok in view.text().split_whitespace() {
252
            match tok.split_once(':') {
253
                Some(("label", v)) if !v.is_empty() => f.labels.push(v.to_lowercase()),
254
                Some(("assignee", v)) if !v.is_empty() => f.assignees.push(v.trim_start_matches('@').to_lowercase()),
255
                Some(("state", v)) if !v.is_empty() => f.state = v.to_lowercase(),
256
                _ => f.words.push(tok.to_lowercase()),
257
            }
258
        }
259
        f
260
    }
261
262
    fn is_empty(&self) -> bool {
263
        self.labels.is_empty() && self.assignees.is_empty() && self.state.is_empty() && self.words.is_empty()
264
    }
265
266
    /// Every term holds: each word in the title or reference, each label
267
    /// and assignee among the card's, and its state.
268
    fn keeps(&self, c: &CardView) -> bool {
269
        let (title, reference) = (c.title.to_lowercase(), c.reference.to_lowercase());
270
        self.words.iter().all(|w| title.contains(w) || reference.contains(w))
271
            && self.labels.iter().all(|l| c.labels.iter().any(|x| x.name.eq_ignore_ascii_case(l)))
272
            && self.assignees.iter().all(|a| c.assignees.iter().any(|x| x.eq_ignore_ascii_case(a)))
273
            && (self.state.is_empty() || c.state.eq_ignore_ascii_case(&self.state))
274
    }
275
}
276
657e7d5c Andy McCall ↶ 277
/// Filter and cut the columns as `view` says.
278
fn shape(columns: &mut [ColumnView], view: &BoardQuery) {
6a306cd0 Andy McCall ↶ 279
    let filter = CardFilter::of(view);
657e7d5c Andy McCall ↶ 280
    for col in columns.iter_mut() {
281
        col.total = col.cards.len();
6a306cd0 Andy McCall ↶ 282
        if !filter.is_empty() {
283
            col.cards.retain(|c| filter.keeps(c));
439ecd87 Andy McCall ↶ 284
        } else if col.cards.len() > COLUMN_SHOWN && view.all != Some(col.column.id) && !view.archived() {
657e7d5c Andy McCall ↶ 285
            // Cards join a column at its end: the newest are the last.
286
            let cut = col.cards.len() - COLUMN_SHOWN;
287
            col.cards.drain(..cut);
288
        }
289
        col.hidden = col.total - col.cards.len();
290
    }
291
}
292
e1ec9fbf Andy McCall ↶ 293
#[derive(Template)]
294
#[template(path = "project.html")]
295
pub struct BoardPage {
296
    shell: Shell,
297
    project: pdb::Project,
298
    columns: Vec<ColumnView>,
299
    /// The owner's repositories the viewer can read, for adding cards.
300
    repos: Vec<String>,
301
    /// Changes cards and columns (an open project).
302
    can_edit: bool,
303
    /// Changes the settings (to reopen a closed project too).
304
    can_manage: bool,
305
    notice: Option<String>,
306
    error: Option<String>,
b1e92a62 Andy McCall ↶ 307
    /// Owners the viewer may move the project to (#125): themselves and the
308
    /// organisations they belong to, but not its owner now.
309
    transfer_to: Vec<String>,
657e7d5c Andy McCall ↶ 310
    /// The filter the page shows (#293), and whether one is set.
311
    q: String,
312
    state: String,
313
    filtered: bool,
439ecd87 Andy McCall ↶ 314
    /// The archive view: archived cards, each restorable (#293).
315
    archived: bool,
316
    /// Archived cards on the whole board.
317
    archived_total: usize,
e1ec9fbf Andy McCall ↶ 318
}
319
657e7d5c Andy McCall ↶ 320
#[allow(clippy::too_many_arguments)]
e1ec9fbf Andy McCall ↶ 321
async fn board(
322
    app: &Shared,
323
    shell: Shell,
324
    viewer: &Viewer,
325
    owner: &str,
326
    number: i64,
327
    notice: Option<String>,
328
    error: Option<String>,
657e7d5c Andy McCall ↶ 329
    view: &BoardQuery,
e1ec9fbf Andy McCall ↶ 330
) -> Result<Page<BoardPage>, Error> {
331
    let e = |e| Error::from_db(shell.clone(), e);
332
    let r = rights(app, &shell, viewer, owner).await?;
333
    let project = pdb::get(&app.db, owner, number)
334
        .await
335
        .map_err(e)?
336
        .filter(|p| p.public || r.member)
337
        .ok_or_else(|| Error::not_found(shell.clone()))?;
439ecd87 Andy McCall ↶ 338
    let archived = view.archived();
339
    let (mut columns, repos) = board_columns(app, viewer.account(), owner, &project, archived).await.map_err(e)?;
657e7d5c Andy McCall ↶ 340
    shape(&mut columns, view);
439ecd87 Andy McCall ↶ 341
    let archived_total = columns.iter().map(|c| c.archived).sum();
ef20fdc1 Andy McCall ↶ 342
    let can_edit = r.edit && !project.closed;
b1e92a62 Andy McCall ↶ 343
    let mut transfer_to = Vec::new();
344
    if let (true, Some(a)) = (r.edit, viewer.account()) {
345
        transfer_to.push(a.username.clone());
346
        let orgs = db::accounts::orgs_of(&app.db, a.id).await.map_err(e)?;
347
        transfer_to.extend(orgs.into_iter().map(|(o, _)| o.name));
348
        transfer_to.retain(|o| o != owner);
349
    }
657e7d5c Andy McCall ↶ 350
    let (q, state) = (view.text(), view.state());
351
    let filtered = !q.is_empty() || !state.is_empty();
439ecd87 Andy McCall ↶ 352
    Ok(Page(BoardPage {
353
        shell,
354
        project,
355
        columns,
356
        repos,
357
        can_edit,
358
        can_manage: r.edit,
359
        notice,
360
        error,
361
        transfer_to,
362
        q,
363
        state,
364
        filtered,
365
        archived,
366
        archived_total,
367
    }))
ef20fdc1 Andy McCall ↶ 368
}
369
370
/// A project's columns with the cards `account` may see, and the owner's
439ecd87 Andy McCall ↶ 371
/// repositories it can read (for adding cards). `archived`: the archived
372
/// cards instead of those on the board (#293); each column counts its
373
/// archived cards either way.
ef20fdc1 Andy McCall ↶ 374
pub async fn board_columns(
375
    app: &Shared,
376
    account: Option<&db::accounts::Account>,
377
    owner: &str,
378
    project: &pdb::Project,
439ecd87 Andy McCall ↶ 379
    archived: bool,
ef20fdc1 Andy McCall ↶ 380
) -> sqlx::Result<(Vec<ColumnView>, Vec<String>)> {
e1ec9fbf Andy McCall ↶ 381
    let mut readable: std::collections::HashMap<i64, db::repos::RepoRow> = Default::default();
ef20fdc1 Andy McCall ↶ 382
    for row in db::repos::list_by_owner(&app.db, owner).await? {
383
        let role = roles::role_for(&app.db, account, &row).await?;
e1ec9fbf Andy McCall ↶ 384
        if roles::allows(role, Access::Read) {
385
            readable.insert(row.id, row);
386
        }
387
    }
439ecd87 Andy McCall ↶ 388
    let all = pdb::cards(&app.db, project.id).await?;
389
    let archived_in = |column: i64| all.iter().filter(|c| c.column_id == column && c.archived_ms.is_some()).count();
390
    let cards: Vec<&pdb::Card> = all.iter().filter(|c| c.archived_ms.is_some() == archived).collect();
6a306cd0 Andy McCall ↶ 391
    // What the cards show, read once per repository, not per card: a
392
    // board of 300 cards made 300 queries.
393
    let mut shown: std::collections::HashMap<(i64, bool, i64), Shown> = Default::default();
394
    let mut repo_ids: Vec<(i64, bool)> =
395
        cards.iter().filter_map(|c| Some((c.repo_id?, c.kind == "issue"))).filter(|(rid, _)| readable.contains_key(rid)).collect();
396
    repo_ids.sort();
397
    repo_ids.dedup();
398
    for (rid, issues) in repo_ids {
399
        shown.extend(shown_in(app, rid, issues).await?.into_iter().map(|(n, s)| ((rid, issues, n), s)));
400
    }
e1ec9fbf Andy McCall ↶ 401
    let mut columns = Vec::new();
ef20fdc1 Andy McCall ↶ 402
    for column in pdb::columns(&app.db, project.id).await? {
e1ec9fbf Andy McCall ↶ 403
        let mut views = Vec::new();
439ecd87 Andy McCall ↶ 404
        for card in cards.iter().copied().filter(|c| c.column_id == column.id) {
e1ec9fbf Andy McCall ↶ 405
            match (card.kind.as_str(), card.repo_id, card.number) {
406
                ("note", _, _) => views.push(CardView {
407
                    card: card.clone(),
408
                    reference: String::new(),
409
                    url: String::new(),
410
                    title: card.note.clone(),
411
                    state: String::new(),
6a306cd0 Andy McCall ↶ 412
                    labels: Vec::new(),
413
                    assignees: Vec::new(),
e1ec9fbf Andy McCall ↶ 414
                }),
415
                (kind, Some(rid), Some(n)) => {
416
                    // Cards of repositories the viewer cannot read are not shown at all.
417
                    let Some(row) = readable.get(&rid) else { continue };
6a306cd0 Andy McCall ↶ 418
                    let Some(s) = shown.get(&(rid, kind == "issue", n)) else { continue };
e1ec9fbf Andy McCall ↶ 419
                    let slug = format!("{}/{}", row.owner, row.name);
420
                    views.push(CardView {
421
                        card: card.clone(),
422
                        reference: format!("{slug}#{n}"),
423
                        url: format!("/{slug}/{kind}/{n}"),
6a306cd0 Andy McCall ↶ 424
                        title: s.title.clone(),
425
                        state: s.state.clone(),
426
                        labels: s.labels.clone(),
427
                        assignees: s.assignees.clone(),
e1ec9fbf Andy McCall ↶ 428
                    });
429
                }
430
                _ => {}
431
            }
432
        }
657e7d5c Andy McCall ↶ 433
        let total = views.len();
439ecd87 Andy McCall ↶ 434
        let archived = archived_in(column.id);
946fe7a0 Andy McCall ↶ 435
        let items: Vec<&CardView> = views.iter().filter(|v| v.card.kind != "note").collect();
436
        let finished = !items.is_empty() && items.iter().all(|v| matches!(v.state.as_str(), "closed" | "landed"));
437
        columns.push(ColumnView { column, cards: views, hidden: 0, total, archived, finished });
e1ec9fbf Andy McCall ↶ 438
    }
439
    let mut repos: Vec<String> = readable.values().map(|r| r.name.clone()).collect();
440
    repos.sort();
ef20fdc1 Andy McCall ↶ 441
    Ok((columns, repos))
6a306cd0 Andy McCall ↶ 442
}
443
444
/// What a card shows of an issue or a proposal.
445
struct Shown {
446
    title: String,
447
    state: String,
448
    labels: Vec<idb::Label>,
449
    assignees: Vec<String>,
450
}
451
452
/// A repository's issues (or proposals) as cards show them, by number.
453
async fn shown_in(app: &Shared, repo_id: i64, issues: bool) -> sqlx::Result<Vec<(i64, Shown)>> {
454
    use std::collections::HashMap;
455
    let mut out = Vec::new();
456
    if issues {
457
        let mut labels: HashMap<i64, Vec<idb::Label>> = HashMap::new();
458
        for (id, l) in idb::labels_by_issue(&app.db, repo_id).await? {
459
            labels.entry(id).or_default().push(l);
460
        }
461
        let mut assignees: HashMap<i64, Vec<String>> = HashMap::new();
462
        for (id, u) in idb::assignees_by_issue(&app.db, repo_id).await? {
463
            assignees.entry(id).or_default().push(u);
464
        }
465
        for i in idb::list(&app.db, repo_id).await? {
466
            let mut a = assignees.remove(&i.id).unwrap_or_default();
467
            a.sort();
468
            let s = Shown { labels: labels.remove(&i.id).unwrap_or_default(), assignees: a, title: i.title, state: i.state };
469
            out.push((i.number, s));
470
        }
471
    } else {
472
        let mut labels: HashMap<i64, Vec<idb::Label>> = HashMap::new();
473
        for (id, l) in idb::labels_by_proposal(&app.db, repo_id).await? {
474
            labels.entry(id).or_default().push(l);
475
        }
476
        for p in db::proposals::list(&app.db, repo_id, &[]).await? {
477
            let s = Shown { labels: labels.remove(&p.id).unwrap_or_default(), assignees: Vec::new(), title: p.title, state: p.state };
478
            out.push((p.number, s));
479
        }
480
    }
481
    Ok(out)
e1ec9fbf Andy McCall ↶ 482
}
483
657e7d5c Andy McCall ↶ 484
pub async fn show(
485
    State(app): State<Shared>,
486
    viewer: Viewer,
487
    Path((owner, number)): Path<(String, i64)>,
488
    Query(view): Query<BoardQuery>,
489
) -> Result<Response, Error> {
e1ec9fbf Andy McCall ↶ 490
    let shell = Shell::new(&app, &format!("/projects/{owner}/{number}"), &viewer);
b1e92a62 Andy McCall ↶ 491
    // A board transferred away (#125): its old address goes to its new one.
492
    let e = |e| Error::from_db(shell.clone(), e);
493
    if pdb::get(&app.db, &owner, number).await.map_err(e)?.is_none() {
494
        if let Some(p) = pdb::redirected(&app.db, &owner, number).await.map_err(e)? {
495
            return Ok(Redirect::permanent(&format!("/projects/{}/{}", p.owner, p.number)).into_response());
496
        }
497
    }
657e7d5c Andy McCall ↶ 498
    Ok(board(&app, shell, &viewer, &owner, number, None, None, &view).await?.into_response())
e1ec9fbf Andy McCall ↶ 499
}
500
501
#[derive(Deserialize)]
502
pub struct BoardForm {
503
    #[serde(rename = "_csrf")]
504
    csrf_token: String,
505
    action: String,
506
    #[serde(default)]
507
    card: Option<i64>,
508
    #[serde(default)]
509
    column: Option<i64>,
510
    #[serde(default)]
511
    name: String,
512
    /// `repo#12`, or `#12` with `repo`.
513
    #[serde(default)]
514
    reference: String,
515
    #[serde(default)]
516
    repo: String,
517
    #[serde(default)]
518
    note: String,
946fe7a0 Andy McCall ↶ 519
    /// Automatic archiving: `finished` (the default), `days` or `never`.
e1ec9fbf Andy McCall ↶ 520
    #[serde(default)]
946fe7a0 Andy McCall ↶ 521
    mode: String,
522
    #[serde(default)]
e1ec9fbf Andy McCall ↶ 523
    title: String,
524
    #[serde(default)]
525
    description: String,
526
    #[serde(default)]
527
    private: Option<String>,
528
    #[serde(default)]
529
    closed: Option<String>,
b1e92a62 Andy McCall ↶ 530
    /// The owner to transfer the project to (#125).
531
    #[serde(default)]
532
    to: String,
439ecd87 Andy McCall ↶ 533
    /// Days, for archiving a column's older cards (#293); empty is never.
534
    #[serde(default)]
535
    days: String,
e1ec9fbf Andy McCall ↶ 536
}
537
538
/// `repo#12` or `#12` (with a repository chosen) to (repository, number).
539
fn parse_reference(reference: &str, repo: &str) -> Option<(String, i64)> {
540
    let r = reference.trim();
541
    let (name, n) = r.split_once('#')?;
542
    let name = if name.is_empty() { repo.trim() } else { name.trim() };
543
    let n: i64 = n.trim().parse().ok()?;
544
    (!name.is_empty() && n > 0 && !name.contains('/')).then(|| (name.to_string(), n))
ef20fdc1 Andy McCall ↶ 545
}
546
547
/// Add a note, or the issue or proposal `reference` names (`repo#12`, or
548
/// `#12` with `repo`), to a column. `Ok(Err(why))` for what the caller
549
/// should be told: an unknown repository or number, or a card already there.
550
#[allow(clippy::too_many_arguments)]
551
pub async fn add_card(
552
    app: &Shared,
553
    account: Option<&db::accounts::Account>,
554
    owner: &str,
555
    project_id: i64,
556
    column_id: i64,
557
    reference: &str,
558
    repo: &str,
559
    note: &str,
560
    actor: &str,
561
) -> sqlx::Result<Result<pdb::Card, String>> {
562
    if !note.trim().is_empty() {
563
        let note: String = note.trim().chars().take(500).collect();
564
        pdb::add_card(
565
            &app.db,
566
            project_id,
567
            pdb::NewCard { column_id, kind: "note", repo_id: None, number: None, note: &note, added_by: actor },
568
        )
569
        .await?;
570
        return Ok(Ok(newest_card(app, project_id).await?));
571
    }
572
    let Some((repo, n)) = parse_reference(reference, repo) else {
573
        return Ok(Err("Name an issue or proposal as repo#12, or write a note.".into()));
574
    };
575
    let Some(row) = db::repos::get(&app.db, owner, &repo).await? else { return Ok(Err(format!("{owner} has no repository {repo}."))) };
576
    let role = roles::role_for(&app.db, account, &row).await?;
577
    let (issues, proposals) = db::issues::numbers(&app.db, row.id).await?;
578
    let kind = if issues.contains(&n) {
579
        "issue"
580
    } else if proposals.contains(&n) {
581
        "proposal"
582
    } else {
583
        return Ok(Err(format!("{repo} has no issue or proposal #{n}.")));
584
    };
585
    if !roles::allows(role, Access::Read) {
586
        return Ok(Err(format!("{repo} has no issue or proposal #{n}.")));
587
    }
588
    if !pdb::add_card(
589
        &app.db,
590
        project_id,
591
        pdb::NewCard { column_id, kind, repo_id: Some(row.id), number: Some(n), note: "", added_by: actor },
592
    )
593
    .await?
594
    {
595
        return Ok(Err(format!("{repo}#{n} is already on this project.")));
596
    }
597
    Ok(Ok(newest_card(app, project_id).await?))
598
}
599
600
async fn newest_card(app: &Shared, project_id: i64) -> sqlx::Result<pdb::Card> {
5d90e0e0 Andy McCall 601
    sqlx::query_as("SELECT * FROM project_cards WHERE project_id = $1 ORDER BY id DESC LIMIT 1").bind(project_id).fetch_one(&app.db).await
e1ec9fbf Andy McCall ↶ 602
}
603
604
pub async fn act(
605
    State(app): State<Shared>,
606
    viewer: Viewer,
607
    Path((owner, number)): Path<(String, i64)>,
608
    Form(f): Form<BoardForm>,
609
) -> Result<Response, Error> {
610
    let shell = Shell::new(&app, &format!("/projects/{owner}/{number}"), &viewer);
611
    csrf(&viewer, &f.csrf_token, &shell)?;
612
    let r = rights(&app, &shell, &viewer, &owner).await?;
613
    let e = |e| Error::from_db(shell.clone(), e);
614
    let project = pdb::get(&app.db, &owner, number)
615
        .await
616
        .map_err(e)?
617
        .filter(|p| p.public || r.member)
618
        .ok_or_else(|| Error::not_found(shell.clone()))?;
619
    if !r.edit {
620
        return Err(Error::not_found(shell));
621
    }
b1e92a62 Andy McCall ↶ 622
    if project.closed && !matches!(f.action.as_str(), "settings" | "delete" | "transfer") {
657e7d5c Andy McCall ↶ 623
        return Ok(board(
624
            &app,
625
            shell,
626
            &viewer,
627
            &owner,
628
            number,
629
            None,
630
            Some("This project is closed; reopen it to change it.".into()),
631
            &BoardQuery::default(),
632
        )
633
        .await?
634
        .into_response());
e1ec9fbf Andy McCall ↶ 635
    }
636
    let actor = viewer.account().map(|a| a.username.clone()).unwrap_or_default();
637
    let columns = pdb::columns(&app.db, project.id).await.map_err(e)?;
638
    let column = f.column.filter(|c| columns.iter().any(|x| x.id == *c)).or(columns.first().map(|c| c.id));
639
    let mut notice = None;
640
    let mut error = None;
641
    match f.action.as_str() {
642
        "add" => {
643
            let Some(column_id) = column else { return Err(Error::bad(shell, "no column")) };
ef20fdc1 Andy McCall ↶ 644
            if let Err(msg) =
645
                add_card(&app, viewer.account(), &owner, project.id, column_id, &f.reference, &f.repo, &f.note, &actor).await.map_err(e)?
646
            {
647
                error = Some(msg);
e1ec9fbf Andy McCall ↶ 648
            }
649
        }
650
        "move" => {
651
            if let (Some(card), Some(col)) = (f.card, f.column) {
652
                pdb::move_card(&app.db, project.id, card, col).await.map_err(e)?;
653
            }
654
        }
655
        "up" | "down" => {
656
            if let Some(card) = f.card {
657
                pdb::shift_card(&app.db, project.id, card, if f.action == "up" { -1 } else { 1 }).await.map_err(e)?;
658
            }
659
        }
660
        "remove" => {
661
            if let Some(card) = f.card {
662
                pdb::remove_card(&app.db, project.id, card).await.map_err(e)?;
439ecd87 Andy McCall ↶ 663
            }
664
        }
665
        "archive" => {
666
            if let Some(card) = f.card {
667
                pdb::archive_cards(&app.db, project.id, &[card]).await.map_err(e)?;
668
            }
669
        }
670
        "restore" => {
671
            if let Some(card) = f.card {
672
                pdb::restore_card(&app.db, project.id, card).await.map_err(e)?;
673
            }
674
            return Ok(Redirect::to(&format!("/projects/{owner}/{number}?archived=1")).into_response());
675
        }
676
        "archive_older" | "archive_after" => {
677
            let Some(col) = f.column else { return Err(Error::bad(shell, "no column")) };
946fe7a0 Andy McCall ↶ 678
            let days = match (f.action.as_str(), f.mode.as_str(), f.days.trim()) {
679
                ("archive_after", "finished", _) | ("archive_after", "", "") => None,
680
                ("archive_after", "never", _) => Some(pdb::NEVER),
681
                (_, _, d) => match d.parse::<i64>() {
439ecd87 Andy McCall ↶ 682
                    Ok(n) if (0..=3650).contains(&n) => Some(n),
683
                    _ => {
684
                        error = Some("Give a number of days, 0 to 3650.".into());
685
                        None
686
                    }
687
                },
688
            };
689
            let name = columns.iter().find(|c| c.id == col).map(|c| c.name.clone()).unwrap_or_default();
690
            if error.is_none() && f.action == "archive_after" {
691
                pdb::set_archive_after(&app.db, project.id, col, days).await.map_err(e)?;
692
                notice = Some(match days {
946fe7a0 Andy McCall ↶ 693
                    Some(pdb::NEVER) => format!("{name} keeps its cards until you archive them."),
439ecd87 Andy McCall ↶ 694
                    Some(n) => format!("{name} archives its cards {n} day{} after they reach it.", if n == 1 { "" } else { "s" }),
946fe7a0 Andy McCall ↶ 695
                    None => format!("{name} archives finished cards {} days after they reach it.", pdb::FINISHED_KEPT_DAYS),
439ecd87 Andy McCall ↶ 696
                });
697
            } else if let (None, Some(days)) = (&error, days) {
698
                let now = db::now_ms();
699
                let ids: Vec<i64> = pdb::cards(&app.db, project.id)
700
                    .await
701
                    .map_err(e)?
702
                    .into_iter()
703
                    .filter(|c| c.column_id == col && c.archived_ms.is_none() && pdb::older_than(c, days, now))
704
                    .map(|c| c.id)
705
                    .collect();
706
                let n = pdb::archive_cards(&app.db, project.id, &ids).await.map_err(e)?;
707
                let detail = format!("{n} card(s) of {name} older than {days} days");
708
                db::accounts::audit(&app.db, viewer.account(), "project.cards_archived", &format!("{owner}/{number}"), &detail).await.ok();
709
                notice = Some(format!("Archived {n} card{} from {name}.", if n == 1 { "" } else { "s" }));
e1ec9fbf Andy McCall ↶ 710
            }
711
        }
712
        "add_column" => {
713
            let name = f.name.trim();
714
            if name.is_empty() || name.len() > 40 {
715
                error = Some("A column has a name of up to 40 characters.".into());
716
            } else {
717
                pdb::add_column(&app.db, project.id, name).await.map_err(e)?;
718
            }
719
        }
720
        "rename_column" => {
721
            if let (Some(col), name) = (f.column, f.name.trim()) {
722
                if !name.is_empty() && name.len() <= 40 {
723
                    pdb::rename_column(&app.db, project.id, col, name).await.map_err(e)?;
724
                }
725
            }
726
        }
727
        "left" | "right" => {
728
            if let Some(col) = f.column {
729
                pdb::shift_column(&app.db, project.id, col, if f.action == "left" { -1 } else { 1 }).await.map_err(e)?;
730
            }
731
        }
732
        "remove_column" => {
733
            if let Some(col) = f.column {
734
                if !pdb::remove_column(&app.db, project.id, col).await.map_err(e)? {
735
                    error = Some("A project keeps at least one column.".into());
736
                }
737
            }
738
        }
739
        "settings" => {
740
            let title = if f.title.trim().is_empty() { project.title.clone() } else { f.title.trim().chars().take(100).collect() };
741
            pdb::set(&app.db, project.id, &title, f.description.trim(), f.private.is_none(), f.closed.is_some()).await.map_err(e)?;
742
            notice = Some("Saved.".into());
b1e92a62 Andy McCall ↶ 743
        }
744
        "transfer" => {
745
            let to = f.to.trim();
746
            match rights_of(&app, viewer.account(), to).await.map_err(e)? {
747
                _ if to == owner => error = Some(format!("It is {owner}'s already.")),
748
                Some(t) if t.edit => {
749
                    let moved = pdb::transfer(&app.db, project.id, to).await.map_err(e)?;
750
                    let detail = format!("{owner}/{number} to {to}/{}", moved.number);
751
                    db::accounts::audit(&app.db, viewer.account(), "project.transferred", &detail, &project.title).await.ok();
752
                    return Ok(Redirect::to(&format!("/projects/{to}/{}", moved.number)).into_response());
753
                }
754
                _ => error = Some(format!("You cannot make projects under {to}, so you cannot move this one there.")),
755
            }
e1ec9fbf Andy McCall ↶ 756
        }
757
        "delete" => {
758
            pdb::delete(&app.db, project.id).await.map_err(e)?;
759
            db::accounts::audit(&app.db, viewer.account(), "project.deleted", &format!("{owner}/{number}"), &project.title).await.ok();
760
            return Ok(Redirect::to(&format!("/projects/{owner}")).into_response());
761
        }
762
        _ => return Err(Error::bad(shell, "unknown action")),
763
    }
764
    if notice.is_none() && error.is_none() {
765
        // Back to the board, so a reload does not repeat the action.
766
        return Ok(Redirect::to(&format!("/projects/{owner}/{number}")).into_response());
767
    }
657e7d5c Andy McCall ↶ 768
    Ok(board(&app, shell, &viewer, &owner, number, notice, error, &BoardQuery::default()).await?.into_response())
e1ec9fbf Andy McCall ↶ 769
}
770
771
/// The projects an issue or proposal is on that the viewer may see, with
772
/// their column.
773
pub async fn placements_for(app: &Shared, viewer: &Viewer, repo: &db::repos::RepoRow, number: i64) -> Vec<(pdb::Project, String)> {
774
    let Ok(all) = pdb::placements(&app.db, repo.id, number).await else { return vec![] };
775
    let mut out = Vec::new();
776
    for (p, col) in all {
777
        let visible = p.public
778
            || viewer.is_admin()
779
            || match viewer.account() {
780
                Some(v) if v.username == p.owner => true,
781
                Some(v) => match db::accounts::org_by_name(&app.db, &p.owner).await.ok().flatten() {
782
                    Some(o) => db::accounts::org_role(&app.db, o.id, v.id).await.ok().flatten().is_some(),
783
                    None => false,
784
                },
785
                None => false,
786
            };
787
        if visible {
788
            out.push((p, col));
789
        }
790
    }
791
    out
792
}
793
794
#[cfg(test)]
795
mod tests {
796
    use super::parse_reference;
797
798
    #[test]
799
    fn references() {
800
        assert_eq!(parse_reference("oxygen#12", ""), Some(("oxygen".into(), 12)));
801
        assert_eq!(parse_reference("#7", "hub"), Some(("hub".into(), 7)));
802
        assert_eq!(parse_reference(" hub # 3 ", ""), Some(("hub".into(), 3)));
803
        assert_eq!(parse_reference("#7", ""), None, "a repository is needed");
804
        assert_eq!(parse_reference("other/repo#1", ""), None, "only the owner's repositories");
805
        assert_eq!(parse_reference("hub#0", ""), None);
806
        assert_eq!(parse_reference("hub", ""), None);
807
    }
808
}
a1b98695 Andy McCall ↶ 809
810
#[derive(Deserialize)]
811
pub struct PlaceForm {
812
    #[serde(rename = "_csrf")]
813
    csrf_token: String,
814
    /// The project's number among its owner's.
815
    project: i64,
816
    /// `add` or `remove`.
817
    action: String,
818
}
819
820
/// Put an issue or proposal on one of its repository owner's projects (in
821
/// the first column), or take it off, from its own page.
822
async fn place(
823
    app: Shared,
824
    viewer: Viewer,
825
    owner: String,
826
    name: String,
827
    kind: &'static str,
828
    number: i64,
829
    f: PlaceForm,
830
) -> Result<Response, Error> {
831
    let page = format!("/{owner}/{name}/{kind}/{number}");
832
    let shell = Shell::new(&app, &page, &viewer);
833
    csrf(&viewer, &f.csrf_token, &shell)?;
834
    let (_, row, _) = super::lookup(&app, &shell, &viewer, &owner, &name).await?;
835
    let r = rights(&app, &shell, &viewer, &row.owner).await?;
836
    if !r.edit {
837
        return Err(Error::not_found(shell));
838
    }
839
    let e = |e| Error::from_db(shell.clone(), e);
840
    let project = pdb::get(&app.db, &row.owner, f.project).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
841
    let actor = viewer.account().map(|a| a.username.clone()).unwrap_or_default();
842
    let mut error = None;
843
    match f.action.as_str() {
844
        "add" => {
845
            let columns = pdb::columns(&app.db, project.id).await.map_err(e)?;
846
            let Some(first) = columns.first() else { return Err(Error::bad(shell, "that project has no columns")) };
847
            if let Err(msg) =
848
                add_card(&app, viewer.account(), &row.owner, project.id, first.id, &format!("{}#{number}", row.name), &row.name, "", &actor)
849
                    .await
850
                    .map_err(e)?
851
            {
852
                error = Some(msg);
853
            }
854
        }
855
        "remove" => {
856
            for c in pdb::cards(&app.db, project.id).await.map_err(e)? {
857
                if c.repo_id == Some(row.id) && c.number == Some(number) {
858
                    pdb::remove_card(&app.db, project.id, c.id).await.map_err(e)?;
859
                }
860
            }
861
        }
862
        _ => return Err(Error::bad(shell, "add or remove")),
863
    }
864
    let to = match error {
865
        Some(m) => format!("{page}?error={}", super::settings::urlencode(&m)),
866
        None => page,
867
    };
868
    Ok(Redirect::to(&to).into_response())
869
}
870
871
/// `POST /{owner}/{name}/proposal/{number}/project`.
872
pub async fn place_proposal(
873
    State(app): State<Shared>,
874
    viewer: Viewer,
875
    Path((owner, name, number)): Path<(String, String, i64)>,
876
    Form(f): Form<PlaceForm>,
877
) -> Result<Response, Error> {
878
    place(app, viewer, owner, name, "proposal", number, f).await
879
}
880
881
/// `POST /{owner}/{name}/issue/{number}/project`.
882
pub async fn place_issue(
883
    State(app): State<Shared>,
884
    viewer: Viewer,
885
    Path((owner, name, number)): Path<(String, String, i64)>,
886
    Form(f): Form<PlaceForm>,
887
) -> Result<Response, Error> {
888
    place(app, viewer, owner, name, "issue", number, f).await
889
}
890
891
/// The owner's open projects `viewer` may add an item to that it is not on
892
/// yet; `None` when the viewer may not change the owner's projects at all.
893
pub async fn project_choices(
894
    app: &Shared,
895
    viewer: &Viewer,
896
    repo: &db::repos::RepoRow,
897
    placed: &[(pdb::Project, String)],
898
) -> Option<Vec<pdb::Project>> {
899
    let Ok(Some(r)) = rights_of(app, viewer.account(), &repo.owner).await else { return None };
900
    if !r.edit {
901
        return None;
902
    }
903
    Some(
904
        pdb::of_owner(&app.db, &repo.owner)
905
            .await
906
            .unwrap_or_default()
907
            .into_iter()
908
            .filter(|p| !p.closed && !placed.iter().any(|(q, _)| q.id == p.id))
909
            .collect(),
910
    )
911
}