use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::error::AppError; use crate::models::common::{Role, Visibility}; use crate::models::workspaces::Workspace; use crate::service::WorkspaceService; use crate::session::Session; use super::util::{clamp_limit_offset, ensure_affected, merge_optional_text, parse_enum}; #[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)] pub struct CreateWorkspaceParams { pub name: String, pub description: Option, pub visibility: Option, } #[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)] pub struct UpdateWorkspaceParams { pub name: Option, pub description: Option, pub visibility: Option, pub default_role: Option, } impl WorkspaceService { pub async fn workspace_list( &self, ctx: &Session, limit: i64, offset: i64, ) -> Result, AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let (limit, offset) = clamp_limit_offset(limit, offset); sqlx::query_as::<_, Workspace>( "SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at \ FROM workspace WHERE deleted_at IS NULL AND (owner_id = $1 OR id IN \ (SELECT workspace_id FROM workspace_member WHERE user_id = $1 AND status = 'active') \ OR visibility = 'public') \ ORDER BY created_at DESC LIMIT $2 OFFSET $3", ) .bind(user_uid) .bind(limit) .bind(offset) .fetch_all(self.ctx.db.reader()) .await .map_err(AppError::Database) } pub async fn workspace_get( &self, ctx: &Session, workspace_id: Uuid, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_readable(user_uid, &ws).await?; Ok(ws) } pub async fn workspace_create( &self, ctx: &Session, params: CreateWorkspaceParams, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let name = params.name.trim().to_string(); if name.is_empty() { return Err(AppError::BadRequest("name is required".into())); } let visibility = match params.visibility { Some(ref v) => parse_enum( Some(v.clone()), Visibility::Internal, Visibility::Unknown, "visibility", )?, None => Visibility::Internal, }; let now = chrono::Utc::now(); let workspace_id = Uuid::now_v7(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let ws = sqlx::query_as::<_, Workspace>( "INSERT INTO workspace (id, owner_id, name, description, visibility, plan, status, \ default_role, is_personal, created_at, updated_at) \ VALUES ($1, $2, $3, $4, $5, 'free', 'active', 'member', false, $6, $6) \ RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at", ) .bind(workspace_id) .bind(user_uid) .bind(&name) .bind(params.description.as_deref()) .bind(visibility) .bind(now) .fetch_one(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "INSERT INTO workspace_member (id, workspace_id, user_id, role, status, joined_at, created_at, updated_at) \ VALUES ($1, $2, $3, 'owner', 'active', $4, $4, $4)", ) .bind(Uuid::now_v7()) .bind(workspace_id) .bind(user_uid) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "INSERT INTO workspace_settings (workspace_id, allow_public_repos, allow_member_invites, \ require_two_factor, default_repo_visibility, default_branch_name, \ issue_tracking_enabled, pull_requests_enabled, wiki_enabled, created_at, updated_at) \ VALUES ($1, true, true, false, 'private', 'main', true, true, true, $2, $2)", ) .bind(workspace_id) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "INSERT INTO workspace_stats (workspace_id, members_count, repos_count, issues_count, \ pull_requests_count, storage_bytes, bandwidth_bytes, build_minutes_used, updated_at) \ VALUES ($1, 1, 0, 0, 0, 0, 0, 0, $2)", ) .bind(workspace_id) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "INSERT INTO workspace_billing (workspace_id, plan, status, seats, created_at, updated_at) \ VALUES ($1, 'free', 'active', 1, $2, $2)", ) .bind(workspace_id) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "INSERT INTO workspace_custom_branding (workspace_id, enabled, created_at, updated_at) \ VALUES ($1, false, $2, $2)", ) .bind(workspace_id) .bind(now) .execute(&mut *txn) .await .map_err(AppError::Database)?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(ws) } pub async fn workspace_update( &self, ctx: &Session, workspace_id: Uuid, params: UpdateWorkspaceParams, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin) .await?; let name = merge_optional_text(params.name, Some(ws.name.clone())).unwrap_or(ws.name.clone()); let description = merge_optional_text(params.description, ws.description); let visibility = parse_enum( params.visibility, ws.visibility, Visibility::Unknown, "visibility", )?; let default_role = match params.default_role { Some(ref v) => parse_enum( Some(v.clone()), ws.default_role.parse().unwrap_or(Role::Member), Role::Unknown, "default_role", )?, None => ws.default_role.parse().unwrap_or(Role::Member), }; // Restrict default_role to safe roles only match default_role { Role::Member | Role::Contributor | Role::Viewer | Role::Guest => {} _ => { return Err(AppError::BadRequest( "default_role must be one of: member, contributor, viewer, guest".into(), )); } } let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query_as::<_, Workspace>( "UPDATE workspace SET name = $1, description = $2, visibility = $3, default_role = $4, \ updated_at = $5 WHERE id = $6 AND deleted_at IS NULL \ RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at", ) .bind(&name) .bind(&description) .bind(visibility) .bind(default_role.to_string()) .bind(now) .bind(workspace_id) .fetch_optional(&mut *txn) .await .map_err(AppError::Database)? .ok_or(AppError::NotFound("workspace not found".into()))?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(result) } pub async fn workspace_archive( &self, ctx: &Session, workspace_id: Uuid, ) -> Result<(), AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner) .await?; let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query( "UPDATE workspace SET status = 'archived', archived_at = $1, updated_at = $1 \ WHERE id = $2 AND deleted_at IS NULL AND status <> 'archived'", ) .bind(now) .bind(workspace_id) .execute(&mut *txn) .await .map_err(AppError::Database)?; ensure_affected( result.rows_affected(), "workspace not found or already archived", )?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(()) } pub async fn workspace_unarchive( &self, ctx: &Session, workspace_id: Uuid, ) -> Result<(), AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner) .await?; let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query( "UPDATE workspace SET status = 'active', archived_at = NULL, updated_at = $1 \ WHERE id = $2 AND deleted_at IS NULL AND status = 'archived'", ) .bind(now) .bind(workspace_id) .execute(&mut *txn) .await .map_err(AppError::Database)?; ensure_affected( result.rows_affected(), "workspace not found or not archived", )?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(()) } pub async fn workspace_delete( &self, ctx: &Session, workspace_id: Uuid, ) -> Result<(), AppError> { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner) .await?; let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query( "UPDATE workspace SET deleted_at = $1, status = 'deleted', updated_at = $1 \ WHERE id = $2 AND deleted_at IS NULL", ) .bind(now) .bind(workspace_id) .execute(&mut *txn) .await .map_err(AppError::Database)?; ensure_affected(result.rows_affected(), "workspace not found")?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(()) } pub async fn workspace_transfer_owner( &self, ctx: &Session, workspace_id: Uuid, new_owner_id: Uuid, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Owner) .await?; if new_owner_id == ws.owner_id { return Err(AppError::BadRequest( "new owner must be different from current owner".into(), )); } let is_member = sqlx::query_scalar::<_, bool>( "SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')", ) .bind(workspace_id) .bind(new_owner_id) .fetch_one(self.ctx.db.reader()) .await .map_err(AppError::Database)?; if !is_member { return Err(AppError::BadRequest( "new owner must be an active member".into(), )); } let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "UPDATE workspace_member SET role = 'owner', updated_at = $1 \ WHERE workspace_id = $2 AND user_id = $3", ) .bind(now) .bind(workspace_id) .bind(new_owner_id) .execute(&mut *txn) .await .map_err(AppError::Database)?; sqlx::query( "UPDATE workspace_member SET role = 'admin', updated_at = $1 \ WHERE workspace_id = $2 AND user_id = $3", ) .bind(now) .bind(workspace_id) .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query_as::<_, Workspace>( "UPDATE workspace SET owner_id = $1, updated_at = $2 WHERE id = $3 AND deleted_at IS NULL \ RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at", ) .bind(new_owner_id) .bind(now) .bind(workspace_id) .fetch_one(&mut *txn) .await .map_err(AppError::Database)?; txn.commit().await.map_err(|_| AppError::TxnError)?; Ok(result) } pub async fn workspace_upload_avatar( &self, ctx: &Session, workspace_id: Uuid, data: Vec, content_type: Option, file_name: Option, ) -> Result { let user_uid = ctx.user().ok_or(AppError::Unauthorized)?; let ws = self.find_workspace_by_id(workspace_id).await?; self.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin) .await?; let ext = crate::service::util::avatar_extension(content_type.as_deref(), file_name.as_deref())?; crate::service::util::validate_avatar_size(data.len(), 5 * 1024 * 1024)?; let old_avatar_url = ws.avatar_url.clone(); let storage_key = format!( "workspaces/{}/avatar/{}.{}", workspace_id, Uuid::now_v7(), ext ); self.ctx.storage.put(&storage_key, data).await?; let avatar_url = self.ctx.storage.public_url(&storage_key).ok_or_else(|| { AppError::Config("APP_S3_PUBLIC_URL is required for avatar upload".into()) })?; let now = chrono::Utc::now(); let mut txn = self .ctx .db .writer() .begin() .await .map_err(|_| AppError::TxnError)?; sqlx::query("SET LOCAL app.current_user_id = $1") .bind(user_uid) .execute(&mut *txn) .await .map_err(AppError::Database)?; let result = sqlx::query_as::<_, Workspace>( "UPDATE workspace SET avatar_url = $1, updated_at = $2 \ WHERE id = $3 AND deleted_at IS NULL \ RETURNING id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at", ) .bind(&avatar_url) .bind(now) .bind(workspace_id) .fetch_optional(&mut *txn) .await .map_err(AppError::Database)?; if let Some(updated) = result { txn.commit().await.map_err(|_| AppError::TxnError)?; if let Some(old_url) = old_avatar_url && let Some(old_key) = extract_storage_key_from_url(&old_url) { let _ = self.ctx.storage.delete(&old_key).await; } Ok(updated) } else { let _ = self.ctx.storage.delete(&storage_key).await; Err(AppError::NotFound("workspace not found".into())) } } pub(crate) async fn find_workspace_by_id( &self, workspace_id: Uuid, ) -> Result { sqlx::query_as::<_, Workspace>( "SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at \ FROM workspace WHERE id = $1 AND deleted_at IS NULL", ) .bind(workspace_id) .fetch_optional(self.ctx.db.reader()) .await .map_err(AppError::Database)? .ok_or(AppError::NotFound("workspace not found".into())) } pub(crate) async fn find_workspace_by_name(&self, name: &str) -> Result { sqlx::query_as::<_, Workspace>( "SELECT id, owner_id, name, description, avatar_url, visibility, plan, status, \ default_role, is_personal, archived_at, created_at, updated_at, deleted_at \ FROM workspace WHERE lower(name) = lower($1) AND deleted_at IS NULL", ) .bind(name) .fetch_optional(self.ctx.db.reader()) .await .map_err(AppError::Database)? .ok_or(AppError::NotFound("workspace not found".into())) } pub async fn workspace_user_role( &self, user_uid: Uuid, workspace_id: Uuid, ) -> Result, AppError> { let role_str: Option = sqlx::query_scalar( "SELECT role FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active'", ) .bind(workspace_id) .bind(user_uid) .fetch_optional(self.ctx.db.reader()) .await .map_err(AppError::Database)?; match role_str { Some(r) => Ok(Some(r.parse().unwrap_or(Role::Unknown))), None => { let ws = self.find_workspace_by_id(workspace_id).await?; if ws.owner_id == user_uid { return Ok(Some(Role::Owner)); } Ok(None) } } } pub async fn ensure_workspace_readable( &self, user_uid: Uuid, ws: &Workspace, ) -> Result<(), AppError> { if ws.owner_id == user_uid { return Ok(()); } let is_member = sqlx::query_scalar::<_, bool>( "SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')", ) .bind(ws.id) .bind(user_uid) .fetch_one(self.ctx.db.reader()) .await .map_err(AppError::Database)?; if is_member { return Ok(()); } match ws.visibility { Visibility::Public | Visibility::Internal => Ok(()), _ => Err(AppError::Unauthorized), } } pub async fn ensure_workspace_role_at_least( &self, user_uid: Uuid, ws: &Workspace, min_role: Role, ) -> Result { if ws.owner_id == user_uid { return Ok(Role::Owner); } let role_str: Option = sqlx::query_scalar( "SELECT role FROM workspace_member WHERE workspace_id = $1 AND user_id = $2 AND status = 'active'", ) .bind(ws.id) .bind(user_uid) .fetch_optional(self.ctx.db.reader()) .await .map_err(AppError::Database)?; let role = role_str .and_then(|r| r.parse::().ok()) .unwrap_or(Role::Unknown); if super::util::role_level(role) < super::util::role_level(min_role) { return Err(AppError::Unauthorized); } Ok(role) } } use crate::service::util::extract_storage_key_from_url;