Files
kandev/apps/backend/internal/gitlab/controller_watches.go
T
João Salavisa dfaab11959 feat: full GitLab integration — parity with GitHub (#1120)
* feat(backend): full GitLab parity — store, service, poller, WS, presets

Add the watcher/poll/write-action surface on top of the existing GitLab
client + service skeleton:

* 5 new SQLite tables (mr_watches, review_watches, review_mr_tasks,
  issue_watches, issue_watch_tasks, action_presets) + CRUD
* Client + Service: MergeMR, GetProjectMergeMethods, GetProtectedBranch,
  ListUserProjects, SearchProjects, SetMRLabels, SetMRAssignees
* Service: review/issue/MR watch CRUD + Check/Trigger, GetStats,
  CleanupAllReview/IssueTasks (cleanup-policy aware), TriggerMRSync,
  action-presets CRUD with defaults
* Background poller (MR / review / issue loops) wired from main.go
* ~35 GitLab WS action constants + handlers.go registrations
* Mock controller for E2E seeding (MRs, issues, pipelines, discussions,
  approvals, branches)
* eventBus + taskDeleter + taskSessionChecker plumbed through Service
* Event types: GitLabMRFeedback / NewReviewMR / NewIssue / TaskMRUpdated

* feat(web): GitLab frontend parity — types, API, store slice, domain hooks

Extend the frontend GitLab integration on top of the new backend surface:

* HTTP API client expansion (gitlab-api.ts): full CRUD for review/issue/MR
  watches, MR write actions (merge/approve/labels/assignees), MR
  files/commits/feedback, action presets, projects autocomplete, stats
* Store slice expansion: review/issue/MR watches lists, action presets
  by workspace, stats + status with loading flags. Properties prefixed
  with gitlab to avoid collision with GitHub slice
* Domain hooks: use-gitlab-status, use-gitlab-stats,
  use-gitlab-review-watches, use-gitlab-issue-watches,
  use-gitlab-action-presets — mirror github hook shapes
* Type model: ReviewWatch, IssueWatch, MRWatch, ActionPresets, Stats,
  ProjectMergeMethods, MRApproval, Pipeline, MRFeedback, etc.
* Backend controller HTTP routes for watches/presets/write-actions/
  projects/stats so the frontend HTTP API client has endpoints to hit

All passes: backend (build + vet + lint + tests), web (typecheck + lint +
2400 tests).

* fix(gitlab): wire orchestrator event handlers, fix label-filter drop, add tests

Address Claude review blockers on the parity PR:

1. Wire orchestrator subscriptions for GitLab review/issue watch events.
   Add event_handlers_gitlab.go with handleGitLabNewReviewMR /
   handleGitLabNewIssue, dedup reservation handshake, and task-creator
   interfaces (mirrors event_handlers_github.go). main.go now calls
   orchestratorSvc.SetGitLabService so the dedup APIs are usable
2. Fix silent label-filter drop: when a custom_query is set on an issue
   watch, labels were being appended to the unused filter arg. Fold
   labels into customQuery (or default filter) so they actually reach
   GitLab; extracted appendLabelsToQuery helper with explicit handling
   of pre-existing labels= clauses
3. Switch event payloads to pointer types (mirrors GitHub) so
   handlers can type-assert pointer events
4. Backend tests: store_watches_test.go (CRUD + reserve/assign for all
   4 new tables + presets), service_watches_test.go (label-filter
   helper, cleanup policy, project normalisation), action_presets_test.go
5. Frontend slice tests: review/issue watch CRUD round-trips, action
   presets + stats reducer coverage

All green: backend (build+vet+lint+tests), web (typecheck+lint+2403 tests).

* fix(gitlab): address remaining blockers — cleanup wiring, safe defaults, nil guards

Address the second round of Claude review blockers:

1. main.go: wire SetTaskDeleter + SetTaskSessionChecker on services.GitLab
   (mirrors GitHub). Without these, manual cleanup sweeps would always
   error with "task deleter not configured"
2. service_cleanup.go: default cleanup policy on transient DB error is now
   CleanupPolicyNever (preserve tasks) instead of CleanupPolicyAuto
   (silently delete). Genuine "watch was deleted" path also falls under
   the safe-side default; user can manually delete the orphan tasks
3. service_watches.go: add nil guards on requireStore() so the 6 MR-watch
   list/get/delete methods return an errStoreUnavailable error instead
   of panicking when the SQLite store failed to construct at boot
4. use-gitlab-status.ts + use-gitlab-stats.ts: add per-mount attemptedRef
   so an unreachable GitLab doesn't trigger an infinite re-fetch loop —
   the previous useEffect re-ran every render because the failure path
   left status null, satisfying the !status guard

* fix(gitlab): propagate session-check errors, clamp poll interval on update

Address remaining Claude blockers:

* service_cleanup.go: HasUserAuthoredMessage transient errors are now
  preserved (return false → skip delete) instead of silently ignored;
  the alternative was occasionally deleting tasks a user had touched
* service_watches.go: extract clampPollInterval helper applying the same
  bounds (0 → default, <60 → 60) as the create path; both
  applyReviewWatchPatch and applyIssueWatchPatch use it so user-supplied
  zero or tiny values via UpdateXxxWatchRequest no longer hammer GitLab

* fix(gitlab): clear dupl lint, fix preset retry loop + per-workspace watch cache

* service_watches.go: applyReviewWatchPatch / applyIssueWatchPatch get
  nolint:dupl markers — they share shape but per-domain field validation
  lives in the create paths, so deduplicating via generics would obscure
  the contract. Restores backend lint to 0 issues
* use-gitlab-action-presets.ts: per-workspace attemptedRef set so a
  failing preset fetch doesn't retry on every render
* use-gitlab-review-watches.ts + use-gitlab-issue-watches.ts: track
  lastFetchedRef per consumer so a workspace switch triggers a refetch.
  The slice-level loaded flag is shared across instances and can't
  double as a per-workspace cache key

* fix(gitlab): add nil-store guards across review/issue watch + cleanup paths

Round-3 Claude finding: ReviewWatch / IssueWatch / preset / reservation
methods still called s.requireStore().X() directly. If NewStore fails at
boot (table migration error), the service struct's store is nil and every
list/get/update/create/reserve method panics on first request.

Apply the same store-nil → errStoreUnavailable pattern from f95a929 to
every remaining method:
* CreateReviewWatch / CreateIssueWatch
* GetReviewWatch / ListReviewWatches / ListAllReviewWatches /
  UpdateReviewWatch / TriggerReviewWatchAll
* GetIssueWatch / ListIssueWatches / ListAllIssueWatches /
  UpdateIssueWatch / TriggerIssueWatchAll
* ReserveReviewMRTask / AssignReviewMRTaskID / ReleaseReviewMRTask
* ReserveIssueWatchTask / AssignIssueWatchTaskID / ReleaseIssueWatchTask
* lookupReviewPolicy / lookupIssuePolicy (return CleanupPolicyNever)

* fix(gitlab): nil-store guards on CheckXxxWatch + DeleteXxxWatch + cleanup paths

Round-4 Claude finding: 4 remaining panic sites the previous nil-guard
pass missed — these run from the background poller (every 5 min) and the
manual delete/cleanup flows, so a boot-time NewStore failure would
crash the orchestrator process on first tick.

* service_watches.go: add store-nil guards to DeleteReviewWatch /
  DeleteIssueWatch / CheckReviewWatch / CheckIssueWatch
* service_cleanup.go: guard CleanupAllReviewTasks / CleanupAllIssueTasks
  entry points; wrap the trailing DeleteReviewMRTask / DeleteIssueWatchTask
  calls in `if store := s.requireStore(); store != nil` blocks so the
  cleanup succeeds even when the dedup-row delete is unreachable

* refactor(gitlab): split service_watches.go to stay under 800-line revive limit

CI's --new-from-rev lint caught service_watches.go at 808 lines (limit
800). Split into three focused files:

