ryuk-cli 0.1.1

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
//! The tenant-owned example: projects belong to an organization. Copy this shape for your own tables:
//! take `Member`, `require` a role, and put `org_id = m.org_id` in EVERY query (including the by-id ones, so
//! a project id from another org is simply "not found"). Never read the org id from the request body.
use super::AppError;
use crate::{AppState, models::project};
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use ryuk::{
    inertia::{self},
    session::Session,
    tenancy::{Member, Role},
    validation::Form,
};
use sea_orm::{ActiveModelTrait, ActiveValue::Set, ColumnTrait, EntityTrait, QueryFilter};
use serde::Deserialize;
use utoipa::ToSchema;
use validator::Validate;

#[derive(Deserialize, Validate, ToSchema)]
pub struct ProjectForm {
    #[validate(length(min = 1, max = 120, message = "Name must be 1 to 120 characters"))]
    name: String,
}

#[utoipa::path(post, path = "/orgs/{org}/projects", params(("org" = i64, Path, description = "Organization id")), request_body = ProjectForm,
    responses((status = 303, description = "Back to the organization"), (status = 404, description = "Not a member")))]
pub async fn store(State(s): State<AppState>, m: Member, session: Session, Form(f): Form<ProjectForm>) -> Result<Response, AppError> {
    project::ActiveModel {
        org_id: Set(m.org_id),
        name: Set(f.name.trim().to_string()),
        created_by: Set(Some(m.user_id)),
        created_at: Set(chrono::Utc::now().timestamp()),
        ..Default::default()
    }
    .insert(&s.db)
    .await?;
    inertia::flash(&session, "success", "Project created.").await;
    Ok(inertia::redirect(&format!("/orgs/{}", m.org_id)))
}

#[utoipa::path(delete, path = "/orgs/{org}/projects/{id}", params(("org" = i64, Path, description = "Organization id"), ("id" = i64, Path, description = "Project id")),
    responses((status = 303, description = "Back to the organization (with an error flash when you may not delete it: only its creator or an admin may)"), (status = 404, description = "Not in this organization")))]
pub async fn destroy(State(s): State<AppState>, m: Member, Path(ids): Path<(i64, i64)>, session: Session) -> Result<Response, AppError> {
    let id = ids.1;
    // Both filters, always: the id alone would let a member of org A delete org B's project.
    let Some(p) = project::Entity::find_by_id(id).filter(project::Column::OrgId.eq(m.org_id)).one(&s.db).await? else {
        return Ok(StatusCode::NOT_FOUND.into_response());
    };
    if m.role < Role::Admin && p.created_by != Some(m.user_id) {
        return Ok(super::orgs::denied(&session, &format!("/orgs/{}", m.org_id)).await);
    }
    project::Entity::delete_many()
        .filter(project::Column::Id.eq(id))
        .filter(project::Column::OrgId.eq(m.org_id))
        .exec(&s.db)
        .await?;
    inertia::flash(&session, "success", "Project deleted.").await;
    Ok(inertia::redirect(&format!("/orgs/{}", m.org_id)))
}