Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app/database/migrations/2026_12_06_000000_organization_settings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! The organization's settings page.
//!
//! `setup_shown` replaces `setup_dismissed_at`: whether an admin chose to show (`true`) or hide (`false`) the setup
//! checklist, or nobody has (`NULL`), when it shows until it's complete. A hidden one moves over as `false`.
//!
//! `project_threshold` and `project_comment_when_unchanged` are the settings a new project starts with (the projects
//! table's `threshold` and `comment_when_unchanged`, with the same defaults). Changing them leaves existing projects
//! as they are.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r#"
ALTER TABLE organizations ADD COLUMN setup_shown BOOLEAN;
UPDATE organizations SET setup_shown = false WHERE setup_dismissed_at IS NOT NULL;
ALTER TABLE organizations DROP COLUMN setup_dismissed_at;

ALTER TABLE organizations
ADD COLUMN project_threshold DOUBLE PRECISION NOT NULL DEFAULT 0
CHECK (project_threshold >= 0 AND project_threshold <= 1),
ADD COLUMN project_comment_when_unchanged BOOLEAN NOT NULL DEFAULT false;
"#;
31 changes: 31 additions & 0 deletions app/src/auth/invitations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub fn routes(route: &mut Router) {
route.delete("/api/ui/orgs/{org}/invitations/{id}", withdraw);
route.patch("/api/ui/orgs/{org}/members/{id}", update_member);
route.delete("/api/ui/orgs/{org}/members/{id}", remove_member);
route.post("/api/ui/orgs/{org}/leave", leave);
}

/// Invitation emails an organization may send in a day, and one address may receive from all organizations: inviting,
Expand Down Expand Up @@ -545,6 +546,36 @@ pub async fn remove_member(
Ok(Json(json!({ "members": members_json(org_id, true).await? })))
}