* service_events.go (94 LOC) — publish helpers for MR feedback /
  new review MR / new issue / watch lifecycle events
* service_issue_watches.go (302 LOC) — Issue watch CRUD + Check +
  Trigger + fetch + helpers
* service_reservations.go (59 LOC) — Reserve/Assign/Release dedup
  handles used by the orchestrator event handlers

service_watches.go is now 505 lines and contains MR watch + Review
watch only. No behavioral change.

* fix(gitlab): address inline code-review feedback

Address actionable inline comments from Claude/CodeRabbit/cubic/Greptile:

* appendLabelsToQuery: use url.ParseQuery for exact key match instead
  of strings.Contains; previously false-matched keys like mylabels=
  and silently dropped the watch's labels (test added)
* fetchReviewMRs: drop dead `filter = watch.CustomQuery` assignment —
  SearchMRs's buildMRSearchQuery returns customQuery verbatim and
  ignores filter when customQuery is non-empty
* store.go: add workspace_id indexes on gitlab_review_watches and
  gitlab_issue_watches (the 5-min poller and HTTP list endpoints did
  full table scans)
* mock_client.SearchProjects: switch from == to case-insensitive
  Contains so partial-query autocomplete returns the seeded project,
  matching the doc comment
* Poller: add sync.Mutex to guard `started` field; Start/Stop are
  now safe to call concurrently (go test -race would have flagged
  the previous read/write race)
