Files
gitks/service/workspace/integrations.rs
T
zhenyi dca717be10 refactor(workspace): pass workspace object instead of id to service methods
- Replace workspace_id parameter with Workspace object reference in all workspace service methods
- Remove redundant find_workspace_by_id calls that were duplicated in each method
- Update all method signatures across approval, audit, billing, branding, core, settings and stats modules
- Modify SQL queries to bind ws.id instead of separate workspace_id parameter
- Add Workspace import to all affected modules
- Adjust method calls in API handlers to pass workspace object instead of id
- Consolidate workspace retrieval logic to single location per operation flow
2026-06-07 18:44:01 +08:00

217 lines
7.4 KiB
Rust

use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::error::AppError;
use crate::models::common::Provider;
use crate::models::workspaces::{Workspace, WorkspaceIntegration};
use crate::service::WorkspaceService;
use crate::session::Session;
use super::util::{clamp_limit_offset, ensure_affected, required_text};
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct CreateIntegrationParams {
pub provider: String,
pub name: String,
pub config: Option<crate::models::json_types::WorkspaceIntegrationConfig>,
pub secret_ciphertext: Option<String>,
pub enabled: Option<bool>,
}
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
pub struct UpdateIntegrationParams {
pub name: Option<String>,
pub config: Option<crate::models::json_types::WorkspaceIntegrationConfig>,
pub secret_ciphertext: Option<String>,
pub enabled: Option<bool>,
}
impl WorkspaceService {
pub async fn workspace_integrations(
&self,
ctx: &Session,
ws: &Workspace,
limit: i64,
offset: i64,
) -> Result<Vec<WorkspaceIntegration>, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
let (limit, offset) = clamp_limit_offset(limit, offset);
sqlx::query_as::<_, WorkspaceIntegration>(
"SELECT id, workspace_id, provider, name, config, secret_ciphertext, enabled, \
installed_by, last_used_at, created_at, updated_at FROM workspace_integration \
WHERE workspace_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
)
.bind(ws.id)
.bind(limit)
.bind(offset)
.fetch_all(self.ctx.db.reader())
.await
.map_err(AppError::Database)
}
pub async fn workspace_create_integration(
&self,
ctx: &Session,
ws: &Workspace,
params: CreateIntegrationParams,
) -> Result<WorkspaceIntegration, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
let provider = params
.provider
.trim()
.parse::<Provider>()
.map_err(|_| AppError::BadRequest("invalid provider".into()))?;
if provider == Provider::Unknown {
return Err(AppError::BadRequest("invalid provider".into()));
}
let name = required_text(params.name, "name")?;
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::<_, WorkspaceIntegration>(
"INSERT INTO workspace_integration (id, workspace_id, provider, name, config, secret_ciphertext, \
enabled, installed_by, created_at, updated_at) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $9) \
RETURNING id, workspace_id, provider, name, config, secret_ciphertext, enabled, \
installed_by, last_used_at, created_at, updated_at",
)
.bind(Uuid::now_v7())
.bind(ws.id)
.bind(provider)
.bind(&name)
.bind(params.config.map(sqlx::types::Json))
.bind(&params.secret_ciphertext)
.bind(params.enabled.unwrap_or(true))
.bind(user_uid)
.bind(now)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(result)
}
pub async fn workspace_update_integration(
&self,
ctx: &Session,
ws: &Workspace,
integration_id: Uuid,
params: UpdateIntegrationParams,
) -> Result<WorkspaceIntegration, AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
let current = sqlx::query_as::<_, WorkspaceIntegration>(
"SELECT id, workspace_id, provider, name, config, secret_ciphertext, enabled, \
installed_by, last_used_at, created_at, updated_at FROM workspace_integration \
WHERE id = $1 AND workspace_id = $2",
)
.bind(integration_id)
.bind(ws.id)
.fetch_optional(self.ctx.db.reader())
.await
.map_err(AppError::Database)?
.ok_or(AppError::NotFound("integration not found".into()))?;
let name = params
.name
.map(|n| n.trim().to_string())
.unwrap_or(current.name);
let enabled = params.enabled.unwrap_or(current.enabled);
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::<_, WorkspaceIntegration>(
"UPDATE workspace_integration SET name = $1, config = $2, secret_ciphertext = $3, \
enabled = $4, updated_at = $5 WHERE id = $6 AND workspace_id = $7 \
RETURNING id, workspace_id, provider, name, config, secret_ciphertext, enabled, \
installed_by, last_used_at, created_at, updated_at",
)
.bind(&name)
.bind(
params
.config
.map(sqlx::types::Json)
.or_else(|| current.config.clone()),
)
.bind(params.secret_ciphertext.or(current.secret_ciphertext))
.bind(enabled)
.bind(now)
.bind(integration_id)
.bind(ws.id)
.fetch_one(&mut *txn)
.await
.map_err(AppError::Database)?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(result)
}
pub async fn workspace_delete_integration(
&self,
ctx: &Session,
ws: &Workspace,
integration_id: Uuid,
) -> Result<(), AppError> {
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
self.ensure_workspace_role_at_least(user_uid, &ws, crate::models::common::Role::Admin)
.await?;
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_integration WHERE id = $1 AND workspace_id = $2")
.bind(integration_id)
.bind(ws.id)
.execute(&mut *txn)
.await
.map_err(AppError::Database)?;
ensure_affected(result.rows_affected(), "integration not found")?;
txn.commit().await.map_err(|_| AppError::TxnError)?;
Ok(())
}
}