feat: init
This commit is contained in:
@@ -0,0 +1,350 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, role_level};
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::workspaces::WorkspaceMember;
|
||||
use crate::service::WorkspaceService;
|
||||
use crate::session::Session;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema, utoipa::IntoParams)]
|
||||
pub struct AddMemberParams {
|
||||
pub user_id: Uuid,
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateMemberRoleParams {
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
impl WorkspaceService {
|
||||
pub async fn workspace_members(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
workspace_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<WorkspaceMember>, AppError> {
|
||||
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?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, WorkspaceMember>(
|
||||
"SELECT id, workspace_id, user_id, role, status, invited_by, joined_at, \
|
||||
last_active_at, created_at, updated_at FROM workspace_member \
|
||||
WHERE workspace_id = $1 AND status = 'active' ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn workspace_add_member(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
workspace_id: Uuid,
|
||||
params: AddMemberParams,
|
||||
) -> Result<WorkspaceMember, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let ws = self.find_workspace_by_id(workspace_id).await?;
|
||||
let actor_role = self
|
||||
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
|
||||
.await?;
|
||||
|
||||
let settings_allow = sqlx::query_scalar::<_, bool>(
|
||||
"SELECT allow_member_invites FROM workspace_settings WHERE workspace_id = $1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_one(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if !settings_allow && role_level(actor_role) < role_level(Role::Owner) {
|
||||
return Err(AppError::BadRequest(
|
||||
"member invitations are disabled".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let existing = sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM workspace_member WHERE workspace_id = $1 AND user_id = $2)",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(params.user_id)
|
||||
.fetch_one(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if existing {
|
||||
return Err(AppError::Conflict("user is already a member".into()));
|
||||
}
|
||||
|
||||
let role = params
|
||||
.role
|
||||
.as_deref()
|
||||
.and_then(|r| r.parse::<Role>().ok())
|
||||
.unwrap_or(ws.default_role.parse().unwrap_or(Role::Member));
|
||||
|
||||
if role == Role::Owner {
|
||||
return Err(AppError::BadRequest("cannot add member as owner".into()));
|
||||
}
|
||||
if role == Role::Unknown {
|
||||
return Err(AppError::BadRequest("invalid role".into()));
|
||||
}
|
||||
|
||||
// Non-owner admins cannot grant roles equal to or higher than their own
|
||||
if actor_role != Role::Owner && role_level(role) >= role_level(actor_role) {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot grant role equal to or higher than your own".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 member = sqlx::query_as::<_, WorkspaceMember>(
|
||||
"INSERT INTO workspace_member (id, workspace_id, user_id, role, status, invited_by, joined_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, 'active', $5, $6, $6, $6) \
|
||||
RETURNING id, workspace_id, user_id, role, status, invited_by, joined_at, last_active_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(workspace_id)
|
||||
.bind(params.user_id)
|
||||
.bind(role.to_string())
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE workspace_stats SET members_count = members_count + 1, updated_at = $1 WHERE workspace_id = $2",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(member)
|
||||
}
|
||||
|
||||
pub async fn workspace_update_member_role(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
workspace_id: Uuid,
|
||||
member_id: Uuid,
|
||||
params: UpdateMemberRoleParams,
|
||||
) -> Result<WorkspaceMember, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let ws = self.find_workspace_by_id(workspace_id).await?;
|
||||
let actor_role = self
|
||||
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
|
||||
.await?;
|
||||
|
||||
let new_role = params
|
||||
.role
|
||||
.parse::<Role>()
|
||||
.map_err(|_| AppError::BadRequest("invalid role".into()))?;
|
||||
if new_role == Role::Owner {
|
||||
return Err(AppError::BadRequest(
|
||||
"use workspace_transfer_owner to change owner".into(),
|
||||
));
|
||||
}
|
||||
if new_role == Role::Unknown {
|
||||
return Err(AppError::BadRequest("invalid role".into()));
|
||||
}
|
||||
|
||||
// Non-owner admins cannot grant roles equal to or higher than their own
|
||||
if actor_role != Role::Owner && role_level(new_role) >= role_level(actor_role) {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot grant role equal to or higher than your own".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let target = sqlx::query_as::<_, WorkspaceMember>(
|
||||
"SELECT id, workspace_id, user_id, role, status, invited_by, joined_at, \
|
||||
last_active_at, created_at, updated_at FROM workspace_member \
|
||||
WHERE id = $1 AND workspace_id = $2",
|
||||
)
|
||||
.bind(member_id)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("member not found".into()))?;
|
||||
|
||||
if target.role == Role::Owner {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot change owner role; use workspace_transfer_owner".into(),
|
||||
));
|
||||
}
|
||||
if role_level(actor_role) <= role_level(target.role) && actor_role != Role::Owner {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot change role of a member with equal or higher role".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::<_, WorkspaceMember>(
|
||||
"UPDATE workspace_member SET role = $1, updated_at = $2 WHERE id = $3 AND workspace_id = $4 \
|
||||
RETURNING id, workspace_id, user_id, role, status, invited_by, joined_at, last_active_at, created_at, updated_at",
|
||||
)
|
||||
.bind(new_role.to_string())
|
||||
.bind(now)
|
||||
.bind(member_id)
|
||||
.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_remove_member(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
workspace_id: Uuid,
|
||||
member_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let ws = self.find_workspace_by_id(workspace_id).await?;
|
||||
let actor_role = self
|
||||
.ensure_workspace_role_at_least(user_uid, &ws, Role::Admin)
|
||||
.await?;
|
||||
|
||||
let target = sqlx::query_as::<_, WorkspaceMember>(
|
||||
"SELECT id, workspace_id, user_id, role, status, invited_by, joined_at, \
|
||||
last_active_at, created_at, updated_at FROM workspace_member \
|
||||
WHERE id = $1 AND workspace_id = $2",
|
||||
)
|
||||
.bind(member_id)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("member not found".into()))?;
|
||||
|
||||
if target.role == Role::Owner {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot remove owner; transfer ownership first".into(),
|
||||
));
|
||||
}
|
||||
if role_level(actor_role) <= role_level(target.role) && actor_role != Role::Owner {
|
||||
return Err(AppError::BadRequest(
|
||||
"cannot remove a member with equal or higher role".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("DELETE FROM workspace_member WHERE id = $1 AND workspace_id = $2")
|
||||
.bind(member_id)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "member not found")?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE workspace_stats SET members_count = GREATEST(members_count - 1, 0), updated_at = $1 WHERE workspace_id = $2",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn workspace_leave(&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?;
|
||||
|
||||
if ws.owner_id == user_uid {
|
||||
return Err(AppError::BadRequest(
|
||||
"owner cannot leave; transfer ownership first".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("DELETE FROM workspace_member WHERE workspace_id = $1 AND user_id = $2")
|
||||
.bind(workspace_id)
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not a member")?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE workspace_stats SET members_count = GREATEST(members_count - 1, 0), updated_at = $1 WHERE workspace_id = $2",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user