* Add ErrWatchNotFound sentinel; controller_watches.go maps it to
  HTTP 404 via httpRespondError helper. Update/Trigger handlers
  previously returned 500 for missing watches, hiding the distinction
  from real server faults
* service_events.go: log Publish errors on watch lifecycle events
  instead of swallowing them silently
* handlers.go: reject malformed JSON payloads in list-style WS
  handlers rather than silently falling through to broader
  list/search behavior
* event_handlers_gitlab.go: remove dead gitlabRepoSlug helper +
  blank-identifier suppression

* ci: re-trigger to clear flaky E2E shard 3

* fix(gitlab): address final review round — nil guards, store merge, logs, body validation

- CheckMRWatch, UpdateReviewWatch, UpdateIssueWatch: nil guards for store/req
- handlers: wsNewDiscussionNote rejects empty body
- action_presets: Update reads raw stored row (no default freezing);
  Reset validates workspace_id
- service_search.GetStats: log Warn per sub-call failure before zero
- event_handlers_gitlab: log Release* dedup-row errors with context
- web/store.ts: post-slice merge restores every GitLab sub-state field;
  extract buildStateOverrides helper
- web/default-state.ts: add GitLab fields to defaultState +
  mergeInitialState via mergeGitLabFields helper
- web/gitlab-api.ts: UpdateXxxWatchRequest now Omit workspace_id

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-02 22:10:07 +01:00

522 lines
16 KiB
Go