/// `POST /api/ui/orgs/{org}/leave` (any member): leave the organization. Refused for the person's own organization
/// (made at sign-up), for access the forge decides (it would come back at their next sign-in), and for its last admin.
pub async fn leave(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
) -> laravel::Result<Json<Value>> {
let (org_id, _, _) = org_role(&user, &org).await?;
let user_id = user.id;
let row = db::query!(
"SELECT m.source, u.personal_organization_id = {org_id} AS personal FROM memberships m \
JOIN users u ON u.id = m.user_id WHERE m.organization_id = {org_id} AND m.user_id = {user_id}"
)
.select_one()
.await?
.ok_or_else(|| laravel::abort(404))?;
if row.try_get::<Option<bool>>("personal")?.unwrap_or(false) {
return Err(laravel::abort_with(422, "this is your own organization: you can't leave it"));
}
if let Some(forge) = ForgeKind::parse(&row.try_get::<String>("source")?) {
return Err(laravel::abort_with(
422,
format!("your access comes from {}: it follows your permission on the repository there", forge.label()),
));
}
if !change_member(org_id, user_id, None).await? {
return Err(laravel::abort_with(422, "the organization needs another admin first"));
}
Ok(Json(json!({ "ok": true })))
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
92 changes: 91 additions & 1 deletion app/src/auth/orgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::models::{Build, Organization, User};
pub fn routes(route: &mut Router) {
route.post("/api/ui/orgs", create);
route.get("/api/ui/orgs/{org}", show);
route.patch("/api/ui/orgs/{org}", update);
route.get("/api/ui/org-exists/{slug}", exists);
}

Expand Down Expand Up @@ -158,7 +159,8 @@ async fn usage_by_project(org_id: i64) -> laravel::Result<Vec<Value>> {

/// `GET /api/ui/orgs/{org}`: the organization's page for a member: its projects with their newest build, the last 50
/// charges, this month's usage (in all and by project), its members, and for admins its billing email and pending
/// invitations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden.
/// invitations; for its settings page, whether it's the person's own (made at sign-up) and where their access comes from, the settings new projects
/// start with and its GitHub App installations. Self-managed GitLab is off until sc-8634, so its section is empty and hidden.
pub async fn show(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
Expand Down Expand Up @@ -195,6 +197,14 @@ pub async fn show(
})
.collect::<laravel::Result<_>>()?;
let invitations = if admin { super::invitations::pending(org_id).await? } else { Vec::new() };
let user_id = user.id;
let mine = db::query!(
"SELECT u.personal_organization_id IS NOT DISTINCT FROM {org_id} AS personal, m.source FROM users u \
JOIN memberships m ON m.user_id = u.id AND m.organization_id = {org_id} WHERE u.id = {user_id}"
)
.select_one()
.await?
.ok_or_else(|| laravel::abort(404))?;
Ok(Json(json!({
"slug": org.slug, "name": org.name, "role": role.as_str(),
"usage": crate::domain::credits::usage(&org).await?,
Expand All @@ -203,6 +213,86 @@ pub async fn show(
"projects": list, "history": history, "usage_by_project": usage_by_project(org_id).await?,
"members": super::invitations::members_json(org_id, admin).await?, "invitations": invitations,
"setup": super::setup::state(org_id, Some(user.pid)).await?,
"personal": mine.try_get::<bool>("personal")?,
"source": mine.try_get::<String>("source")?,
"project_defaults": {
"threshold": org.project_threshold, "comment_when_unchanged": org.project_comment_when_unchanged,
},
"github_installations": installations(org_id).await?,
"gitlab_instances": [], "gitlab_instances_enabled": false,
})))
}

/// The GitHub App's installations set up for an organization, for its settings page: the account, whether it's a
/// person's or a GitHub organization's, and how many repositories its projects link through it.
async fn installations(org_id: i64) -> laravel::Result<Vec<Value>> {
let rows = db::query!(
"SELECT g.installation_id, g.account_login, g.account_type, g.suspended_at IS NOT NULL AS suspended, \
(SELECT count(DISTINCT p.repository_id) FROM projects p \
WHERE p.organization_id = {org_id} AND p.forge_installation = g.installation_id)::bigint AS repositories \
FROM github_installations g WHERE g.organization_id = {org_id} AND g.deleted_at IS NULL \
ORDER BY lower(g.account_login)"
)
.select()
.await?;
rows.iter()
.map(|r| {
Ok(json!({
"installation_id": r.try_get::<String>("installation_id")?,
"account_login": r.try_get::<String>("account_login")?,
"account_type": r.try_get::<String>("account_type")?,
"suspended": r.try_get::<bool>("suspended")?,
"repositories": r.try_get::<i64>("repositories")?,
}))
})
.collect()
}

#[laravel::input]
#[validate(authenticated)]
pub struct UpdateInput {
/// The organization's display name.
name: Option<String>,
/// The diff threshold a new project starts with, 0 to 1.
project_threshold: Option<f64>,
/// Whether a new project comments on pull requests whose builds are unchanged.
project_comment_when_unchanged: Option<bool>,
}

/// `PATCH /api/ui/orgs/{org}` (admins): its name and the settings new projects start with; fields left out stay as
/// they are. Existing projects keep their own settings.
pub async fn update(
Authenticated(user): Authenticated<User>,
Params(slug): Params<String>,
Valid(p): Valid<UpdateInput>,
) -> laravel::Result<Json<Value>> {
let (org_id, _, role) = super::invitations::org_role(&user, &slug).await?;
if role < Role::Admin {
return Err(laravel::abort_with(403, "only admins can change the organization's settings"));
}
let name = p.name.as_deref().map(str::trim).map(str::to_string);
if let Some(name) = &name
&& (name.is_empty() || name.chars().count() > MAX_NAME)
{
return Err(laravel::abort_with(422, format!("an organization's name is 1 to {MAX_NAME} characters")));
}
if p.project_threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) {
return Err(laravel::abort_with(422, "threshold must be between 0 and 1"));
}
let (threshold, comment) = (p.project_threshold, p.project_comment_when_unchanged);
db::query!(
"UPDATE organizations SET name = COALESCE({name}, name), \
project_threshold = COALESCE({threshold}, project_threshold), \
project_comment_when_unchanged = COALESCE({comment}, project_comment_when_unchanged), \
updated_at = now() WHERE id = {org_id}"
)
.update()
.await?;
let org = Organization::find_or_fail(org_id).await?;
Ok(Json(json!({
"slug": org.slug, "name": org.name,
"project_defaults": {
"threshold": org.project_threshold, "comment_when_unchanged": org.project_comment_when_unchanged,
},
})))
}
25 changes: 12 additions & 13 deletions app/src/auth/setup.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! The "Set up VisualCI" checklist (sc-8900, ported from today's server): each step ticks itself from what has actually
//! happened, with no "mark done". An organization's admins can close it, or open it again.
//! happened, with no "mark done". It shows until it's complete; an organization's admins can hide it or show it again
//! at any time, complete or not (`organizations.setup_shown`, `NULL` until one of them chooses).

use laravel::auth::Authenticated;
use laravel::db;
Expand All @@ -19,7 +20,8 @@ pub const STEPS: &[&str] = &["install_github_app", "connect_agent", "add_to_ci",

/// The checklist for an organization as `user_pid` sees it (a connected agent is per person: an MCP connection, or a
/// personal token that has been used; with no person, such as a project token, it isn't done): each step and whether
/// it's done, the next one, whether it's complete (a build has been approved) and whether someone closed it. Callers
/// it's done, the next one, whether it's complete (a build has been approved) and whether it shows: an admin's choice,
/// else until it's complete. Callers
/// check first that the person may see the organization: this reads it as asked.
///
/// # Errors
Expand All @@ -40,7 +42,7 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel
WHERE p.organization_id = {org_id} AND b.mode = 'ci') AS add_to_ci, \
EXISTS (SELECT 1 FROM reviews r JOIN builds b ON b.id = r.build_id JOIN projects p ON p.id = b.project_id \
WHERE p.organization_id = {org_id} AND r.action = 'approve') AS review_changes, \
(SELECT setup_dismissed_at IS NOT NULL FROM organizations WHERE id = {org_id}) AS dismissed"
(SELECT setup_shown FROM organizations WHERE id = {org_id}) AS shown"
)
.select_one()
.await?
Expand Down Expand Up @@ -83,7 +85,7 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel
"steps": steps.iter().map(|(key, done)| json!({ "key": key, "done": done })).collect::<Vec<_>>(),
"next": next,
"complete": complete,
"dismissed": row.try_get::<Option<bool>>("dismissed")?.unwrap_or(false),
"shown": row.try_get::<Option<bool>>("shown")?.unwrap_or(!complete),
"install_url": "/github/install",
"installations": offers,
// How the listing after their last GitHub sign-in is going (`sign_in_sync::State`): the offers above wait for it
Expand All @@ -95,10 +97,10 @@ pub async fn state(org_id: i64, user_pid: Option<laravel::str::Uuid>) -> laravel
#[laravel::input]
#[validate(authenticated)]
pub struct SetupInput {
dismissed: bool,
shown: bool,
}

/// `POST /api/ui/orgs/{org}/setup` (admins): close the checklist, or open it again.
/// `POST /api/ui/orgs/{org}/setup` (admins): show the checklist or hide it, complete or not.
pub async fn update(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
Expand All @@ -118,12 +120,9 @@ pub async fn update(
Some(_) => return Err(laravel::abort_with(403, "only admins can change the setup checklist")),
None => return Err(laravel::abort(404)),
}
let dismissed = p.dismissed;
db::query!(
"UPDATE organizations SET setup_dismissed_at = CASE WHEN {dismissed} THEN now() END, updated_at = now() \
WHERE id = {org_id}"
)
.update()
.await?;
let shown = p.shown;
db::query!("UPDATE organizations SET setup_shown = {shown}, updated_at = now() WHERE id = {org_id}")
.update()
.await?;
Ok(Json(state(org_id, Some(user.pid)).await?))
}
18 changes: 13 additions & 5 deletions app/src/domain/projects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,17 @@ pub fn renderer_key(engine: &str, dpi: i32, renderer_version: &str) -> String {
format!("{engine}/{dpi}dpi/{renderer_version}")
}

/// Lowercase letters, digits and dashes, at most 60, and not `billing` (the organization's billing page is
/// `app.visualci.com/<org>/billing`).
/// The organization's own pages under `app.visualci.com/<org>/`, which a project's slug can't take.
pub const RESERVED_SLUGS: &[&str] = &["billing", "repositories", "settings"];

/// Lowercase letters, digits and dashes, at most 60, and not one of the organization's own pages
/// ([`RESERVED_SLUGS`]).
#[must_use]
pub fn valid_slug(s: &str) -> bool {
!s.is_empty()
&& s.len() <= 60
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
&& s != "billing"
&& !RESERVED_SLUGS.contains(&s)
}

/// A project's settings, as the web app shows them and the MCP server returns them.
Expand Down Expand Up @@ -189,7 +192,8 @@ pub enum Refused {
}

/// The message for a slug that isn't valid.
pub const INVALID_SLUG: &str = "project slugs use lowercase letters, digits and dashes, and can't be billing";
pub const INVALID_SLUG: &str =
"project slugs use lowercase letters, digits and dashes, and can't be billing, repositories or settings";

/// Whether a database error is a unique violation (PostgreSQL's 23505): a row another request inserted first.
#[must_use]
Expand All @@ -198,7 +202,7 @@ pub fn is_unique_violation(e: &laravel::Error) -> bool {
text.contains("23505") || text.contains("duplicate key value violates unique constraint")
}

/// Make a project in an organization, with the default settings.
/// Make a project in an organization, with the organization's settings for new projects.
///
/// # Errors
/// `Ok(Err(_))` for a slug that isn't valid or is taken; `Err` on a database error.
Expand All @@ -212,11 +216,15 @@ pub async fn create(organization_id: i64, slug: &str, name: &str) -> laravel::Re
return Ok(Err(Refused::Taken));
}
let name = name.trim();
// It starts with the organization's defaults for new projects
let org = crate::models::Organization::find_or_fail(organization_id).await?;
match laravel::model::create!(Project {
pid: laravel::str::uuid7(),
organization_id: organization_id,
slug: slug,
name: name,
threshold: org.project_threshold,
comment_when_unchanged: org.project_comment_when_unchanged,
})
.await
{
Expand Down
8 changes: 7 additions & 1 deletion app/src/models/organizations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,15 @@ pub struct Organization {
pub reload_started_at: Option<Timestamp>,
pub billing_problem: Option<String>,
pub reloads_paused_at: Option<Timestamp>,
pub setup_dismissed_at: Option<Timestamp>,
pub billing_email: Option<String>,
pub stripe_event_at: Option<Timestamp>,
/// An admin's choice to show or hide the setup checklist; `None` shows it until it's complete.
pub setup_shown: Option<bool>,
/// The diff threshold and the unchanged-PR comment a new project starts with.
#[default]
pub project_threshold: f64,
#[default]
pub project_comment_when_unchanged: bool,
}

/// Paths an organization's slug can't take.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"result": {
"content": [
{
"text": "{\"billing_url\":\"https://app.visualci.test/<org:1>/billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"<uuid:1>@example.com\",\"id\":\"<uuid:2>\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"<time:1>\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"<org:1>/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"<org:1>/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"<org:1>\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"<time:2>\",\"unlimited\":false},\"usage_history\":[]}",
"text": "{\"billing_url\":\"https://app.visualci.test/<org:1>/billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"<uuid:1>@example.com\",\"id\":\"<uuid:2>\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"<time:1>\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"<org:1>/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"<org:1>/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"shown\":true,\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"<org:1>\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"<time:2>\",\"unlimited\":false},\"usage_history\":[]}",
"type": "text"
}
],
Expand Down Expand Up @@ -43,12 +43,12 @@
"role": "admin",
"setup": {
"complete": false,
"dismissed": false,
"github": [],
"github_sync": "done",
"install_url": "/github/install",
"installations": [],
"next": "install_github_app",
"shown": true,
"steps": [
{
"done": false,
Expand Down
Loading
Loading