OXYGENHUB
# 6a306cd03fc1 oxygenhub / crates / hub / src / web / projects.rs
30.8 KiB · Rust · last changed Board cards show labels and assignees, and the board filters by them (refs #293) 12 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,
e1ec9fbf Andy McCall ↶ 198
}
199
657e7d5c Andy McCall ↶ 200
/// A column longer than this shows its newest cards only, with "show all"
201
/// (#293): a board's Done column otherwise grows without end.
202
pub const COLUMN_SHOWN: usize = 30;
203
204
/// How the board page shows its cards (#293).
205
#[derive(Deserialize, Default)]
206
pub struct BoardQuery {
207
    /// The column shown whole.
208
    #[serde(default)]
209
    all: Option<i64>,
6a306cd0 Andy McCall ↶ 210
    /// Only cards whose title or reference holds these words, and with
211
    /// `label:NAME`, `assignee:NAME` or `state:STATE` as the issue list takes.
657e7d5c Andy McCall ↶ 212
    #[serde(default)]
213
    q: Option<String>,
214
    /// Only cards in this state (`open`, `closed`, `landed`…).
215
    #[serde(default)]
216
    state: Option<String>,
217
}
218
219
impl BoardQuery {
220
    fn text(&self) -> String {
221
        self.q.as_deref().map(str::trim).unwrap_or("").to_string()
222
    }
223
    fn state(&self) -> String {
224
        self.state.as_deref().map(str::trim).unwrap_or("").to_ascii_lowercase()
225
    }
226
}
227
6a306cd0 Andy McCall ↶ 228
/// The board filter's `label:`, `assignee:` and `state:` terms, and its words.
229
#[derive(Default)]
230
struct CardFilter {
231
    labels: Vec<String>,
232
    assignees: Vec<String>,
233
    state: String,
234
    words: Vec<String>,
235
}
236
237
impl CardFilter {
238
    fn of(view: &BoardQuery) -> CardFilter {
239
        let mut f = CardFilter { state: view.state(), ..Default::default() };
240
        for tok in view.text().split_whitespace() {
241
            match tok.split_once(':') {
242
                Some(("label", v)) if !v.is_empty() => f.labels.push(v.to_lowercase()),
243
                Some(("assignee", v)) if !v.is_empty() => f.assignees.push(v.trim_start_matches('@').to_lowercase()),
244
                Some(("state", v)) if !v.is_empty() => f.state = v.to_lowercase(),
245
                _ => f.words.push(tok.to_lowercase()),
246
            }
247
        }
248
        f
249
    }
250
251
    fn is_empty(&self) -> bool {
252
        self.labels.is_empty() && self.assignees.is_empty() && self.state.is_empty() && self.words.is_empty()
253
    }
254
255
    /// Every term holds: each word in the title or reference, each label
256
    /// and assignee among the card's, and its state.
257
    fn keeps(&self, c: &CardView) -> bool {
258
        let (title, reference) = (c.title.to_lowercase(), c.reference.to_lowercase());
259
        self.words.iter().all(|w| title.contains(w) || reference.contains(w))
260
            && self.labels.iter().all(|l| c.labels.iter().any(|x| x.name.eq_ignore_ascii_case(l)))
261
            && self.assignees.iter().all(|a| c.assignees.iter().any(|x| x.eq_ignore_ascii_case(a)))
262
            && (self.state.is_empty() || c.state.eq_ignore_ascii_case(&self.state))
263
    }
264
}
265
657e7d5c Andy McCall ↶ 266
/// Filter and cut the columns as `view` says.
267
fn shape(columns: &mut [ColumnView], view: &BoardQuery) {
6a306cd0 Andy McCall ↶ 268
    let filter = CardFilter::of(view);
657e7d5c Andy McCall ↶ 269
    for col in columns.iter_mut() {
270
        col.total = col.cards.len();
6a306cd0 Andy McCall ↶ 271
        if !filter.is_empty() {
272
            col.cards.retain(|c| filter.keeps(c));
657e7d5c Andy McCall ↶ 273
        } else if col.cards.len() > COLUMN_SHOWN && view.all != Some(col.column.id) {
274
            // Cards join a column at its end: the newest are the last.
275
            let cut = col.cards.len() - COLUMN_SHOWN;
276
            col.cards.drain(..cut);
277
        }
278
        col.hidden = col.total - col.cards.len();
279
    }
280
}
281
e1ec9fbf Andy McCall ↶ 282
#[derive(Template)]
283
#[template(path = "project.html")]
284
pub struct BoardPage {
285
    shell: Shell,
286
    project: pdb::Project,
287
    columns: Vec<ColumnView>,
288
    /// The owner's repositories the viewer can read, for adding cards.
289
    repos: Vec<String>,
290
    /// Changes cards and columns (an open project).
291
    can_edit: bool,
292
    /// Changes the settings (to reopen a closed project too).
293
    can_manage: bool,
294
    notice: Option<String>,
295
    error: Option<String>,
b1e92a62 Andy McCall ↶ 296
    /// Owners the viewer may move the project to (#125): themselves and the
297
    /// organisations they belong to, but not its owner now.
298
    transfer_to: Vec<String>,
657e7d5c Andy McCall ↶ 299
    /// The filter the page shows (#293), and whether one is set.
300
    q: String,
301
    state: String,
302
    filtered: bool,
e1ec9fbf Andy McCall ↶ 303
}
304
657e7d5c Andy McCall ↶ 305
#[allow(clippy::too_many_arguments)]
e1ec9fbf Andy McCall ↶ 306
async fn board(
307
    app: &Shared,
308
    shell: Shell,
309
    viewer: &Viewer,
310
    owner: &str,
311
    number: i64,
312
    notice: Option<String>,
313
    error: Option<String>,
657e7d5c Andy McCall ↶ 314
    view: &BoardQuery,
e1ec9fbf Andy McCall ↶ 315
) -> Result<Page<BoardPage>, Error> {
316
    let e = |e| Error::from_db(shell.clone(), e);
317
    let r = rights(app, &shell, viewer, owner).await?;
318
    let project = pdb::get(&app.db, owner, number)
319
        .await
320
        .map_err(e)?
321
        .filter(|p| p.public || r.member)
322
        .ok_or_else(|| Error::not_found(shell.clone()))?;
657e7d5c Andy McCall ↶ 323
    let (mut columns, repos) = board_columns(app, viewer.account(), owner, &project).await.map_err(e)?;
324
    shape(&mut columns, view);
ef20fdc1 Andy McCall ↶ 325
    let can_edit = r.edit && !project.closed;
b1e92a62 Andy McCall ↶ 326
    let mut transfer_to = Vec::new();
327
    if let (true, Some(a)) = (r.edit, viewer.account()) {
328
        transfer_to.push(a.username.clone());
329
        let orgs = db::accounts::orgs_of(&app.db, a.id).await.map_err(e)?;
330
        transfer_to.extend(orgs.into_iter().map(|(o, _)| o.name));
331
        transfer_to.retain(|o| o != owner);
332
    }
657e7d5c Andy McCall ↶ 333
    let (q, state) = (view.text(), view.state());
334
    let filtered = !q.is_empty() || !state.is_empty();
335
    Ok(Page(BoardPage { shell, project, columns, repos, can_edit, can_manage: r.edit, notice, error, transfer_to, q, state, filtered }))
ef20fdc1 Andy McCall ↶ 336
}
337
338
/// A project's columns with the cards `account` may see, and the owner's
339
/// repositories it can read (for adding cards).
340
pub async fn board_columns(
341
    app: &Shared,
342
    account: Option<&db::accounts::Account>,
343
    owner: &str,
344
    project: &pdb::Project,
345
) -> sqlx::Result<(Vec<ColumnView>, Vec<String>)> {
e1ec9fbf Andy McCall ↶ 346
    let mut readable: std::collections::HashMap<i64, db::repos::RepoRow> = Default::default();
ef20fdc1 Andy McCall ↶ 347
    for row in db::repos::list_by_owner(&app.db, owner).await? {
348
        let role = roles::role_for(&app.db, account, &row).await?;
e1ec9fbf Andy McCall ↶ 349
        if roles::allows(role, Access::Read) {
350
            readable.insert(row.id, row);
351
        }
352
    }
ef20fdc1 Andy McCall ↶ 353
    let cards = pdb::cards(&app.db, project.id).await?;
6a306cd0 Andy McCall ↶ 354
    // What the cards show, read once per repository, not per card: a
355
    // board of 300 cards made 300 queries.
356
    let mut shown: std::collections::HashMap<(i64, bool, i64), Shown> = Default::default();
357
    let mut repo_ids: Vec<(i64, bool)> =
358
        cards.iter().filter_map(|c| Some((c.repo_id?, c.kind == "issue"))).filter(|(rid, _)| readable.contains_key(rid)).collect();
359
    repo_ids.sort();
360
    repo_ids.dedup();
361
    for (rid, issues) in repo_ids {
362
        shown.extend(shown_in(app, rid, issues).await?.into_iter().map(|(n, s)| ((rid, issues, n), s)));
363
    }
e1ec9fbf Andy McCall ↶ 364
    let mut columns = Vec::new();
ef20fdc1 Andy McCall ↶ 365
    for column in pdb::columns(&app.db, project.id).await? {
e1ec9fbf Andy McCall ↶ 366
        let mut views = Vec::new();
367
        for card in cards.iter().filter(|c| c.column_id == column.id) {
368
            match (card.kind.as_str(), card.repo_id, card.number) {
369
                ("note", _, _) => views.push(CardView {
370
                    card: card.clone(),
371
                    reference: String::new(),
372
                    url: String::new(),
373
                    title: card.note.clone(),
374
                    state: String::new(),
6a306cd0 Andy McCall ↶ 375
                    labels: Vec::new(),
376
                    assignees: Vec::new(),
e1ec9fbf Andy McCall ↶ 377
                }),
378
                (kind, Some(rid), Some(n)) => {
379
                    // Cards of repositories the viewer cannot read are not shown at all.
380
                    let Some(row) = readable.get(&rid) else { continue };
6a306cd0 Andy McCall ↶ 381
                    let Some(s) = shown.get(&(rid, kind == "issue", n)) else { continue };
e1ec9fbf Andy McCall ↶ 382
                    let slug = format!("{}/{}", row.owner, row.name);
383
                    views.push(CardView {
384
                        card: card.clone(),
385
                        reference: format!("{slug}#{n}"),
386
                        url: format!("/{slug}/{kind}/{n}"),
6a306cd0 Andy McCall ↶ 387
                        title: s.title.clone(),
388
                        state: s.state.clone(),
389
                        labels: s.labels.clone(),
390
                        assignees: s.assignees.clone(),
e1ec9fbf Andy McCall ↶ 391
                    });
392
                }
393
                _ => {}
394
            }
395
        }
657e7d5c Andy McCall ↶ 396
        let total = views.len();
397
        columns.push(ColumnView { column, cards: views, hidden: 0, total });
e1ec9fbf Andy McCall ↶ 398
    }
399
    let mut repos: Vec<String> = readable.values().map(|r| r.name.clone()).collect();
400
    repos.sort();
ef20fdc1 Andy McCall ↶ 401
    Ok((columns, repos))
6a306cd0 Andy McCall ↶ 402
}
403
404
/// What a card shows of an issue or a proposal.
405
struct Shown {
406
    title: String,
407
    state: String,
408
    labels: Vec<idb::Label>,
409
    assignees: Vec<String>,
410
}
411
412
/// A repository's issues (or proposals) as cards show them, by number.
413
async fn shown_in(app: &Shared, repo_id: i64, issues: bool) -> sqlx::Result<Vec<(i64, Shown)>> {
414
    use std::collections::HashMap;
415
    let mut out = Vec::new();
416
    if issues {
417
        let mut labels: HashMap<i64, Vec<idb::Label>> = HashMap::new();
418
        for (id, l) in idb::labels_by_issue(&app.db, repo_id).await? {
419
            labels.entry(id).or_default().push(l);
420
        }
421
        let mut assignees: HashMap<i64, Vec<String>> = HashMap::new();
422
        for (id, u) in idb::assignees_by_issue(&app.db, repo_id).await? {
423
            assignees.entry(id).or_default().push(u);
424
        }
425
        for i in idb::list(&app.db, repo_id).await? {
426
            let mut a = assignees.remove(&i.id).unwrap_or_default();
427
            a.sort();
428
            let s = Shown { labels: labels.remove(&i.id).unwrap_or_default(), assignees: a, title: i.title, state: i.state };
429
            out.push((i.number, s));
430
        }
431
    } else {
432
        let mut labels: HashMap<i64, Vec<idb::Label>> = HashMap::new();
433
        for (id, l) in idb::labels_by_proposal(&app.db, repo_id).await? {
434
            labels.entry(id).or_default().push(l);
435
        }
436
        for p in db::proposals::list(&app.db, repo_id, &[]).await? {
437
            let s = Shown { labels: labels.remove(&p.id).unwrap_or_default(), assignees: Vec::new(), title: p.title, state: p.state };
438
            out.push((p.number, s));
439
        }
440
    }
441
    Ok(out)
e1ec9fbf Andy McCall ↶ 442
}
443
657e7d5c Andy McCall ↶ 444
pub async fn show(
445
    State(app): State<Shared>,
446
    viewer: Viewer,
447
    Path((owner, number)): Path<(String, i64)>,
448
    Query(view): Query<BoardQuery>,
449
) -> Result<Response, Error> {
e1ec9fbf Andy McCall ↶ 450
    let shell = Shell::new(&app, &format!("/projects/{owner}/{number}"), &viewer);
b1e92a62 Andy McCall ↶ 451
    // A board transferred away (#125): its old address goes to its new one.
452
    let e = |e| Error::from_db(shell.clone(), e);
453
    if pdb::get(&app.db, &owner, number).await.map_err(e)?.is_none() {
454
        if let Some(p) = pdb::redirected(&app.db, &owner, number).await.map_err(e)? {
455
            return Ok(Redirect::permanent(&format!("/projects/{}/{}", p.owner, p.number)).into_response());
456
        }
457
    }
657e7d5c Andy McCall ↶ 458
    Ok(board(&app, shell, &viewer, &owner, number, None, None, &view).await?.into_response())
e1ec9fbf Andy McCall ↶ 459
}
460
461
#[derive(Deserialize)]
462
pub struct BoardForm {
463
    #[serde(rename = "_csrf")]
464
    csrf_token: String,
465
    action: String,
466
    #[serde(default)]
467
    card: Option<i64>,
468
    #[serde(default)]
469
    column: Option<i64>,
470
    #[serde(default)]
471
    name: String,
472
    /// `repo#12`, or `#12` with `repo`.
473
    #[serde(default)]
474
    reference: String,
475
    #[serde(default)]
476
    repo: String,
477
    #[serde(default)]
478
    note: String,
479
    #[serde(default)]
480
    title: String,
481
    #[serde(default)]
482
    description: String,
483
    #[serde(default)]
484
    private: Option<String>,
485
    #[serde(default)]
486
    closed: Option<String>,
b1e92a62 Andy McCall ↶ 487
    /// The owner to transfer the project to (#125).
488
    #[serde(default)]
489
    to: String,
e1ec9fbf Andy McCall ↶ 490
}
491
492
/// `repo#12` or `#12` (with a repository chosen) to (repository, number).
493
fn parse_reference(reference: &str, repo: &str) -> Option<(String, i64)> {
494
    let r = reference.trim();
495
    let (name, n) = r.split_once('#')?;
496
    let name = if name.is_empty() { repo.trim() } else { name.trim() };
497
    let n: i64 = n.trim().parse().ok()?;
498
    (!name.is_empty() && n > 0 && !name.contains('/')).then(|| (name.to_string(), n))
ef20fdc1 Andy McCall ↶ 499
}
500
501
/// Add a note, or the issue or proposal `reference` names (`repo#12`, or
502
/// `#12` with `repo`), to a column. `Ok(Err(why))` for what the caller
503
/// should be told: an unknown repository or number, or a card already there.
504
#[allow(clippy::too_many_arguments)]
505
pub async fn add_card(
506
    app: &Shared,
507
    account: Option<&db::accounts::Account>,
508
    owner: &str,
509
    project_id: i64,
510
    column_id: i64,
511
    reference: &str,
512
    repo: &str,
513
    note: &str,
514
    actor: &str,
515
) -> sqlx::Result<Result<pdb::Card, String>> {
516
    if !note.trim().is_empty() {
517
        let note: String = note.trim().chars().take(500).collect();
518
        pdb::add_card(
519
            &app.db,
520
            project_id,
521
            pdb::NewCard { column_id, kind: "note", repo_id: None, number: None, note: &note, added_by: actor },
522
        )
523
        .await?;
524
        return Ok(Ok(newest_card(app, project_id).await?));
525
    }
526
    let Some((repo, n)) = parse_reference(reference, repo) else {
527
        return Ok(Err("Name an issue or proposal as repo#12, or write a note.".into()));
528
    };
529
    let Some(row) = db::repos::get(&app.db, owner, &repo).await? else { return Ok(Err(format!("{owner} has no repository {repo}."))) };
530
    let role = roles::role_for(&app.db, account, &row).await?;
531
    let (issues, proposals) = db::issues::numbers(&app.db, row.id).await?;
532
    let kind = if issues.contains(&n) {
533
        "issue"
534
    } else if proposals.contains(&n) {
535
        "proposal"
536
    } else {
537
        return Ok(Err(format!("{repo} has no issue or proposal #{n}.")));
538
    };
539
    if !roles::allows(role, Access::Read) {
540
        return Ok(Err(format!("{repo} has no issue or proposal #{n}.")));
541
    }
542
    if !pdb::add_card(
543
        &app.db,
544
        project_id,
545
        pdb::NewCard { column_id, kind, repo_id: Some(row.id), number: Some(n), note: "", added_by: actor },
546
    )
547
    .await?
548
    {
549
        return Ok(Err(format!("{repo}#{n} is already on this project.")));
550
    }
551
    Ok(Ok(newest_card(app, project_id).await?))
552
}
553
554
async fn newest_card(app: &Shared, project_id: i64) -> sqlx::Result<pdb::Card> {
5d90e0e0 Andy McCall 555
    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 ↶ 556
}
557
558
pub async fn act(
559
    State(app): State<Shared>,
560
    viewer: Viewer,
561
    Path((owner, number)): Path<(String, i64)>,
562
    Form(f): Form<BoardForm>,
563
) -> Result<Response, Error> {
564
    let shell = Shell::new(&app, &format!("/projects/{owner}/{number}"), &viewer);
565
    csrf(&viewer, &f.csrf_token, &shell)?;
566
    let r = rights(&app, &shell, &viewer, &owner).await?;
567
    let e = |e| Error::from_db(shell.clone(), e);
568
    let project = pdb::get(&app.db, &owner, number)
569
        .await
570
        .map_err(e)?
571
        .filter(|p| p.public || r.member)
572
        .ok_or_else(|| Error::not_found(shell.clone()))?;
573
    if !r.edit {
574
        return Err(Error::not_found(shell));
575
    }
b1e92a62 Andy McCall ↶ 576
    if project.closed && !matches!(f.action.as_str(), "settings" | "delete" | "transfer") {
657e7d5c Andy McCall ↶ 577
        return Ok(board(
578
            &app,
579
            shell,
580
            &viewer,
581
            &owner,
582
            number,
583
            None,
584
            Some("This project is closed; reopen it to change it.".into()),
585
            &BoardQuery::default(),
586
        )
587
        .await?
588
        .into_response());
e1ec9fbf Andy McCall ↶ 589
    }
590
    let actor = viewer.account().map(|a| a.username.clone()).unwrap_or_default();
591
    let columns = pdb::columns(&app.db, project.id).await.map_err(e)?;
592
    let column = f.column.filter(|c| columns.iter().any(|x| x.id == *c)).or(columns.first().map(|c| c.id));
593
    let mut notice = None;
594
    let mut error = None;
595
    match f.action.as_str() {
596
        "add" => {
597
            let Some(column_id) = column else { return Err(Error::bad(shell, "no column")) };
ef20fdc1 Andy McCall ↶ 598
            if let Err(msg) =
599
                add_card(&app, viewer.account(), &owner, project.id, column_id, &f.reference, &f.repo, &f.note, &actor).await.map_err(e)?
600
            {
601
                error = Some(msg);
e1ec9fbf Andy McCall ↶ 602
            }
603
        }
604
        "move" => {
605
            if let (Some(card), Some(col)) = (f.card, f.column) {
606
                pdb::move_card(&app.db, project.id, card, col).await.map_err(e)?;
607
            }
608
        }
609
        "up" | "down" => {
610
            if let Some(card) = f.card {
611
                pdb::shift_card(&app.db, project.id, card, if f.action == "up" { -1 } else { 1 }).await.map_err(e)?;
612
            }
613
        }
614
        "remove" => {
615
            if let Some(card) = f.card {
616
                pdb::remove_card(&app.db, project.id, card).await.map_err(e)?;
617
            }
618
        }
619
        "add_column" => {
620
            let name = f.name.trim();
621
            if name.is_empty() || name.len() > 40 {
622
                error = Some("A column has a name of up to 40 characters.".into());
623
            } else {
624
                pdb::add_column(&app.db, project.id, name).await.map_err(e)?;
625
            }
626
        }
627
        "rename_column" => {
628
            if let (Some(col), name) = (f.column, f.name.trim()) {
629
                if !name.is_empty() && name.len() <= 40 {
630
                    pdb::rename_column(&app.db, project.id, col, name).await.map_err(e)?;
631
                }
632
            }
633
        }
634
        "left" | "right" => {
635
            if let Some(col) = f.column {
636
                pdb::shift_column(&app.db, project.id, col, if f.action == "left" { -1 } else { 1 }).await.map_err(e)?;
637
            }
638
        }
639
        "remove_column" => {
640
            if let Some(col) = f.column {
641
                if !pdb::remove_column(&app.db, project.id, col).await.map_err(e)? {
642
                    error = Some("A project keeps at least one column.".into());
643
                }
644
            }
645
        }
646
        "settings" => {
647
            let title = if f.title.trim().is_empty() { project.title.clone() } else { f.title.trim().chars().take(100).collect() };
648
            pdb::set(&app.db, project.id, &title, f.description.trim(), f.private.is_none(), f.closed.is_some()).await.map_err(e)?;
649
            notice = Some("Saved.".into());
b1e92a62 Andy McCall ↶ 650
        }
651
        "transfer" => {
652
            let to = f.to.trim();
653
            match rights_of(&app, viewer.account(), to).await.map_err(e)? {
654
                _ if to == owner => error = Some(format!("It is {owner}'s already.")),
655
                Some(t) if t.edit => {
656
                    let moved = pdb::transfer(&app.db, project.id, to).await.map_err(e)?;
657
                    let detail = format!("{owner}/{number} to {to}/{}", moved.number);
658
                    db::accounts::audit(&app.db, viewer.account(), "project.transferred", &detail, &project.title).await.ok();
659
                    return Ok(Redirect::to(&format!("/projects/{to}/{}", moved.number)).into_response());
660
                }
661
                _ => error = Some(format!("You cannot make projects under {to}, so you cannot move this one there.")),
662
            }
e1ec9fbf Andy McCall ↶ 663
        }
664
        "delete" => {
665
            pdb::delete(&app.db, project.id).await.map_err(e)?;
666
            db::accounts::audit(&app.db, viewer.account(), "project.deleted", &format!("{owner}/{number}"), &project.title).await.ok();
667
            return Ok(Redirect::to(&format!("/projects/{owner}")).into_response());
668
        }
669
        _ => return Err(Error::bad(shell, "unknown action")),
670
    }
671
    if notice.is_none() && error.is_none() {
672
        // Back to the board, so a reload does not repeat the action.
673
        return Ok(Redirect::to(&format!("/projects/{owner}/{number}")).into_response());
674
    }
657e7d5c Andy McCall ↶ 675
    Ok(board(&app, shell, &viewer, &owner, number, notice, error, &BoardQuery::default()).await?.into_response())
e1ec9fbf Andy McCall ↶ 676
}
677
678
/// The projects an issue or proposal is on that the viewer may see, with
679
/// their column.
680
pub async fn placements_for(app: &Shared, viewer: &Viewer, repo: &db::repos::RepoRow, number: i64) -> Vec<(pdb::Project, String)> {
681
    let Ok(all) = pdb::placements(&app.db, repo.id, number).await else { return vec![] };
682
    let mut out = Vec::new();
683
    for (p, col) in all {
684
        let visible = p.public
685
            || viewer.is_admin()
686
            || match viewer.account() {
687
                Some(v) if v.username == p.owner => true,
688
                Some(v) => match db::accounts::org_by_name(&app.db, &p.owner).await.ok().flatten() {
689
                    Some(o) => db::accounts::org_role(&app.db, o.id, v.id).await.ok().flatten().is_some(),
690
                    None => false,
691
                },
692
                None => false,
693
            };
694
        if visible {
695
            out.push((p, col));
696
        }
697
    }
698
    out
699
}
700
701
#[cfg(test)]
702
mod tests {
703
    use super::parse_reference;
704
705
    #[test]
706
    fn references() {
707
        assert_eq!(parse_reference("oxygen#12", ""), Some(("oxygen".into(), 12)));
708
        assert_eq!(parse_reference("#7", "hub"), Some(("hub".into(), 7)));
709
        assert_eq!(parse_reference(" hub # 3 ", ""), Some(("hub".into(), 3)));
710
        assert_eq!(parse_reference("#7", ""), None, "a repository is needed");
711
        assert_eq!(parse_reference("other/repo#1", ""), None, "only the owner's repositories");
712
        assert_eq!(parse_reference("hub#0", ""), None);
713
        assert_eq!(parse_reference("hub", ""), None);
714
    }
715
}
a1b98695 Andy McCall ↶ 716
717
#[derive(Deserialize)]
718
pub struct PlaceForm {
719
    #[serde(rename = "_csrf")]
720
    csrf_token: String,
721
    /// The project's number among its owner's.
722
    project: i64,
723
    /// `add` or `remove`.
724
    action: String,
725
}
726
727
/// Put an issue or proposal on one of its repository owner's projects (in
728
/// the first column), or take it off, from its own page.
729
async fn place(
730
    app: Shared,
731
    viewer: Viewer,
732
    owner: String,
733
    name: String,
734
    kind: &'static str,
735
    number: i64,
736
    f: PlaceForm,
737
) -> Result<Response, Error> {
738
    let page = format!("/{owner}/{name}/{kind}/{number}");
739
    let shell = Shell::new(&app, &page, &viewer);
740
    csrf(&viewer, &f.csrf_token, &shell)?;
741
    let (_, row, _) = super::lookup(&app, &shell, &viewer, &owner, &name).await?;
742
    let r = rights(&app, &shell, &viewer, &row.owner).await?;
743
    if !r.edit {
744
        return Err(Error::not_found(shell));
745
    }
746
    let e = |e| Error::from_db(shell.clone(), e);
747
    let project = pdb::get(&app.db, &row.owner, f.project).await.map_err(e)?.ok_or_else(|| Error::not_found(shell.clone()))?;
748
    let actor = viewer.account().map(|a| a.username.clone()).unwrap_or_default();
749
    let mut error = None;
750
    match f.action.as_str() {
751
        "add" => {
752
            let columns = pdb::columns(&app.db, project.id).await.map_err(e)?;
753
            let Some(first) = columns.first() else { return Err(Error::bad(shell, "that project has no columns")) };
754
            if let Err(msg) =
755
                add_card(&app, viewer.account(), &row.owner, project.id, first.id, &format!("{}#{number}", row.name), &row.name, "", &actor)
756
                    .await
757
                    .map_err(e)?
758
            {
759
                error = Some(msg);
760
            }
761
        }
762
        "remove" => {
763
            for c in pdb::cards(&app.db, project.id).await.map_err(e)? {
764
                if c.repo_id == Some(row.id) && c.number == Some(number) {
765
                    pdb::remove_card(&app.db, project.id, c.id).await.map_err(e)?;
766
                }
767
            }
768
        }
769
        _ => return Err(Error::bad(shell, "add or remove")),
770
    }
771
    let to = match error {
772
        Some(m) => format!("{page}?error={}", super::settings::urlencode(&m)),
773
        None => page,
774
    };
775
    Ok(Redirect::to(&to).into_response())
776
}
777
778
/// `POST /{owner}/{name}/proposal/{number}/project`.
779
pub async fn place_proposal(
780
    State(app): State<Shared>,
781
    viewer: Viewer,
782
    Path((owner, name, number)): Path<(String, String, i64)>,
783
    Form(f): Form<PlaceForm>,
784
) -> Result<Response, Error> {
785
    place(app, viewer, owner, name, "proposal", number, f).await
786
}
787
788
/// `POST /{owner}/{name}/issue/{number}/project`.
789
pub async fn place_issue(
790
    State(app): State<Shared>,
791
    viewer: Viewer,
792
    Path((owner, name, number)): Path<(String, String, i64)>,
793
    Form(f): Form<PlaceForm>,
794
) -> Result<Response, Error> {
795
    place(app, viewer, owner, name, "issue", number, f).await
796
}
797
798
/// The owner's open projects `viewer` may add an item to that it is not on
799
/// yet; `None` when the viewer may not change the owner's projects at all.
800
pub async fn project_choices(
801
    app: &Shared,
802
    viewer: &Viewer,
803
    repo: &db::repos::RepoRow,
804
    placed: &[(pdb::Project, String)],
805
) -> Option<Vec<pdb::Project>> {
806
    let Ok(Some(r)) = rights_of(app, viewer.account(), &repo.owner).await else { return None };
807
    if !r.edit {
808
        return None;
809
    }
810
    Some(
811
        pdb::of_owner(&app.db, &repo.owner)
812
            .await
813
            .unwrap_or_default()
814
            .into_iter()
815
            .filter(|p| !p.closed && !placed.iter().any(|(q, _)| q.id == p.id))
816
            .collect(),
817
    )
818
}