package gitlab
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
)
// httpRespondError maps known sentinel errors to their HTTP code and
// writes a JSON {"error": "..."} body. Returns true when a response was
// written so callers can early-return.
func httpRespondError(ctx *gin.Context, err error) bool {
if err == nil {
return false
}
switch {
case errors.Is(err, ErrWatchNotFound):
ctx.JSON(http.StatusNotFound, gin.H{responseErrorKey: err.Error()})
default:
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
}
return true
}
// RegisterWatchHTTPRoutes wires the watch + presets + write-action HTTP
// surface on top of the v1 routes. Called from RegisterHTTPRoutes after the
// base set is registered.
func (c *Controller) RegisterWatchHTTPRoutes(router *gin.Engine) {
api := router.Group("/api/v1/gitlab")
// MR / Review / Issue watches
api.GET("/watches/mr", c.httpListMRWatches)
api.DELETE("/watches/mr/:id", c.httpDeleteMRWatch)
api.GET("/watches/review", c.httpListReviewWatches)
api.POST("/watches/review", c.httpCreateReviewWatch)
api.PUT("/watches/review/:id", c.httpUpdateReviewWatch)
api.DELETE("/watches/review/:id", c.httpDeleteReviewWatch)
api.POST("/watches/review/:id/trigger", c.httpTriggerReviewWatch)
api.POST("/watches/review/trigger-all", c.httpTriggerAllReviewChecks)
api.GET("/watches/issue", c.httpListIssueWatches)
api.POST("/watches/issue", c.httpCreateIssueWatch)
api.PUT("/watches/issue/:id", c.httpUpdateIssueWatch)
api.DELETE("/watches/issue/:id", c.httpDeleteIssueWatch)
api.POST("/watches/issue/:id/trigger", c.httpTriggerIssueWatch)
api.POST("/watches/issue/trigger-all", c.httpTriggerAllIssueChecks)
// Cleanup
api.POST("/cleanup/review-tasks", c.httpCleanupReviewTasks)
api.POST("/cleanup/issue-tasks", c.httpCleanupIssueTasks)
// Projects + branches autocomplete
api.GET("/projects", c.httpListUserProjects)
api.GET("/projects/search", c.httpSearchProjects)
api.GET("/projects/branches", c.httpListProjectBranches)
api.GET("/projects/merge-methods", c.httpGetProjectMergeMethods)
// MR write actions
api.PUT("/mrs/merge", c.httpMergeMR)
api.POST("/mrs/approve", c.httpApproveMR)
api.POST("/mrs/unapprove", c.httpUnapproveMR)
api.PUT("/mrs/labels", c.httpSetMRLabels)
api.PUT("/mrs/assignees", c.httpSetMRAssignees)
api.GET("/mrs/files", c.httpGetMRFiles)
api.GET("/mrs/commits", c.httpGetMRCommits)
// Action presets
api.GET("/action-presets", c.httpGetActionPresets)
api.PUT("/action-presets", c.httpUpdateActionPresets)
api.POST("/action-presets/reset", c.httpResetActionPresets)
// Stats
api.GET("/stats", c.httpGetStats)
}
// --- Helpers ---
func bindJSON[T any](ctx *gin.Context, out *T) bool {
if err := ctx.ShouldBindJSON(out); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: errors.New("invalid payload").Error()})
return false
}
return true
}
// --- MR watches ---
func (c *Controller) httpListMRWatches(ctx *gin.Context) {
sessionID := ctx.Query("session_id")
taskID := ctx.Query("task_id")
switch {
case sessionID != "":
watches, err := c.service.ListMRWatchesBySession(ctx.Request.Context(), sessionID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"watches": watches})
case taskID != "":
watches, err := c.service.ListMRWatchesByTask(ctx.Request.Context(), taskID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"watches": watches})
default:
watches, err := c.service.ListActiveMRWatches(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"watches": watches})
}
}
func (c *Controller) httpDeleteMRWatch(ctx *gin.Context) {
id := ctx.Param("id")
if err := c.service.DeleteMRWatch(ctx.Request.Context(), id); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": true})
}
// --- Review watches ---
func (c *Controller) httpListReviewWatches(ctx *gin.Context) {
wsID := ctx.Query("workspace_id")
var (
watches []*ReviewWatch
err error
)
if wsID == "" {
watches, err = c.service.ListAllReviewWatches(ctx.Request.Context())
} else {
watches, err = c.service.ListReviewWatches(ctx.Request.Context(), wsID)
}
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"watches": watches})
}
func (c *Controller) httpCreateReviewWatch(ctx *gin.Context) {
var req CreateReviewWatchRequest
if !bindJSON(ctx, &req) {
return
}
rw, err := c.service.CreateReviewWatch(ctx.Request.Context(), &req)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, rw)
}
func (c *Controller) httpUpdateReviewWatch(ctx *gin.Context) {
id := ctx.Param("id")
var req UpdateReviewWatchRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.UpdateReviewWatch(ctx.Request.Context(), id, &req); httpRespondError(ctx, err) {
return
}
rw, err := c.service.GetReviewWatch(ctx.Request.Context(), id)
if err != nil || rw == nil {
ctx.JSON(http.StatusOK, gin.H{"updated": true})
return
}
ctx.JSON(http.StatusOK, rw)
}
func (c *Controller) httpDeleteReviewWatch(ctx *gin.Context) {
id := ctx.Param("id")
if err := c.service.DeleteReviewWatch(ctx.Request.Context(), id); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": true})
}
func (c *Controller) httpTriggerReviewWatch(ctx *gin.Context) {
id := ctx.Param("id")
mrs, err := c.service.TriggerReviewWatch(ctx.Request.Context(), id)
if httpRespondError(ctx, err) {
return
}
ctx.JSON(http.StatusOK, gin.H{"mrs": mrs, "count": len(mrs)})
}
func (c *Controller) httpTriggerAllReviewChecks(ctx *gin.Context) {
n, err := c.service.TriggerReviewWatchAll(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"count": n})
}
// --- Issue watches ---
func (c *Controller) httpListIssueWatches(ctx *gin.Context) {
wsID := ctx.Query("workspace_id")
var (
watches []*IssueWatch
err error
)
if wsID == "" {
watches, err = c.service.ListAllIssueWatches(ctx.Request.Context())
} else {
watches, err = c.service.ListIssueWatches(ctx.Request.Context(), wsID)
}
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"watches": watches})
}
func (c *Controller) httpCreateIssueWatch(ctx *gin.Context) {
var req CreateIssueWatchRequest
if !bindJSON(ctx, &req) {
return
}
iw, err := c.service.CreateIssueWatch(ctx.Request.Context(), &req)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, iw)
}
func (c *Controller) httpUpdateIssueWatch(ctx *gin.Context) {
id := ctx.Param("id")
var req UpdateIssueWatchRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.UpdateIssueWatch(ctx.Request.Context(), id, &req); httpRespondError(ctx, err) {
return
}
iw, err := c.service.GetIssueWatch(ctx.Request.Context(), id)
if err != nil || iw == nil {
ctx.JSON(http.StatusOK, gin.H{"updated": true})
return
}
ctx.JSON(http.StatusOK, iw)
}
func (c *Controller) httpDeleteIssueWatch(ctx *gin.Context) {
id := ctx.Param("id")
if err := c.service.DeleteIssueWatch(ctx.Request.Context(), id); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": true})
}
func (c *Controller) httpTriggerIssueWatch(ctx *gin.Context) {
id := ctx.Param("id")
issues, err := c.service.TriggerIssueWatch(ctx.Request.Context(), id)
if httpRespondError(ctx, err) {
return
}
ctx.JSON(http.StatusOK, gin.H{"issues": issues, "count": len(issues)})
}
func (c *Controller) httpTriggerAllIssueChecks(ctx *gin.Context) {
n, err := c.service.TriggerIssueWatchAll(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"count": n})
}
// --- Cleanup ---
func (c *Controller) httpCleanupReviewTasks(ctx *gin.Context) {
n, err := c.service.CleanupAllReviewTasks(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": n})
}
func (c *Controller) httpCleanupIssueTasks(ctx *gin.Context) {
n, err := c.service.CleanupAllIssueTasks(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"deleted": n})
}
// --- Projects ---
func (c *Controller) httpListUserProjects(ctx *gin.Context) {
projects, err := c.service.ListUserProjects(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"projects": projects})
}
func (c *Controller) httpSearchProjects(ctx *gin.Context) {
query := ctx.Query("query")
projects, err := c.service.SearchProjects(ctx.Request.Context(), query, 50)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"projects": projects})
}
func (c *Controller) httpListProjectBranches(ctx *gin.Context) {
project := ctx.Query("project")
if project == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "project required"})
return
}
branches, err := c.service.ListProjectBranches(ctx.Request.Context(), project)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"branches": branches})
}
func (c *Controller) httpGetProjectMergeMethods(ctx *gin.Context) {
project := ctx.Query("project")
if project == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "project required"})
return
}
methods, err := c.service.GetProjectMergeMethods(ctx.Request.Context(), project)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, methods)
}
// --- Write actions ---
type mergeMRRequest struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
Method string `json:"method"`
SquashCommitMessage string `json:"squash_commit_message"`
}
func (c *Controller) httpMergeMR(ctx *gin.Context) {
var req mergeMRRequest
if !bindJSON(ctx, &req) {
return
}
mr, err := c.service.MergeMR(ctx.Request.Context(), req.Project, req.IID, req.Method, req.SquashCommitMessage)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, mr)
}
type approveMRRequest struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
}
func (c *Controller) httpApproveMR(ctx *gin.Context) {
var req approveMRRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.SubmitMRApproval(ctx.Request.Context(), req.Project, req.IID); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"approved": true})
}
func (c *Controller) httpUnapproveMR(ctx *gin.Context) {
var req approveMRRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.SubmitMRUnapproval(ctx.Request.Context(), req.Project, req.IID); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"unapproved": true})
}
type setMRLabelsRequest struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
Labels []string `json:"labels"`
}
func (c *Controller) httpSetMRLabels(ctx *gin.Context) {
var req setMRLabelsRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.SetMRLabels(ctx.Request.Context(), req.Project, req.IID, req.Labels); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"updated": true})
}
type setMRAssigneesRequest struct {
Project string `json:"project" binding:"required"`
IID int `json:"iid" binding:"required"`
AssigneeIDs []int `json:"assignee_ids"`
}
func (c *Controller) httpSetMRAssignees(ctx *gin.Context) {
var req setMRAssigneesRequest
if !bindJSON(ctx, &req) {
return
}
if err := c.service.SetMRAssignees(ctx.Request.Context(), req.Project, req.IID, req.AssigneeIDs); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"updated": true})
}
func (c *Controller) httpGetMRFiles(ctx *gin.Context) {
project, iid, err := parseProjectAndIID(ctx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
return
}
files, err := c.service.GetMRFiles(ctx.Request.Context(), project, iid)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"files": files})
}
func (c *Controller) httpGetMRCommits(ctx *gin.Context) {
project, iid, err := parseProjectAndIID(ctx)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: err.Error()})
return
}
commits, err := c.service.GetMRCommits(ctx.Request.Context(), project, iid)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"commits": commits})
}
// --- Action presets ---
func (c *Controller) httpGetActionPresets(ctx *gin.Context) {
wsID := ctx.Query("workspace_id")
if wsID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "workspace_id required"})
return
}
presets, err := c.service.GetActionPresetsOrDefault(ctx.Request.Context(), wsID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, presets)
}
func (c *Controller) httpUpdateActionPresets(ctx *gin.Context) {
var req UpdateActionPresetsRequest
if !bindJSON(ctx, &req) {
return
}
if req.WorkspaceID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "workspace_id required"})
return
}
presets, err := c.service.UpdateActionPresets(ctx.Request.Context(), &req)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, presets)
}
func (c *Controller) httpResetActionPresets(ctx *gin.Context) {
wsID := ctx.Query("workspace_id")
if wsID == "" {
ctx.JSON(http.StatusBadRequest, gin.H{responseErrorKey: "workspace_id required"})
return
}
presets, err := c.service.ResetActionPresets(ctx.Request.Context(), wsID)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, presets)
}
// --- Stats ---
func (c *Controller) httpGetStats(ctx *gin.Context) {
stats, err := c.service.GetStats(ctx.Request.Context())
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{responseErrorKey: err.Error()})
return
}
ctx.JSON(http.StatusOK, stats)
}