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;
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)))
}