868 lines
29 KiB
Rust
868 lines
29 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
use uuid::Uuid;
|
|
|
|
use crate::error::AppError;
|
|
use crate::models::common::{EventType, Priority, Role, State, Visibility};
|
|
use crate::models::issues::Issue;
|
|
use crate::models::workspaces::Workspace;
|
|
use crate::service::IssueService;
|
|
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 CreateIssueParams {
|
|
pub title: String,
|
|
pub body: Option<String>,
|
|
pub priority: Option<String>,
|
|
pub visibility: Option<String>,
|
|
pub due_at: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub repo_ids: Vec<Uuid>,
|
|
pub label_ids: Vec<Uuid>,
|
|
pub assignee_ids: Vec<Uuid>,
|
|
pub milestone_id: Option<Uuid>,
|
|
}
|
|
|
|
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
|
pub struct UpdateIssueParams {
|
|
pub title: Option<String>,
|
|
pub body: Option<String>,
|
|
pub priority: Option<String>,
|
|
pub visibility: Option<String>,
|
|
pub due_at: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub milestone_id: Option<Uuid>,
|
|
}
|
|
|
|
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
|
pub struct IssueListFilters {
|
|
pub state: Option<String>,
|
|
pub priority: Option<String>,
|
|
pub author_id: Option<Uuid>,
|
|
pub assignee_id: Option<Uuid>,
|
|
pub milestone_id: Option<Uuid>,
|
|
pub label_id: Option<Uuid>,
|
|
}
|
|
|
|
impl IssueService {
|
|
pub async fn issue_list(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
filters: IssueListFilters,
|
|
limit: i64,
|
|
offset: i64,
|
|
) -> Result<Vec<Issue>, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let ws = self.resolve_workspace(wk_name).await?;
|
|
self.ensure_workspace_readable(wk_name, user_uid).await?;
|
|
let (limit, offset) = clamp_limit_offset(limit, offset);
|
|
|
|
let state = filters
|
|
.state
|
|
.as_deref()
|
|
.and_then(|s| s.parse::<State>().ok())
|
|
.filter(|s| *s != State::Unknown);
|
|
let priority = filters
|
|
.priority
|
|
.as_deref()
|
|
.and_then(|s| s.parse::<Priority>().ok())
|
|
.filter(|p| *p != Priority::Unknown);
|
|
|
|
sqlx::query_as::<_, Issue>(
|
|
"SELECT DISTINCT i.id, i.workspace_id, i.author_id, i.number, i.title, i.body, \
|
|
i.state, i.priority, i.visibility, i.locked, i.milestone_id, i.closed_by, i.closed_at, i.due_at, \
|
|
i.created_at, i.updated_at, i.deleted_at \
|
|
FROM issue i \
|
|
LEFT JOIN issue_assignee ia ON ia.issue_id = i.id \
|
|
LEFT JOIN issue_label_relation ilr ON ilr.issue_id = i.id \
|
|
WHERE i.workspace_id = $1 AND i.deleted_at IS NULL \
|
|
AND ($2::text IS NULL OR i.state::text = $2) \
|
|
AND ($3::text IS NULL OR i.priority::text = $3) \
|
|
AND ($4::uuid IS NULL OR i.author_id = $4) \
|
|
AND ($5::uuid IS NULL OR ia.assignee_id = $5) \
|
|
AND ($6::uuid IS NULL OR i.milestone_id = $6) \
|
|
AND ($7::uuid IS NULL OR ilr.label_id = $7) \
|
|
AND (i.visibility = 'public' OR i.workspace_id IN \
|
|
(SELECT workspace_id FROM workspace_member WHERE user_id = $8 AND status = 'active') \
|
|
OR i.author_id = $8) \
|
|
ORDER BY i.number DESC LIMIT $9 OFFSET $10",
|
|
)
|
|
.bind(ws.id)
|
|
.bind(state.map(|s| s.to_string()))
|
|
.bind(priority.map(|p| p.to_string()))
|
|
.bind(filters.author_id)
|
|
.bind(filters.assignee_id)
|
|
.bind(filters.milestone_id)
|
|
.bind(filters.label_id)
|
|
.bind(user_uid)
|
|
.bind(limit)
|
|
.bind(offset)
|
|
.fetch_all(self.ctx.db.reader())
|
|
.await
|
|
.map_err(AppError::Database)
|
|
}
|
|
|
|
pub async fn issue_get(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
self.ensure_issue_readable(user_uid, &issue).await?;
|
|
Ok(issue)
|
|
}
|
|
|
|
#[tracing::instrument(skip(self, ctx, params), fields(title = %params.title))]
|
|
pub async fn issue_create(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
params: CreateIssueParams,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let title = crate::service::util::required_text(params.title, "title")?;
|
|
let ws = self.resolve_workspace(wk_name).await?;
|
|
self.ensure_workspace_role_at_least(wk_name, user_uid, Role::Member)
|
|
.await?;
|
|
|
|
// Validate repo_ids belong to this workspace
|
|
for repo_id in ¶ms.repo_ids {
|
|
let repo = crate::models::repos::Repo::find_by_id(self.ctx.db.reader(), *repo_id)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or_else(|| AppError::NotFound(format!("Repository {} not found", repo_id)))?;
|
|
|
|
if repo.workspace_id != ws.id {
|
|
return Err(AppError::BadRequest(format!(
|
|
"Repository {} does not belong to this workspace",
|
|
repo_id
|
|
)));
|
|
}
|
|
|
|
self.ensure_repo_readable(user_uid, &repo).await?;
|
|
}
|
|
|
|
// Validate label_ids belong to repos in this workspace
|
|
for label_id in ¶ms.label_ids {
|
|
let label: Option<(Uuid,)> = sqlx::query_as(
|
|
"SELECT r.workspace_id FROM issue_label il \
|
|
JOIN repo r ON r.id = il.repo_id \
|
|
WHERE il.id = $1",
|
|
)
|
|
.bind(label_id)
|
|
.fetch_optional(self.ctx.db.reader())
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
match label {
|
|
Some((workspace_id,)) if workspace_id == ws.id => {}
|
|
Some(_) => {
|
|
return Err(AppError::BadRequest(format!(
|
|
"Label {} does not belong to this workspace",
|
|
label_id
|
|
)));
|
|
}
|
|
None => return Err(AppError::NotFound(format!("Label {} not found", label_id))),
|
|
}
|
|
}
|
|
|
|
// Validate assignee_ids are workspace members
|
|
for assignee_id in ¶ms.assignee_ids {
|
|
let is_member: bool = sqlx::query_scalar(
|
|
"SELECT EXISTS(SELECT 1 FROM workspace_member \
|
|
WHERE workspace_id = $1 AND user_id = $2 AND status = 'active')",
|
|
)
|
|
.bind(ws.id)
|
|
.bind(assignee_id)
|
|
.fetch_one(self.ctx.db.reader())
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
if !is_member {
|
|
return Err(AppError::BadRequest(format!(
|
|
"User {} is not a member of this workspace",
|
|
assignee_id
|
|
)));
|
|
}
|
|
}
|
|
|
|
// Validate milestone_id belongs to a repo in this workspace
|
|
if let Some(milestone_id) = params.milestone_id {
|
|
let milestone: Option<(Uuid,)> = sqlx::query_as(
|
|
"SELECT r.workspace_id FROM issue_milestone im \
|
|
JOIN repo r ON r.id = im.repo_id \
|
|
WHERE im.id = $1",
|
|
)
|
|
.bind(milestone_id)
|
|
.fetch_optional(self.ctx.db.reader())
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
match milestone {
|
|
Some((workspace_id,)) if workspace_id == ws.id => {}
|
|
Some(_) => {
|
|
return Err(AppError::BadRequest(
|
|
"Milestone does not belong to this workspace".into(),
|
|
));
|
|
}
|
|
None => return Err(AppError::NotFound("Milestone not found".into())),
|
|
}
|
|
}
|
|
|
|
let priority = match params.priority {
|
|
Some(ref v) => parse_enum(
|
|
Some(v.clone()),
|
|
Priority::None,
|
|
Priority::Unknown,
|
|
"priority",
|
|
)?,
|
|
None => Priority::None,
|
|
};
|
|
let visibility = match params.visibility {
|
|
Some(ref v) => parse_enum(
|
|
Some(v.clone()),
|
|
Visibility::Public,
|
|
Visibility::Unknown,
|
|
"visibility",
|
|
)?,
|
|
None => Visibility::Public,
|
|
};
|
|
|
|
let now = chrono::Utc::now();
|
|
let issue_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 number = Issue::next_number(&mut *txn, ws.id)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
let issue = sqlx::query_as::<_, Issue>(
|
|
"INSERT INTO issue (id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, 'open', $7, $8, false, $9, NULL, NULL, $10, $11, $11) \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(issue_id)
|
|
.bind(ws.id)
|
|
.bind(user_uid)
|
|
.bind(number)
|
|
.bind(&title)
|
|
.bind(params.body.as_deref())
|
|
.bind(priority)
|
|
.bind(visibility)
|
|
.bind(params.milestone_id)
|
|
.bind(params.due_at)
|
|
.bind(now)
|
|
.fetch_one(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
sqlx::query(
|
|
"INSERT INTO issue_stats (issue_id, comments_count, reactions_count, assignees_count, \
|
|
labels_count, subscribers_count, last_commented_at, updated_at) \
|
|
VALUES ($1, 0, 0, $2, $3, 1, NULL, $4)",
|
|
)
|
|
.bind(issue_id)
|
|
.bind(params.assignee_ids.len() as i32)
|
|
.bind(params.label_ids.len() as i32)
|
|
.bind(now)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
sqlx::query(
|
|
"INSERT INTO issue_subscriber (id, issue_id, user_id, reason, muted, created_at, updated_at) \
|
|
VALUES ($1, $2, $3, 'author', false, $4, $4)",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(issue_id)
|
|
.bind(user_uid)
|
|
.bind(now)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
for repo_id in ¶ms.repo_ids {
|
|
sqlx::query(
|
|
"INSERT INTO issue_repo_relation (id, issue_id, repo_id, relation_type, created_by, created_at) \
|
|
VALUES ($1, $2, $3, 'references', $4, $5)",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(issue_id)
|
|
.bind(repo_id)
|
|
.bind(user_uid)
|
|
.bind(now)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
}
|
|
|
|
for label_id in ¶ms.label_ids {
|
|
sqlx::query(
|
|
"INSERT INTO issue_label_relation (id, issue_id, label_id, created_by, created_at) \
|
|
VALUES ($1, $2, $3, $4, $5)",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(issue_id)
|
|
.bind(label_id)
|
|
.bind(user_uid)
|
|
.bind(now)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
}
|
|
|
|
for assignee_id in ¶ms.assignee_ids {
|
|
sqlx::query(
|
|
"INSERT INTO issue_assignee (id, issue_id, assignee_id, assigned_by, created_at) \
|
|
VALUES ($1, $2, $3, $4, $5)",
|
|
)
|
|
.bind(Uuid::now_v7())
|
|
.bind(issue_id)
|
|
.bind(assignee_id)
|
|
.bind(user_uid)
|
|
.bind(now)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
}
|
|
|
|
sqlx::query(
|
|
"UPDATE workspace_stats SET issues_count = issues_count + 1, updated_at = $1 \
|
|
WHERE workspace_id = $2",
|
|
)
|
|
.bind(now)
|
|
.bind(ws.id)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Created)
|
|
.await;
|
|
tracing::info!(issue_id = %issue_id, number = number, "Issue created");
|
|
Ok(issue)
|
|
}
|
|
|
|
pub async fn issue_update(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
params: UpdateIssueParams,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_editable(user_uid, &issue).await?;
|
|
|
|
let title = merge_optional_text(params.title, Some(issue.title.clone()))
|
|
.unwrap_or(issue.title.clone());
|
|
let body = merge_optional_text(params.body, issue.body.clone());
|
|
let priority = match params.priority {
|
|
Some(ref v) => parse_enum(
|
|
Some(v.clone()),
|
|
issue.priority,
|
|
Priority::Unknown,
|
|
"priority",
|
|
)?,
|
|
None => issue.priority,
|
|
};
|
|
let visibility = match params.visibility {
|
|
Some(ref v) => parse_enum(
|
|
Some(v.clone()),
|
|
issue.visibility,
|
|
Visibility::Unknown,
|
|
"visibility",
|
|
)?,
|
|
None => issue.visibility,
|
|
};
|
|
|
|
if let Some(milestone_id) = params.milestone_id {
|
|
self.ensure_milestone_in_workspace(milestone_id, issue.workspace_id)
|
|
.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_as::<_, Issue>(
|
|
"UPDATE issue SET title = $1, body = $2, priority = $3, visibility = $4, \
|
|
due_at = $5, milestone_id = $6, updated_at = $7 WHERE id = $8 AND deleted_at IS NULL \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(&title)
|
|
.bind(&body)
|
|
.bind(priority)
|
|
.bind(visibility)
|
|
.bind(params.due_at.or(issue.due_at))
|
|
.bind(params.milestone_id.or(issue.milestone_id))
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.fetch_one(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Updated)
|
|
.await;
|
|
Ok(result)
|
|
}
|
|
|
|
pub async fn issue_close(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_editable(user_uid, &issue).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_as::<_, Issue>(
|
|
"UPDATE issue SET state = 'closed', closed_by = $1, closed_at = $2, updated_at = $2 \
|
|
WHERE id = $3 AND deleted_at IS NULL AND state = 'open' \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(user_uid)
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.fetch_optional(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or(AppError::NotFound("issue not found or already closed".into()))?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Closed)
|
|
.await;
|
|
Ok(result)
|
|
}
|
|
|
|
pub async fn issue_reopen(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_editable(user_uid, &issue).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_as::<_, Issue>(
|
|
"UPDATE issue SET state = 'open', closed_by = NULL, closed_at = NULL, updated_at = $1 \
|
|
WHERE id = $2 AND deleted_at IS NULL AND state = 'closed' \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.fetch_optional(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or(AppError::NotFound("issue not found or not closed".into()))?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Reopened)
|
|
.await;
|
|
Ok(result)
|
|
}
|
|
|
|
pub async fn issue_delete(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
) -> Result<(), AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_admin(user_uid, &issue).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 issue SET deleted_at = $1, updated_at = $1 WHERE id = $2 AND deleted_at IS NULL",
|
|
)
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
ensure_affected(result.rows_affected(), "issue not found")?;
|
|
|
|
sqlx::query(
|
|
"UPDATE workspace_stats SET issues_count = GREATEST(issues_count - 1, 0), updated_at = $1 \
|
|
WHERE workspace_id = $2",
|
|
)
|
|
.bind(now)
|
|
.bind(issue.workspace_id)
|
|
.execute(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Deleted)
|
|
.await;
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn issue_lock(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
locked: bool,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_editable(user_uid, &issue).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_as::<_, Issue>(
|
|
"UPDATE issue SET locked = $1, updated_at = $2 WHERE id = $3 AND deleted_at IS NULL \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(locked)
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.fetch_one(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
let event_type = if locked {
|
|
EventType::Archived
|
|
} else {
|
|
EventType::Restored
|
|
};
|
|
self.record_issue_event(issue_id, Some(user_uid), event_type)
|
|
.await;
|
|
Ok(result)
|
|
}
|
|
|
|
pub async fn issue_transfer(
|
|
&self,
|
|
ctx: &Session,
|
|
wk_name: &str,
|
|
number: i64,
|
|
new_wk_name: &str,
|
|
) -> Result<Issue, AppError> {
|
|
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
|
let issue = self.resolve_issue(wk_name, number).await?;
|
|
let issue_id = issue.id;
|
|
self.ensure_issue_admin(user_uid, &issue).await?;
|
|
let new_ws = self.resolve_workspace(new_wk_name).await?;
|
|
self.ensure_workspace_role_at_least(new_wk_name, user_uid, Role::Admin)
|
|
.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 new_number = Issue::next_number(&mut *txn, new_ws.id)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
let result = sqlx::query_as::<_, Issue>(
|
|
"UPDATE issue SET workspace_id = $1, number = $2, updated_at = $3 WHERE id = $4 AND deleted_at IS NULL \
|
|
RETURNING id, workspace_id, author_id, number, title, body, state, priority, \
|
|
visibility, locked, milestone_id, closed_by, closed_at, due_at, created_at, updated_at, deleted_at",
|
|
)
|
|
.bind(new_ws.id)
|
|
.bind(new_number)
|
|
.bind(now)
|
|
.bind(issue_id)
|
|
.fetch_one(&mut *txn)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
sqlx::query(
|
|
"UPDATE workspace_stats SET issues_count = GREATEST(issues_count - 1, 0), updated_at = $1 WHERE workspace_id = $2",
|
|
).bind(now).bind(issue.workspace_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
|
|
|
sqlx::query(
|
|
"UPDATE workspace_stats SET issues_count = issues_count + 1, updated_at = $1 WHERE workspace_id = $2",
|
|
).bind(now).bind(new_ws.id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
|
|
|
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
|
self.record_issue_event(issue_id, Some(user_uid), EventType::Updated)
|
|
.await;
|
|
Ok(result)
|
|
}
|
|
|
|
async fn record_issue_event(
|
|
&self,
|
|
issue_id: Uuid,
|
|
actor_id: Option<Uuid>,
|
|
event_type: EventType,
|
|
) {
|
|
if let Err(err) = self
|
|
.create_issue_event(issue_id, actor_id, event_type, None, None, None)
|
|
.await
|
|
{
|
|
tracing::warn!(issue_id = %issue_id, error = %err, "Failed to create issue event");
|
|
}
|
|
}
|
|
|
|
async fn ensure_milestone_in_workspace(
|
|
&self,
|
|
milestone_id: Uuid,
|
|
workspace_id: Uuid,
|
|
) -> Result<(), AppError> {
|
|
let milestone_workspace_id: Option<Uuid> = sqlx::query_scalar(
|
|
"SELECT r.workspace_id FROM issue_milestone im \
|
|
JOIN repo r ON r.id = im.repo_id \
|
|
WHERE im.id = $1",
|
|
)
|
|
.bind(milestone_id)
|
|
.fetch_optional(self.ctx.db.reader())
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
|
|
match milestone_workspace_id {
|
|
Some(id) if id == workspace_id => Ok(()),
|
|
Some(_) => Err(AppError::BadRequest(
|
|
"Milestone does not belong to this workspace".into(),
|
|
)),
|
|
None => Err(AppError::NotFound("Milestone not found".into())),
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn resolve_workspace(&self, wk_name: &str) -> Result<Workspace, AppError> {
|
|
Workspace::find_by_name(self.ctx.db.reader(), wk_name)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or(AppError::NotFound("workspace not found".into()))
|
|
}
|
|
|
|
pub(crate) async fn resolve_issue(
|
|
&self,
|
|
wk_name: &str,
|
|
number: i64,
|
|
) -> Result<Issue, AppError> {
|
|
let ws = self.resolve_workspace(wk_name).await?;
|
|
Issue::find_by_number(self.ctx.db.reader(), ws.id, number)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or(AppError::NotFound("issue not found".into()))
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub(crate) async fn find_issue_by_id(&self, issue_id: Uuid) -> Result<Issue, AppError> {
|
|
Issue::find_by_id(self.ctx.db.reader(), issue_id)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.ok_or(AppError::NotFound("issue not found".into()))
|
|
}
|
|
|
|
pub(crate) async fn ensure_issue_readable(
|
|
&self,
|
|
user_uid: Uuid,
|
|
issue: &Issue,
|
|
) -> Result<(), AppError> {
|
|
if issue.author_id == user_uid {
|
|
return Ok(());
|
|
}
|
|
let is_member = Workspace::is_member(self.ctx.db.reader(), issue.workspace_id, user_uid)
|
|
.await
|
|
.map_err(AppError::Database)?;
|
|
if is_member {
|
|
return Ok(());
|
|
}
|
|
if issue.visibility == Visibility::Public {
|
|
return Ok(());
|
|
}
|
|
Err(AppError::Unauthorized)
|
|
}
|
|
|
|
pub(crate) async fn ensure_issue_editable(
|
|
&self,
|
|
user_uid: Uuid,
|
|
issue: &Issue,
|
|
) -> Result<(), AppError> {
|
|
if issue.author_id == user_uid {
|
|
return Ok(());
|
|
}
|
|
let role = Workspace::user_role(
|
|
self.ctx.db.reader(),
|
|
issue.workspace_id,
|
|
user_uid,
|
|
Uuid::nil(),
|
|
)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.unwrap_or(Role::Unknown);
|
|
if crate::service::util::role_level(role) >= crate::service::util::role_level(Role::Member)
|
|
{
|
|
return Ok(());
|
|
}
|
|
Err(AppError::Unauthorized)
|
|
}
|
|
|
|
pub(crate) async fn ensure_issue_admin(
|
|
&self,
|
|
user_uid: Uuid,
|
|
issue: &Issue,
|
|
) -> Result<(), AppError> {
|
|
let role = Workspace::user_role(
|
|
self.ctx.db.reader(),
|
|
issue.workspace_id,
|
|
user_uid,
|
|
Uuid::nil(),
|
|
)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.unwrap_or(Role::Unknown);
|
|
if crate::service::util::role_level(role) >= crate::service::util::role_level(Role::Admin) {
|
|
return Ok(());
|
|
}
|
|
Err(AppError::Unauthorized)
|
|
}
|
|
|
|
pub(crate) async fn ensure_workspace_readable(
|
|
&self,
|
|
wk_name: &str,
|
|
user_uid: Uuid,
|
|
) -> Result<(), AppError> {
|
|
let ws = self.resolve_workspace(wk_name).await?;
|
|
if Workspace::is_readable(self.ctx.db.reader(), &ws, user_uid)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
{
|
|
Ok(())
|
|
} else {
|
|
Err(AppError::Unauthorized)
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn ensure_workspace_role_at_least(
|
|
&self,
|
|
wk_name: &str,
|
|
user_uid: Uuid,
|
|
min_role: Role,
|
|
) -> Result<Role, AppError> {
|
|
let ws = self.resolve_workspace(wk_name).await?;
|
|
let role = Workspace::user_role(self.ctx.db.reader(), ws.id, user_uid, ws.owner_id)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
.unwrap_or(Role::Unknown);
|
|
if crate::service::util::role_level(role) < crate::service::util::role_level(min_role) {
|
|
return Err(AppError::Unauthorized);
|
|
}
|
|
Ok(role)
|
|
}
|
|
|
|
pub(crate) async fn ensure_repo_readable(
|
|
&self,
|
|
user_uid: Uuid,
|
|
repo: &crate::models::repos::Repo,
|
|
) -> Result<(), AppError> {
|
|
use crate::models::repos::Repo;
|
|
|
|
if Repo::is_readable(self.ctx.db.reader(), repo, user_uid)
|
|
.await
|
|
.map_err(AppError::Database)?
|
|
{
|
|
Ok(())
|
|
} else {
|
|
Err(AppError::Unauthorized)
|
|
}
|
|
}
|
|
}
|