feat: init
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::prs::PrAssignee;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected};
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_assignees(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrAssignee>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrAssignee>(
|
||||
"SELECT id, pull_request_id, assignee_id, assigned_by, created_at \
|
||||
FROM pr_assignee WHERE pull_request_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_assign(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
assignee_id: Uuid,
|
||||
) -> Result<PrAssignee, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_editable(user_uid, &pr).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::<_, PrAssignee>(
|
||||
"INSERT INTO pr_assignee (id, pull_request_id, assignee_id, assigned_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (pull_request_id, assignee_id) DO NOTHING \
|
||||
RETURNING id, pull_request_id, assignee_id, assigned_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(pr.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(
|
||||
"INSERT INTO pr_subscription (id, pull_request_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(pr.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 pr_unassign(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
assignee_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_editable(user_uid, &pr).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 pr_assignee WHERE pull_request_id = $1 AND assignee_id = $2")
|
||||
.bind(pr.id)
|
||||
.bind(assignee_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "assignee not found")?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::{Role, Status};
|
||||
use crate::models::prs::PrCheckRun;
|
||||
use crate::service::PrService;
|
||||
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 CreateCheckRunParams {
|
||||
pub commit_sha: String,
|
||||
pub name: String,
|
||||
pub status: String,
|
||||
pub conclusion: Option<String>,
|
||||
pub details_url: Option<String>,
|
||||
pub external_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateCheckRunParams {
|
||||
pub status: Option<String>,
|
||||
pub conclusion: Option<String>,
|
||||
pub details_url: Option<String>,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_check_runs(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrCheckRun>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrCheckRun>(
|
||||
"SELECT id, pull_request_id, commit_sha, name, status, conclusion, details_url, \
|
||||
external_id, started_at, completed_at, created_at, updated_at \
|
||||
FROM pr_check_run WHERE pull_request_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_create_check_run(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
params: CreateCheckRunParams,
|
||||
) -> Result<PrCheckRun, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Member)
|
||||
.await?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
|
||||
let name = required_text(params.name, "name")?;
|
||||
let status = params
|
||||
.status
|
||||
.trim()
|
||||
.parse::<Status>()
|
||||
.map_err(|_| AppError::BadRequest("invalid status".into()))?;
|
||||
if status == Status::Unknown {
|
||||
return Err(AppError::BadRequest("invalid status".into()));
|
||||
}
|
||||
let conclusion = params
|
||||
.conclusion
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<Status>().ok())
|
||||
.filter(|s| *s != Status::Unknown);
|
||||
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, PrCheckRun>(
|
||||
"INSERT INTO pr_check_run (id, pull_request_id, commit_sha, name, status, conclusion, \
|
||||
details_url, external_id, started_at, completed_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $11) \
|
||||
RETURNING id, pull_request_id, commit_sha, name, status, conclusion, details_url, \
|
||||
external_id, started_at, completed_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(pr.id)
|
||||
.bind(¶ms.commit_sha)
|
||||
.bind(&name)
|
||||
.bind(status)
|
||||
.bind(conclusion)
|
||||
.bind(params.details_url.as_deref())
|
||||
.bind(params.external_id.as_deref())
|
||||
.bind(if status == Status::Running {
|
||||
Some(now)
|
||||
} else {
|
||||
None
|
||||
})
|
||||
.bind(
|
||||
if matches!(status, Status::Completed | Status::Success | Status::Failed) {
|
||||
Some(now)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
.bind(now)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_update_check_run(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
check_run_id: Uuid,
|
||||
params: UpdateCheckRunParams,
|
||||
) -> Result<PrCheckRun, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Member)
|
||||
.await?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
|
||||
let current = sqlx::query_as::<_, PrCheckRun>(
|
||||
"SELECT id, pull_request_id, commit_sha, name, status, conclusion, details_url, \
|
||||
external_id, started_at, completed_at, created_at, updated_at \
|
||||
FROM pr_check_run WHERE id = $1 AND pull_request_id = $2",
|
||||
)
|
||||
.bind(check_run_id)
|
||||
.bind(pr.id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("check run not found".into()))?;
|
||||
|
||||
let status = match params.status {
|
||||
Some(ref v) => v
|
||||
.trim()
|
||||
.parse::<Status>()
|
||||
.map_err(|_| AppError::BadRequest("invalid status".into()))?,
|
||||
None => current.status,
|
||||
};
|
||||
let conclusion = params
|
||||
.conclusion
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse::<Status>().ok())
|
||||
.filter(|s| *s != Status::Unknown)
|
||||
.or(current.conclusion);
|
||||
let details_url = params.details_url.or(current.details_url);
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
sqlx::query_as::<_, PrCheckRun>(
|
||||
"UPDATE pr_check_run SET status = $1, conclusion = $2, details_url = $3, updated_at = $4 \
|
||||
WHERE id = $5 \
|
||||
RETURNING id, pull_request_id, commit_sha, name, status, conclusion, details_url, \
|
||||
external_id, started_at, completed_at, created_at, updated_at",
|
||||
)
|
||||
.bind(status).bind(conclusion).bind(details_url.as_deref()).bind(now).bind(check_run_id)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_delete_check_run(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
check_run_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Admin)
|
||||
.await?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
|
||||
let result = sqlx::query("DELETE FROM pr_check_run WHERE id = $1 AND pull_request_id = $2")
|
||||
.bind(check_run_id)
|
||||
.bind(pr.id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "check run not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use crate::error::AppError;
|
||||
use crate::models::prs::PrCommit;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::clamp_limit_offset;
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_commits(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrCommit>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrCommit>(
|
||||
"SELECT id, pull_request_id, repo_id, commit_sha, position, authored_at, committed_at, created_at \
|
||||
FROM pr_commit WHERE pull_request_id = $1 ORDER BY position ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
+1084
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::{EventType, JsonValue};
|
||||
use crate::models::prs::PrEvent;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::clamp_limit_offset;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct CreatePrEventParams {
|
||||
pub event_type: String,
|
||||
pub old_value: Option<JsonValue>,
|
||||
pub new_value: Option<JsonValue>,
|
||||
pub metadata: Option<JsonValue>,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_list_events(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrEvent>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
|
||||
sqlx::query_as::<_, PrEvent>(
|
||||
"SELECT id, pull_request_id, actor_id, event_type, old_value, new_value, metadata, created_at \
|
||||
FROM pr_event WHERE pull_request_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub(crate) async fn create_pr_event(
|
||||
&self,
|
||||
pull_request_id: Uuid,
|
||||
actor_id: Option<Uuid>,
|
||||
event_type: EventType,
|
||||
old_value: Option<JsonValue>,
|
||||
new_value: Option<JsonValue>,
|
||||
metadata: Option<JsonValue>,
|
||||
) -> Result<PrEvent, AppError> {
|
||||
sqlx::query_as::<_, PrEvent>(
|
||||
"INSERT INTO pr_event (id, pull_request_id, actor_id, event_type, old_value, new_value, metadata, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) \
|
||||
RETURNING id, pull_request_id, actor_id, event_type, old_value, new_value, metadata, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(pull_request_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,34 @@
|
||||
use crate::error::AppError;
|
||||
use crate::models::prs::PrFile;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::clamp_limit_offset;
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_files(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrFile>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrFile>(
|
||||
"SELECT id, pull_request_id, path, old_path, status, additions, deletions, changes, \
|
||||
patch, created_at, updated_at \
|
||||
FROM pr_file WHERE pull_request_id = $1 ORDER BY path ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::prs::{PrLabel, PrLabelRelation};
|
||||
use crate::service::PrService;
|
||||
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 CreatePrLabelParams {
|
||||
pub name: String,
|
||||
pub color: String,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdatePrLabelParams {
|
||||
pub name: Option<String>,
|
||||
pub color: Option<String>,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_labels(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
) -> Result<Vec<PrLabel>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_readable(user_uid, &repo).await?;
|
||||
sqlx::query_as::<_, PrLabel>(
|
||||
"SELECT id, repo_id, name, color, description, created_by, created_at, updated_at \
|
||||
FROM pr_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 pr_create_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
params: CreatePrLabelParams,
|
||||
) -> Result<PrLabel, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, 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::<_, PrLabel>(
|
||||
"INSERT INTO pr_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 pr_update_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
label_id: Uuid,
|
||||
params: UpdatePrLabelParams,
|
||||
) -> Result<PrLabel, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Admin)
|
||||
.await?;
|
||||
let current = sqlx::query_as::<_, PrLabel>(
|
||||
"SELECT id, repo_id, name, color, description, created_by, created_at, updated_at \
|
||||
FROM pr_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::<_, PrLabel>(
|
||||
"UPDATE pr_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 pr_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 = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Admin)
|
||||
.await?;
|
||||
let result = sqlx::query("DELETE FROM pr_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 pr_assign_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
label_id: Uuid,
|
||||
) -> Result<PrLabelRelation, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_editable(user_uid, &pr).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::<_, PrLabelRelation>(
|
||||
"INSERT INTO pr_label_relation (id, pull_request_id, label_id, created_by, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5) \
|
||||
RETURNING id, pull_request_id, label_id, created_by, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7())
|
||||
.bind(pr.id)
|
||||
.bind(label_id)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(rel)
|
||||
}
|
||||
|
||||
pub async fn pr_unassign_label(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
label_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_editable(user_uid, &pr).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 pr_label_relation WHERE pull_request_id = $1 AND label_id = $2",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(label_id)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "label not assigned")?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn pr_label_relations(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrLabelRelation>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrLabelRelation>(
|
||||
"SELECT id, pull_request_id, label_id, created_by, created_at \
|
||||
FROM pr_label_relation WHERE pull_request_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::MergeStrategyKind;
|
||||
use crate::models::prs::PrMergeStrategy;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::parse_enum;
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, utoipa::ToSchema)]
|
||||
pub struct UpdateMergeStrategyParams {
|
||||
pub strategy: Option<String>,
|
||||
pub auto_merge: Option<bool>,
|
||||
pub squash_title: Option<String>,
|
||||
pub squash_message: Option<String>,
|
||||
pub delete_source_branch: Option<bool>,
|
||||
pub merge_when_checks_pass: Option<bool>,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_merge_strategy(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
) -> Result<PrMergeStrategy, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
sqlx::query_as::<_, PrMergeStrategy>(
|
||||
"SELECT pull_request_id, strategy, auto_merge, squash_title, squash_message, \
|
||||
delete_source_branch, merge_when_checks_pass, selected_by, created_at, updated_at \
|
||||
FROM pr_merge_strategy WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("PR merge strategy not found".into()))
|
||||
}
|
||||
|
||||
pub async fn pr_update_merge_strategy(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
params: UpdateMergeStrategyParams,
|
||||
) -> Result<PrMergeStrategy, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_editable(user_uid, &pr).await?;
|
||||
|
||||
let current = sqlx::query_as::<_, PrMergeStrategy>(
|
||||
"SELECT pull_request_id, strategy, auto_merge, squash_title, squash_message, \
|
||||
delete_source_branch, merge_when_checks_pass, selected_by, created_at, updated_at \
|
||||
FROM pr_merge_strategy WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
let strategy = match params.strategy {
|
||||
Some(ref v) => parse_enum(
|
||||
Some(v.clone()),
|
||||
current
|
||||
.as_ref()
|
||||
.map(|c| c.strategy)
|
||||
.unwrap_or(MergeStrategyKind::Merge),
|
||||
MergeStrategyKind::Unknown,
|
||||
"strategy",
|
||||
)?,
|
||||
None => current
|
||||
.as_ref()
|
||||
.map(|c| c.strategy)
|
||||
.unwrap_or(MergeStrategyKind::Merge),
|
||||
};
|
||||
let auto_merge = params
|
||||
.auto_merge
|
||||
.or(current.as_ref().map(|c| c.auto_merge))
|
||||
.unwrap_or(false);
|
||||
let squash_title = params
|
||||
.squash_title
|
||||
.or_else(|| current.as_ref().and_then(|c| c.squash_title.clone()));
|
||||
let squash_message = params
|
||||
.squash_message
|
||||
.or_else(|| current.as_ref().and_then(|c| c.squash_message.clone()));
|
||||
let delete_source_branch = params
|
||||
.delete_source_branch
|
||||
.or(current.as_ref().map(|c| c.delete_source_branch))
|
||||
.unwrap_or(false);
|
||||
let merge_when_checks_pass = params
|
||||
.merge_when_checks_pass
|
||||
.or(current.as_ref().map(|c| c.merge_when_checks_pass))
|
||||
.unwrap_or(false);
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
if current.is_some() {
|
||||
sqlx::query_as::<_, PrMergeStrategy>(
|
||||
"UPDATE pr_merge_strategy SET strategy = $1, auto_merge = $2, squash_title = $3, \
|
||||
squash_message = $4, delete_source_branch = $5, merge_when_checks_pass = $6, \
|
||||
selected_by = $7, updated_at = $8 WHERE pull_request_id = $9 \
|
||||
RETURNING pull_request_id, strategy, auto_merge, squash_title, squash_message, \
|
||||
delete_source_branch, merge_when_checks_pass, selected_by, created_at, updated_at",
|
||||
)
|
||||
.bind(strategy)
|
||||
.bind(auto_merge)
|
||||
.bind(squash_title.as_deref())
|
||||
.bind(squash_message.as_deref())
|
||||
.bind(delete_source_branch)
|
||||
.bind(merge_when_checks_pass)
|
||||
.bind(user_uid)
|
||||
.bind(now)
|
||||
.bind(pr.id)
|
||||
.fetch_one(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
} else {
|
||||
sqlx::query_as::<_, PrMergeStrategy>(
|
||||
"INSERT INTO pr_merge_strategy (pull_request_id, strategy, auto_merge, squash_title, \
|
||||
squash_message, delete_source_branch, merge_when_checks_pass, selected_by, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $9) \
|
||||
RETURNING pull_request_id, strategy, auto_merge, squash_title, squash_message, \
|
||||
delete_source_branch, merge_when_checks_pass, selected_by, created_at, updated_at",
|
||||
)
|
||||
.bind(pr.id).bind(strategy).bind(auto_merge).bind(squash_title.as_deref()).bind(squash_message.as_deref())
|
||||
.bind(delete_source_branch).bind(merge_when_checks_pass).bind(user_uid).bind(now)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
pub mod assignees;
|
||||
pub mod check_runs;
|
||||
pub mod commits;
|
||||
pub mod core;
|
||||
pub mod events;
|
||||
pub mod files;
|
||||
pub mod labels;
|
||||
pub mod merge_strategy;
|
||||
pub mod reactions;
|
||||
pub mod reviews;
|
||||
pub mod status;
|
||||
pub mod subscriptions;
|
||||
pub mod util;
|
||||
@@ -0,0 +1,96 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::TargetType;
|
||||
use crate::models::prs::PrReaction;
|
||||
use crate::service::PrService;
|
||||
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 CreateReactionParams {
|
||||
pub content: String,
|
||||
pub target_type: Option<String>,
|
||||
pub target_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_reactions(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrReaction>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrReaction>(
|
||||
"SELECT id, pull_request_id, user_id, content, target_type, target_id, created_at \
|
||||
FROM pr_reaction WHERE pull_request_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_add_reaction(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
params: CreateReactionParams,
|
||||
) -> Result<PrReaction, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).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::PullRequest);
|
||||
if target_type == TargetType::Unknown {
|
||||
return Err(AppError::BadRequest("invalid target_type".into()));
|
||||
}
|
||||
let now = chrono::Utc::now();
|
||||
sqlx::query_as::<_, PrReaction>(
|
||||
"INSERT INTO pr_reaction (id, pull_request_id, user_id, content, target_type, target_id, created_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7) \
|
||||
RETURNING id, pull_request_id, user_id, content, target_type, target_id, created_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(pr.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 pr_remove_reaction(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
reaction_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let result = sqlx::query(
|
||||
"DELETE FROM pr_reaction WHERE id = $1 AND pull_request_id = $2 AND user_id = $3",
|
||||
)
|
||||
.bind(reaction_id)
|
||||
.bind(pr.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,431 @@
|
||||
use chrono::Utc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::common::Role;
|
||||
use crate::models::prs::{PrReview, PrReviewComment};
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected, required_text};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct CreateReviewParams {
|
||||
pub body: Option<String>,
|
||||
pub state: Option<String>,
|
||||
pub commit_sha: Option<String>,
|
||||
pub comments: Option<Vec<ReviewCommentParams>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct ReviewCommentParams {
|
||||
pub path: String,
|
||||
pub body: String,
|
||||
pub line: Option<i32>,
|
||||
pub start_line: Option<i32>,
|
||||
pub diff_hunk: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct SubmitReviewParams {
|
||||
pub body: Option<String>,
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct DismissReviewParams {
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct AddReplyParams {
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_list_reviews(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrReview>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrReview>(
|
||||
"SELECT id, pull_request_id, author_id, state, body, commit_sha, \
|
||||
submitted_at, dismissed_at, dismissed_by, dismiss_reason, created_at, updated_at \
|
||||
FROM pr_review WHERE pull_request_id = $1 \
|
||||
ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_create_review(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
params: CreateReviewParams,
|
||||
) -> Result<PrReview, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
|
||||
let state = params.state.as_deref().unwrap_or("pending");
|
||||
if !["pending", "approved", "changes_requested", "commented"].contains(&state) {
|
||||
return Err(AppError::BadRequest("invalid review state".into()));
|
||||
}
|
||||
if matches!(state, "approved" | "changes_requested") {
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Member)
|
||||
.await?;
|
||||
if state == "approved" && pr.author_id == user_uid {
|
||||
return Err(AppError::BadRequest(
|
||||
"PR authors cannot approve their own pull requests".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let now = Utc::now();
|
||||
let review_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 review = sqlx::query_as::<_, PrReview>(
|
||||
"INSERT INTO pr_review (id, pull_request_id, author_id, state, body, commit_sha, \
|
||||
submitted_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8) \
|
||||
RETURNING id, pull_request_id, author_id, state, body, commit_sha, \
|
||||
submitted_at, dismissed_at, dismissed_by, dismiss_reason, created_at, updated_at",
|
||||
)
|
||||
.bind(review_id)
|
||||
.bind(pr.id)
|
||||
.bind(user_uid)
|
||||
.bind(state)
|
||||
.bind(params.body.as_deref())
|
||||
.bind(
|
||||
params
|
||||
.commit_sha
|
||||
.as_deref()
|
||||
.or(Some(pr.head_commit_sha.as_str())),
|
||||
)
|
||||
.bind(if state != "pending" { Some(now) } else { None })
|
||||
.bind(now)
|
||||
.fetch_one(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
if let Some(comments) = ¶ms.comments {
|
||||
for c in comments {
|
||||
let path = required_text(c.path.clone(), "path")?;
|
||||
let body = required_text(c.body.clone(), "body")?;
|
||||
sqlx::query(
|
||||
"INSERT INTO pr_review_comment (id, review_id, pull_request_id, author_id, body, path, \
|
||||
line, original_line, start_line, original_start_line, diff_hunk, in_reply_to_id, \
|
||||
edited_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NULL, NULL, $12, $12)",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(review_id).bind(pr.id).bind(user_uid)
|
||||
.bind(&body).bind(&path)
|
||||
.bind(c.line).bind(c.line)
|
||||
.bind(c.start_line).bind(c.start_line)
|
||||
.bind(c.diff_hunk.as_deref())
|
||||
.bind(now)
|
||||
.execute(&mut *txn).await.map_err(AppError::Database)?;
|
||||
}
|
||||
}
|
||||
|
||||
if matches!(state, "approved" | "changes_requested") {
|
||||
sqlx::query(
|
||||
"UPDATE pr_status SET approvals_count = (SELECT COUNT(*) FROM pr_review r \
|
||||
JOIN pull_request pr ON pr.id = r.pull_request_id \
|
||||
WHERE r.pull_request_id = $1 AND r.state = 'approved' AND r.dismissed_at IS NULL \
|
||||
AND r.submitted_at IS NOT NULL AND r.author_id <> pr.author_id), \
|
||||
updated_at = $2 WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(review)
|
||||
}
|
||||
|
||||
pub async fn pr_submit_review(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
review_id: Uuid,
|
||||
params: SubmitReviewParams,
|
||||
) -> Result<PrReview, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
|
||||
let state = params.state.as_str();
|
||||
if !["approved", "changes_requested", "commented"].contains(&state) {
|
||||
return Err(AppError::BadRequest("invalid review state".into()));
|
||||
}
|
||||
|
||||
if matches!(state, "approved" | "changes_requested") {
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Member)
|
||||
.await?;
|
||||
if state == "approved" && pr.author_id == user_uid {
|
||||
return Err(AppError::BadRequest(
|
||||
"PR authors cannot approve their own pull requests".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let now = 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 review = sqlx::query_as::<_, PrReview>(
|
||||
"UPDATE pr_review SET state = $1, body = COALESCE($2, body), submitted_at = $3, updated_at = $3 \
|
||||
WHERE id = $4 AND pull_request_id = $5 AND author_id = $6 AND submitted_at IS NULL AND dismissed_at IS NULL \
|
||||
RETURNING id, pull_request_id, author_id, state, body, commit_sha, \
|
||||
submitted_at, dismissed_at, dismissed_by, dismiss_reason, created_at, updated_at",
|
||||
)
|
||||
.bind(state).bind(params.body.as_deref()).bind(now)
|
||||
.bind(review_id).bind(pr.id).bind(user_uid)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("review not found or already submitted".into()))?;
|
||||
|
||||
if state == "approved" || state == "changes_requested" {
|
||||
sqlx::query(
|
||||
"UPDATE pr_status SET approvals_count = (SELECT COUNT(*) FROM pr_review r \
|
||||
JOIN pull_request pr ON pr.id = r.pull_request_id \
|
||||
WHERE r.pull_request_id = $1 AND r.state = 'approved' AND r.dismissed_at IS NULL \
|
||||
AND r.submitted_at IS NOT NULL AND r.author_id <> pr.author_id), \
|
||||
updated_at = $2 WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
}
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(review)
|
||||
}
|
||||
|
||||
pub async fn pr_dismiss_review(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
review_id: Uuid,
|
||||
params: DismissReviewParams,
|
||||
) -> Result<PrReview, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
self.ensure_repo_role_at_least(user_uid, &repo, Role::Admin)
|
||||
.await?;
|
||||
|
||||
let reason = required_text(params.reason, "reason")?;
|
||||
let now = 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 review = sqlx::query_as::<_, PrReview>(
|
||||
"UPDATE pr_review SET dismissed_at = $1, dismissed_by = $2, dismiss_reason = $3, updated_at = $1 \
|
||||
WHERE id = $4 AND pull_request_id = $5 AND submitted_at IS NOT NULL AND dismissed_at IS NULL \
|
||||
RETURNING id, pull_request_id, author_id, state, body, commit_sha, \
|
||||
submitted_at, dismissed_at, dismissed_by, dismiss_reason, created_at, updated_at",
|
||||
)
|
||||
.bind(now).bind(user_uid).bind(&reason)
|
||||
.bind(review_id).bind(pr.id)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("review not found or not submitted".into()))?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE pr_status SET approvals_count = (SELECT COUNT(*) FROM pr_review \
|
||||
WHERE pull_request_id = $1 AND state = 'approved' AND dismissed_at IS NULL), \
|
||||
updated_at = $2 WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.bind(now)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(review)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn pr_review_comments(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
review_id: Uuid,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrReviewComment>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrReviewComment>(
|
||||
"SELECT id, review_id, pull_request_id, author_id, body, path, line, original_line, \
|
||||
start_line, original_start_line, diff_hunk, in_reply_to_id, edited_at, created_at, updated_at \
|
||||
FROM pr_review_comment WHERE review_id = $1 AND pull_request_id = $2 ORDER BY created_at ASC LIMIT $3 OFFSET $4",
|
||||
)
|
||||
.bind(review_id).bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_add_review_reply(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
comment_id: Uuid,
|
||||
params: AddReplyParams,
|
||||
) -> Result<PrReviewComment, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
|
||||
let body = required_text(params.body, "body")?;
|
||||
let parent = sqlx::query_as::<_, PrReviewComment>(
|
||||
"SELECT id, review_id, pull_request_id, author_id, body, path, line, original_line, \
|
||||
start_line, original_start_line, diff_hunk, in_reply_to_id, edited_at, created_at, updated_at \
|
||||
FROM pr_review_comment WHERE id = $1 AND pull_request_id = $2",
|
||||
)
|
||||
.bind(comment_id).bind(pr.id)
|
||||
.fetch_optional(self.ctx.db.reader()).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("comment not found".into()))?;
|
||||
|
||||
let now = Utc::now();
|
||||
sqlx::query_as::<_, PrReviewComment>(
|
||||
"INSERT INTO pr_review_comment (id, review_id, pull_request_id, author_id, body, path, \
|
||||
line, original_line, start_line, original_start_line, diff_hunk, in_reply_to_id, \
|
||||
edited_at, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NULL, $13, $13) \
|
||||
RETURNING id, review_id, pull_request_id, author_id, body, path, line, original_line, \
|
||||
start_line, original_start_line, diff_hunk, in_reply_to_id, edited_at, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(parent.review_id).bind(pr.id).bind(user_uid)
|
||||
.bind(&body).bind(&parent.path)
|
||||
.bind(parent.line).bind(parent.original_line)
|
||||
.bind(parent.start_line).bind(parent.original_start_line)
|
||||
.bind(parent.diff_hunk.as_deref())
|
||||
.bind(comment_id).bind(now)
|
||||
.fetch_one(self.ctx.db.writer()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_update_review_comment(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
comment_id: Uuid,
|
||||
params: AddReplyParams,
|
||||
) -> Result<PrReviewComment, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
let body = required_text(params.body, "body")?;
|
||||
let now = Utc::now();
|
||||
sqlx::query_as::<_, PrReviewComment>(
|
||||
"UPDATE pr_review_comment SET body = $1, edited_at = $2, updated_at = $2 \
|
||||
WHERE id = $3 AND pull_request_id = $4 AND author_id = $5 \
|
||||
RETURNING id, review_id, pull_request_id, author_id, body, path, line, original_line, \
|
||||
start_line, original_start_line, diff_hunk, in_reply_to_id, edited_at, created_at, updated_at",
|
||||
)
|
||||
.bind(&body).bind(now).bind(comment_id).bind(pr.id).bind(user_uid)
|
||||
.fetch_optional(self.ctx.db.writer()).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("comment not found or not authored by you".into()))
|
||||
}
|
||||
|
||||
pub async fn pr_delete_review_comment(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
comment_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
let repo = self.resolve_repo(wk_name, repo_name).await?;
|
||||
|
||||
let comment = sqlx::query_as::<_, PrReviewComment>(
|
||||
"SELECT id, review_id, pull_request_id, author_id, body, path, line, original_line, \
|
||||
start_line, original_start_line, diff_hunk, in_reply_to_id, edited_at, created_at, updated_at \
|
||||
FROM pr_review_comment WHERE id = $1 AND pull_request_id = $2",
|
||||
)
|
||||
.bind(comment_id).bind(pr.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_repo_role_at_least(user_uid, &repo, Role::Admin)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let result = sqlx::query("DELETE FROM pr_review_comment WHERE id = $1")
|
||||
.bind(comment_id)
|
||||
.execute(self.ctx.db.writer())
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "comment not found")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use crate::error::AppError;
|
||||
use crate::models::prs::PrStatus;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_status(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
) -> Result<PrStatus, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
sqlx::query_as::<_, PrStatus>(
|
||||
"SELECT pull_request_id, head_commit_sha, checks_state, mergeable_state, conflicts, \
|
||||
approvals_count, requested_reviews_count, changed_files_count, additions_count, \
|
||||
deletions_count, updated_at \
|
||||
FROM pr_status WHERE pull_request_id = $1",
|
||||
)
|
||||
.bind(pr.id)
|
||||
.fetch_optional(self.ctx.db.reader())
|
||||
.await
|
||||
.map_err(AppError::Database)?
|
||||
.ok_or(AppError::NotFound("PR status not found".into()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::AppError;
|
||||
use crate::models::prs::PrSubscription;
|
||||
use crate::service::PrService;
|
||||
use crate::session::Session;
|
||||
|
||||
use super::util::{clamp_limit_offset, ensure_affected};
|
||||
|
||||
impl PrService {
|
||||
pub async fn pr_subscriptions(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Result<Vec<PrSubscription>, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let (limit, offset) = clamp_limit_offset(limit, offset);
|
||||
sqlx::query_as::<_, PrSubscription>(
|
||||
"SELECT id, pull_request_id, user_id, reason, muted, created_at, updated_at \
|
||||
FROM pr_subscription WHERE pull_request_id = $1 ORDER BY created_at ASC LIMIT $2 OFFSET $3",
|
||||
)
|
||||
.bind(pr.id).bind(limit).bind(offset)
|
||||
.fetch_all(self.ctx.db.reader()).await.map_err(AppError::Database)
|
||||
}
|
||||
|
||||
pub async fn pr_subscribe(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
) -> Result<PrSubscription, AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).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::<_, PrSubscription>(
|
||||
"INSERT INTO pr_subscription (id, pull_request_id, user_id, reason, muted, created_at, updated_at) \
|
||||
VALUES ($1, $2, $3, 'manual', false, $4, $4) ON CONFLICT (pull_request_id, user_id) DO NOTHING \
|
||||
RETURNING id, pull_request_id, user_id, reason, muted, created_at, updated_at",
|
||||
)
|
||||
.bind(Uuid::now_v7()).bind(pr.id).bind(user_uid).bind(now)
|
||||
.fetch_optional(&mut *txn).await.map_err(AppError::Database)?
|
||||
.ok_or(AppError::Conflict("already subscribed".into()))?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(sub)
|
||||
}
|
||||
|
||||
pub async fn pr_unsubscribe(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).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 pr_subscription WHERE pull_request_id = $1 AND user_id = $2")
|
||||
.bind(pr.id)
|
||||
.bind(user_uid)
|
||||
.execute(&mut *txn)
|
||||
.await
|
||||
.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not subscribed")?;
|
||||
|
||||
txn.commit().await.map_err(|_| AppError::TxnError)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn pr_mute(
|
||||
&self,
|
||||
ctx: &Session,
|
||||
wk_name: &str,
|
||||
repo_name: &str,
|
||||
number: i64,
|
||||
muted: bool,
|
||||
) -> Result<(), AppError> {
|
||||
let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
|
||||
let pr = self.resolve_pr(wk_name, repo_name, number).await?;
|
||||
self.ensure_pr_readable(user_uid, &pr).await?;
|
||||
let result = sqlx::query(
|
||||
"UPDATE pr_subscription SET muted = $1, updated_at = $2 WHERE pull_request_id = $3 AND user_id = $4",
|
||||
)
|
||||
.bind(muted).bind(chrono::Utc::now()).bind(pr.id).bind(user_uid)
|
||||
.execute(self.ctx.db.writer()).await.map_err(AppError::Database)?;
|
||||
ensure_affected(result.rows_affected(), "not subscribed")
|
||||
}
|
||||
}
|
||||
@@ -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