feat: init
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::issues::IssueAssignee;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected};
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_assignees(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueAssignee>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueAssignee>(
|
||||
"SELECT id, issue_id, assignee_id, assigned_by, created_at \
|
||||
FROM issue_assignee WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_assign(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
assignee_id: Uuid,
|
||||
) -> Result<IssueAssignee, 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 assignee = sqlx::query_as::<_, IssueAssignee>(
|
||||
"INSERT INTO issue_assignee (id, issue_id, assignee_id, assigned_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (issue_id, assignee_id) DO NOTHING \
|
||||
RETURNING id, issue_id, assignee_id, assigned_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(issue_id)
|
||||
.bind(assignee_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_optional(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("user already assigned".into()))?;
|
||||
sqlx::query("UPDATE issue_stats SET assignees_count = assignees_count + 1, updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).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, 'assignee', false, $4, $4) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(issue_id).bind(assignee_id).bind(now)
|
||||
.execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(assignee)
|
||||
}
|
||||
|
||||
pub async fn issue_unassign(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
assignee_id: Uuid,
|
||||
) -> 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_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("DELETE FROM issue_assignee WHERE issue_id = $1 AND assignee_id = $2")
|
||||
.bind(issue_id)
|
||||
.bind(assignee_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "assignee not found")?;
|
||||
sqlx::query("UPDATE issue_stats SET assignees_count = GREATEST(assignees_count - 1, 0), updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::issues::IssueComment;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, required_text};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateCommentParams {
|
||||
pub body: String,
|
||||
pub reply_to_comment_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateCommentParams {
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_comments(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueComment>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueComment>(
|
||||
"SELECT id, issue_id, author_id, body, reply_to_comment_id, edited_at, deleted_at, \
|
||||
created_at, updated_at FROM issue_comment \
|
||||
WHERE issue_id = $1 AND deleted_at IS NULL ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_create_comment(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
params: CreateCommentParams,
|
||||
) -> Result<IssueComment, 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_readable(user_uid, &issue).await?;
|
||||
|
||||
if issue.locked {
|
||||
self.ensure_issue_editable(user_uid, &issue).await?;
|
||||
}
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
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 comment = sqlx::query_as::<_, IssueComment>(
|
||||
"INSERT INTO issue_comment (id, issue_id, author_id, body, reply_to_comment_id, \
|
||||
edited_at, deleted_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, NULL, NULL, $6, $6) \
|
||||
RETURNING id, issue_id, author_id, body, reply_to_comment_id, edited_at, deleted_at, \
|
||||
created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(issue_id)
|
||||
.bind(user_uid)
|
||||
.bind(&body)
|
||||
.bind(params.reply_to_comment_id)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE issue_stats SET comments_count = comments_count + 1, \
|
||||
last_commented_at = $1, updated_at = $1 WHERE issue_id = $2",
|
||||
)
|
||||
.bind(now)
|
||||
.bind(issue_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let is_subscribed: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM issue_subscriber WHERE issue_id = $1 AND user_id = $2)",
|
||||
)
|
||||
.bind(issue_id)
|
||||
.bind(user_uid)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if !is_subscribed {
|
||||
sqlx::query(
|
||||
"INSERT INTO issue_subscriber (id, issue_id, user_id, reason, muted, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, 'participant', false, $4, $4) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(issue_id).bind(user_uid).bind(now)
|
||||
.execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(comment)
|
||||
}
|
||||
|
||||
pub async fn issue_update_comment(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
comment_id: Uuid,
|
||||
params: UpdateCommentParams,
|
||||
) -> Result<IssueComment, 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_readable(user_uid, &issue).await?;
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
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::<_, IssueComment>(
|
||||
"UPDATE issue_comment SET body = $1, edited_at = $2, updated_at = $2 \
|
||||
WHERE id = $3 AND issue_id = $4 AND author_id = $5 AND deleted_at IS NULL \
|
||||
RETURNING id, issue_id, author_id, body, reply_to_comment_id, edited_at, deleted_at, \
|
||||
created_at, updated_at",
|
||||
)
|
||||
.bind(&body)
|
||||
.bind(now)
|
||||
.bind(comment_id)
|
||||
.bind(issue_id)
|
||||
.bind(user_uid)
|
||||
.fetch_optional(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound(
|
||||
"comment not found or not authored by you".into(),
|
||||
))?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn issue_delete_comment(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
comment_id: Uuid,
|
||||
) -> 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;
|
||||
|
||||
let comment = sqlx::query_as::<_, IssueComment>(
|
||||
"SELECT id, issue_id, author_id, body, reply_to_comment_id, edited_at, deleted_at, \
|
||||
created_at, updated_at FROM issue_comment WHERE id = $1 AND issue_id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(comment_id).bind(issue_id).fetch_optional(self.ctx.db.reader()).await
|
||||
.map_err(AppError::Database)?.ok_or(AppError::NotFound("comment not found".into()))?;
|
||||
|
||||
if comment.author_id != user_uid {
|
||||
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_comment SET deleted_at = $1, updated_at = $1 WHERE id = $2 AND deleted_at IS NULL",
|
||||
)
|
||||
.bind(now).bind(comment_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "comment not found")?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE issue_stats SET comments_count = GREATEST(comments_count - 1, 0), updated_at = $1 WHERE issue_id = $2",
|
||||
)
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,867 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::{EventType, JsonValue};
|
||||
use crate::models::issues::IssueEvent;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::clamp_limit_offset;
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_list_events(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueEvent>, 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?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, IssueEvent>(
|
||||
"SELECT id, issue_id, actor_id, event_type, old_value, new_value, metadata, created_at \
|
||||
FROM issue_event WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub(crate) async fn create_issue_event(
|
||||
&self,
|
||||
issue_id: Uuid,
|
||||
actor_id: Option<Uuid>,
|
||||
event_type: EventType,
|
||||
old_value: Option<JsonValue>,
|
||||
new_value: Option<JsonValue>,
|
||||
metadata: Option<JsonValue>,
|
||||
) -> Result<IssueEvent, AppError> {
|
||||
sqlx::query_as::<_, IssueEvent>(
|
||||
"INSERT INTO issue_event (id, issue_id, actor_id, event_type, old_value, new_value, metadata, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
|
||||
RETURNING id, issue_id, actor_id, event_type, old_value, new_value, metadata, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(issue_id)
|
||||
.bind(actor_id)
|
||||
.bind(event_type)
|
||||
.bind(old_value)
|
||||
.bind(new_value)
|
||||
.bind(metadata)
|
||||
.bind(chrono::Utc::now())
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::issues::{IssueLabel, IssueLabelRelation};
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, required_text};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateLabelParams {
|
||||
pub name: String,
|
||||
pub color: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateLabelParams {
|
||||
pub name: Option<String>,
|
||||
pub color: Option<String>,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub(crate) async fn resolve_repo_id(
|
||||
&self,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
) -> Result<Uuid, AppError> {
|
||||
let ws = self.resolve_workspace(wk_name).await?;
|
||||
crate::models::repos::Repo::find_by_name(self.ctx.db.reader(), ws.id, repo_name)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.map(|r| r.id)
|
||||
.ok_or(AppError::NotFound("repo not found".into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_repo_role(
|
||||
&self,
|
||||
repo_id: Uuid,
|
||||
user_uid: Uuid,
|
||||
min: Role,
|
||||
) -> Result<(), AppError> {
|
||||
let repo = crate::models::repos::Repo::find_by_id(self.ctx.db.reader(), repo_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("repo not found".into()))?;
|
||||
let role = crate::models::repos::Repo::user_role(
|
||||
self.ctx.db.reader(),
|
||||
repo.id,
|
||||
user_uid,
|
||||
repo.owner_id,
|
||||
)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.unwrap_or(Role::Unknown);
|
||||
if crate::service::util::role_level(role) < crate::service::util::role_level(min) {
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn issue_labels(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
) -> Result<Vec<IssueLabel>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
let repo = crate::models::repos::Repo::find_by_id(self.ctx.db.reader(), repo_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("repo not found".into()))?;
|
||||
self.ensure_repo_readable(user_uid, &repo).await?;
|
||||
sqlx::query_as::<_, IssueLabel>(
|
||||
"SELECT id, repo_id, name, color, description, created_by, created_at, updated_at \
|
||||
FROM issue_label WHERE repo_id = $1 ORDER BY name ASC",
|
||||
)
|
||||
.bind(repo_id)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_create_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
params: CreateLabelParams,
|
||||
) -> Result<IssueLabel, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Member)
|
||||
.await?;
|
||||
let name = required_text(params.name, "name")?;
|
||||
let color = required_text(params.color, "color")?;
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, IssueLabel>(
|
||||
"INSERT INTO issue_label (id, repo_id, name, color, description, created_by, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $7) \
|
||||
RETURNING id, repo_id, name, color, description, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(repo_id).bind(&name).bind(&color)
|
||||
.bind(params.description.as_deref()).bind(user_uid).bind(now)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_update_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
label_id: Uuid,
|
||||
params: UpdateLabelParams,
|
||||
) -> Result<IssueLabel, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Admin)
|
||||
.await?;
|
||||
let current = sqlx::query_as::<_, IssueLabel>(
|
||||
"SELECT id, repo_id, name, color, description, created_by, created_at, updated_at \
|
||||
FROM issue_label WHERE id = $1 AND repo_id = $2",
|
||||
)
|
||||
.bind(label_id)
|
||||
.bind(repo_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("label not found".into()))?;
|
||||
|
||||
let name = params.name.unwrap_or(current.name);
|
||||
let color = params.color.unwrap_or(current.color);
|
||||
let description = super::util::merge_optional_text(params.description, current.description);
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, IssueLabel>(
|
||||
"UPDATE issue_label SET name = $1, color = $2, description = $3, updated_at = $4 \
|
||||
WHERE id = $5 RETURNING id, repo_id, name, color, description, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(&name).bind(&color).bind(&description).bind(now).bind(label_id)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_delete_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
label_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Admin)
|
||||
.await?;
|
||||
let result = sqlx::query("DELETE FROM issue_label WHERE id = $1 AND repo_id = $2")
|
||||
.bind(label_id)
|
||||
.bind(repo_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "label not found")
|
||||
}
|
||||
|
||||
pub async fn issue_assign_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
label_id: Uuid,
|
||||
) -> Result<IssueLabelRelation, 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 rel = sqlx::query_as::<_, IssueLabelRelation>(
|
||||
"INSERT INTO issue_label_relation (id, issue_id, label_id, created_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (issue_id, label_id) DO NOTHING \
|
||||
RETURNING id, issue_id, label_id, created_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(issue_id)
|
||||
.bind(label_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_optional(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("label already assigned".into()))?;
|
||||
sqlx::query("UPDATE issue_stats SET labels_count = labels_count + 1, updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(rel)
|
||||
}
|
||||
|
||||
pub async fn issue_unassign_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
label_id: Uuid,
|
||||
) -> 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_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("DELETE FROM issue_label_relation WHERE issue_id = $1 AND label_id = $2")
|
||||
.bind(issue_id)
|
||||
.bind(label_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "label not assigned")?;
|
||||
sqlx::query("UPDATE issue_stats SET labels_count = GREATEST(labels_count - 1, 0), updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn issue_label_relations(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueLabelRelation>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueLabelRelation>(
|
||||
"SELECT id, issue_id, label_id, created_by, created_at \
|
||||
FROM issue_label_relation WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::{Role, State};
|
||||
use crate::models::issues::IssueMilestone;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, merge_optional_text, required_text};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateMilestoneParams {
|
||||
pub title: String,
|
||||
pub description: Option<String>,
|
||||
pub due_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateMilestoneParams {
|
||||
pub title: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub due_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
pub state: Option<String>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_milestones(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueMilestone>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
let repo = crate::models::repos::Repo::find_by_id(self.ctx.db.reader(), repo_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("repo not found".into()))?;
|
||||
self.ensure_repo_readable(user_uid, &repo).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueMilestone>(
|
||||
"SELECT id, repo_id, title, description, state, due_at, closed_at, created_by, \
|
||||
created_at, updated_at FROM issue_milestone WHERE repo_id = $1 \
|
||||
ORDER BY state ASC, due_at ASC NULLS LAST LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(repo_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_create_milestone(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
params: CreateMilestoneParams,
|
||||
) -> Result<IssueMilestone, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Member)
|
||||
.await?;
|
||||
let title = required_text(params.title, "title")?;
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, IssueMilestone>(
|
||||
"INSERT INTO issue_milestone (id, repo_id, title, description, state, due_at, closed_at, \
|
||||
created_by, created_at, updated_at) VALUES ($1, $2, $3, $4, 'open', $5, NULL, $6, $7, $7) \
|
||||
RETURNING id, repo_id, title, description, state, due_at, closed_at, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(repo_id).bind(&title).bind(params.description.as_deref())
|
||||
.bind(params.due_at).bind(user_uid).bind(now)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_update_milestone(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
milestone_id: Uuid,
|
||||
params: UpdateMilestoneParams,
|
||||
) -> Result<IssueMilestone, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Member)
|
||||
.await?;
|
||||
let current = sqlx::query_as::<_, IssueMilestone>(
|
||||
"SELECT id, repo_id, title, description, state, due_at, closed_at, created_by, created_at, updated_at \
|
||||
FROM issue_milestone WHERE id = $1 AND repo_id = $2",
|
||||
)
|
||||
.bind(milestone_id).bind(repo_id).fetch_optional(self.ctx.db.reader()).await
|
||||
.map_err(AppError::Database)?.ok_or(AppError::NotFound("milestone not found".into()))?;
|
||||
|
||||
let title = params.title.unwrap_or(current.title);
|
||||
let description = merge_optional_text(params.description, current.description);
|
||||
let due_at = params.due_at.or(current.due_at);
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
let (state, closed_at) = match params.state.as_deref() {
|
||||
Some("closed") if current.state != State::Closed => (State::Closed, Some(now)),
|
||||
Some("open") if current.state != State::Open => (State::Open, None),
|
||||
_ => (current.state, current.closed_at),
|
||||
};
|
||||
|
||||
sqlx::query_as::<_, IssueMilestone>(
|
||||
"UPDATE issue_milestone SET title = $1, description = $2, state = $3, due_at = $4, \
|
||||
closed_at = $5, updated_at = $6 WHERE id = $7 \
|
||||
RETURNING id, repo_id, title, description, state, due_at, closed_at, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(&title).bind(&description).bind(state).bind(due_at).bind(closed_at).bind(now).bind(milestone_id)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_delete_milestone(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
milestone_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Admin)
|
||||
.await?;
|
||||
let result = sqlx::query("DELETE FROM issue_milestone WHERE id = $1 AND repo_id = $2")
|
||||
.bind(milestone_id)
|
||||
.bind(repo_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "milestone not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
pub mod assignees;
|
||||
pub mod comments;
|
||||
pub mod core;
|
||||
pub mod events;
|
||||
pub mod labels;
|
||||
pub mod milestones;
|
||||
pub mod pr_relations;
|
||||
pub mod reactions;
|
||||
pub mod repo_relations;
|
||||
pub mod subscribers;
|
||||
pub mod templates;
|
||||
pub mod util;
|
||||
@@ -0,0 +1,122 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::RelationType;
|
||||
use crate::models::issues::IssuePrRelation;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, parse_enum};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct LinkPrParams {
|
||||
pub pull_request_id: Uuid,
|
||||
pub relation_type: Option<String>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_pr_relations(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssuePrRelation>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssuePrRelation>(
|
||||
"SELECT id, issue_id, pull_request_id, relation_type, created_by, created_at \
|
||||
FROM issue_pr_relation WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_link_pr(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
params: LinkPrParams,
|
||||
) -> Result<IssuePrRelation, 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 relation_type = match params.relation_type {
|
||||
Some(ref v) => parse_enum(
|
||||
Some(v.clone()),
|
||||
RelationType::References,
|
||||
RelationType::Unknown,
|
||||
"relation_type",
|
||||
)?,
|
||||
None => RelationType::References,
|
||||
};
|
||||
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 rel = sqlx::query_as::<_, IssuePrRelation>(
|
||||
"INSERT INTO issue_pr_relation (id, issue_id, pull_request_id, relation_type, created_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (issue_id, pull_request_id) DO NOTHING \
|
||||
RETURNING id, issue_id, pull_request_id, relation_type, created_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(issue_id).bind(params.pull_request_id)
|
||||
.bind(relation_type).bind(user_uid).bind(now)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("PR already linked".into()))?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(rel)
|
||||
}
|
||||
|
||||
pub async fn issue_unlink_pr(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
relation_id: Uuid,
|
||||
) -> 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_editable(user_uid, &issue).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 issue_pr_relation WHERE id = $1 AND issue_id = $2")
|
||||
.bind(relation_id)
|
||||
.bind(issue_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "PR relation not found")?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::TargetType;
|
||||
use crate::models::issues::IssueReaction;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, required_text};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateIssueReactionParams {
|
||||
pub content: String,
|
||||
pub target_type: Option<String>,
|
||||
pub target_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_reactions(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueReaction>, 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?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, IssueReaction>(
|
||||
"SELECT id, issue_id, user_id, content, target_type, target_id, created_at \
|
||||
FROM issue_reaction WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_add_reaction(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
params: CreateIssueReactionParams,
|
||||
) -> Result<IssueReaction, 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?;
|
||||
|
||||
let content = required_text(params.content, "content")?;
|
||||
let target_type = params
|
||||
.target_type
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<TargetType>().ok())
|
||||
.unwrap_or(TargetType::Issue);
|
||||
if target_type == TargetType::Unknown {
|
||||
return Err(AppError::BadRequest("invalid target_type".into()));
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, IssueReaction>(
|
||||
"INSERT INTO issue_reaction (id, issue_id, user_id, content, target_type, target_id, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) \
|
||||
RETURNING id, issue_id, user_id, content, target_type, target_id, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(issue.id)
|
||||
.bind(user_uid)
|
||||
.bind(&content)
|
||||
.bind(target_type)
|
||||
.bind(params.target_id)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_remove_reaction(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
reaction_id: Uuid,
|
||||
) -> Result<(), 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?;
|
||||
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM issue_reaction WHERE id = $1 AND issue_id = $2 AND user_id = $3",
|
||||
)
|
||||
.bind(reaction_id)
|
||||
.bind(issue.id)
|
||||
.bind(user_uid)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(
|
||||
result.rows_affected(),
|
||||
"reaction not found or not authored by you",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::RelationType;
|
||||
use crate::models::issues::IssueRepoRelation;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, parse_enum};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct LinkRepoParams {
|
||||
pub repo_id: Uuid,
|
||||
pub relation_type: Option<String>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_repo_relations(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueRepoRelation>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueRepoRelation>(
|
||||
"SELECT id, issue_id, repo_id, relation_type, created_by, created_at \
|
||||
FROM issue_repo_relation WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_link_repo(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
params: LinkRepoParams,
|
||||
) -> Result<IssueRepoRelation, 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 relation_type = match params.relation_type {
|
||||
Some(ref v) => parse_enum(
|
||||
Some(v.clone()),
|
||||
RelationType::References,
|
||||
RelationType::Unknown,
|
||||
"relation_type",
|
||||
)?,
|
||||
None => RelationType::References,
|
||||
};
|
||||
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 rel = sqlx::query_as::<_, IssueRepoRelation>(
|
||||
"INSERT INTO issue_repo_relation (id, issue_id, repo_id, relation_type, created_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (issue_id, repo_id) DO NOTHING \
|
||||
RETURNING id, issue_id, repo_id, relation_type, created_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(issue_id).bind(params.repo_id)
|
||||
.bind(relation_type).bind(user_uid).bind(now)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("repo already linked".into()))?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(rel)
|
||||
}
|
||||
|
||||
pub async fn issue_unlink_repo(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
relation_id: Uuid,
|
||||
) -> 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_editable(user_uid, &issue).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 issue_repo_relation WHERE id = $1 AND issue_id = $2")
|
||||
.bind(relation_id)
|
||||
.bind(issue_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "repo relation not found")?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::issues::IssueSubscriber;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected};
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_subscribers(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueSubscriber>, 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_readable(user_uid, &issue).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueSubscriber>(
|
||||
"SELECT id, issue_id, user_id, reason, muted, created_at, updated_at \
|
||||
FROM issue_subscriber WHERE issue_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(issue_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_subscribe(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
) -> Result<IssueSubscriber, 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_readable(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 sub = sqlx::query_as::<_, IssueSubscriber>(
|
||||
"INSERT INTO issue_subscriber (id, issue_id, user_id, reason, muted, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, 'manual', false, $4, $4) ON CONFLICT (issue_id, user_id) DO NOTHING \
|
||||
RETURNING id, issue_id, user_id, reason, muted, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(issue_id).bind(user_uid).bind(now)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("already subscribed".into()))?;
|
||||
sqlx::query("UPDATE issue_stats SET subscribers_count = subscribers_count + 1, updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(sub)
|
||||
}
|
||||
|
||||
pub async fn issue_unsubscribe(
|
||||
&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;
|
||||
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 issue_subscriber WHERE issue_id = $1 AND user_id = $2")
|
||||
.bind(issue_id)
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not subscribed")?;
|
||||
sqlx::query("UPDATE issue_stats SET subscribers_count = GREATEST(subscribers_count - 1, 0), updated_at = $1 WHERE issue_id = $2")
|
||||
.bind(now).bind(issue_id).execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn issue_mute(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
number: i64,
|
||||
muted: bool,
|
||||
) -> 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;
|
||||
let result = sqlx::query(
|
||||
"UPDATE issue_subscriber SET muted = $1, updated_at = $2 WHERE issue_id = $3 AND user_id = $4",
|
||||
)
|
||||
.bind(muted).bind(chrono::Utc::now()).bind(issue_id).bind(user_uid)
|
||||
.execute(self.ctx.db.writer()).await.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not subscribed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::issues::IssueTemplate;
|
||||
use crate::service::IssueService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, required_text};
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreateTemplateParams {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub title_template: Option<String>,
|
||||
pub body_template: String,
|
||||
pub labels: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateTemplateParams {
|
||||
pub name: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub title_template: Option<String>,
|
||||
pub body_template: Option<String>,
|
||||
pub labels: Option<Vec<String>>,
|
||||
pub active: Option<bool>,
|
||||
}
|
||||
|
||||
impl IssueService {
|
||||
pub async fn issue_templates(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<IssueTemplate>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
let repo = crate::models::repos::Repo::find_by_id(self.ctx.db.reader(), repo_id)
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("repo not found".into()))?;
|
||||
self.ensure_repo_readable(user_uid, &repo).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, IssueTemplate>(
|
||||
"SELECT id, repo_id, name, description, title_template, body_template, labels, \
|
||||
active, created_by, created_at, updated_at \
|
||||
FROM issue_template WHERE repo_id = $1 AND active = true \
|
||||
ORDER BY name ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(repo_id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_create_template(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
params: CreateTemplateParams,
|
||||
) -> Result<IssueTemplate, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Member)
|
||||
.await?;
|
||||
let name = required_text(params.name, "name")?;
|
||||
let body_template = required_text(params.body_template, "body_template")?;
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, IssueTemplate>(
|
||||
"INSERT INTO issue_template (id, repo_id, name, description, title_template, body_template, \
|
||||
labels, active, created_by, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, true, $8, $9, $9) \
|
||||
RETURNING id, repo_id, name, description, title_template, body_template, labels, \
|
||||
active, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(repo_id).bind(&name).bind(params.description.as_deref())
|
||||
.bind(params.title_template.as_deref()).bind(&body_template)
|
||||
.bind(sqlx::types::Json(¶ms.labels)).bind(user_uid).bind(now)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_update_template(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
template_id: Uuid,
|
||||
params: UpdateTemplateParams,
|
||||
) -> Result<IssueTemplate, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Admin)
|
||||
.await?;
|
||||
let current = sqlx::query_as::<_, IssueTemplate>(
|
||||
"SELECT id, repo_id, name, description, title_template, body_template, labels, \
|
||||
active, created_by, created_at, updated_at \
|
||||
FROM issue_template WHERE id = $1 AND repo_id = $2",
|
||||
)
|
||||
.bind(template_id)
|
||||
.bind(repo_id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("template not found".into()))?;
|
||||
|
||||
let name = params.name.unwrap_or(current.name);
|
||||
let description = params.description.or(current.description);
|
||||
let title_template = params.title_template.or(current.title_template);
|
||||
let body_template = params.body_template.unwrap_or(current.body_template);
|
||||
let labels = params.labels.unwrap_or(current.labels);
|
||||
let active = params.active.unwrap_or(current.active);
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
sqlx::query_as::<_, IssueTemplate>(
|
||||
"UPDATE issue_template SET name = $1, description = $2, title_template = $3, \
|
||||
body_template = $4, labels = $5, active = $6, updated_at = $7 WHERE id = $8 \
|
||||
RETURNING id, repo_id, name, description, title_template, body_template, labels, \
|
||||
active, created_by, created_at, updated_at",
|
||||
)
|
||||
.bind(&name)
|
||||
.bind(&description)
|
||||
.bind(&title_template)
|
||||
.bind(&body_template)
|
||||
.bind(sqlx::types::Json(&labels))
|
||||
.bind(active)
|
||||
.bind(now)
|
||||
.bind(template_id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn issue_delete_template(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
template_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo_id = self.resolve_repo_id(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role(repo_id, user_uid, Role::Admin)
|
||||
.await?;
|
||||
let result = sqlx::query("DELETE FROM issue_template WHERE id = $1 AND repo_id = $2")
|
||||
.bind(template_id)
|
||||
.bind(repo_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "template not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub use crate::service::util::{
|
||||
clamp_limit_offset, ensure_affected, merge_optional_text, parse_enum, required_text, role_level,
|
||||
};
|
||||
Reference in New Issue
Block a user