e740417885
* feat(linear): enrich issue watch filters with priority, labels, creator, estimate Adds priority, labels (multi-select), creator (team member select), and estimate range filters to Linear issue watchers — closing the gap with Linear's GraphQL filter surface so users can scope auto-run watchers nearly as tightly as they would in Linear itself. - Backend: extend SearchFilter, map new fields to IssueFilter, add ListLabels / ListUsers on the Client interface, expose them over HTTP (GET /api/v1/linear/labels, /users) and via SearchIssues query params. - Frontend: extend LinearSearchFilter, fetch labels + users per team, render new filter controls in the watcher dialog, and split helpers into linear-issue-watch-form.ts + linear-issue-watch-fields.tsx so the dialog stays under file/function size limits. * fix(linear): address reviewer feedback on enriched filter PR - Reject invalid priority / malformed estimate query params with 400 instead of silently dropping them; reject estimateMin > estimateMax. Mirror the bounds check in the issue-watch validator so JSON-encoded watches go through the same gate. - A11y: render label/state toggle Badges inside <button aria-pressed> so keyboard users can navigate and screen readers can announce state. - Recover from per-team fetch failures so a transient network blip doesn't permanently mark a team as "fetched-empty" — clear the in-flight marker when any of states/labels/users fail, allowing remount to retry. - Tighten priority typing: LinearSearchFilter.priority is 0|1|2|3|4, and LinearPriority is the source of truth on the form-state side. Promote FormState from a type alias to an interface per repo convention. * fix(linear): align update error message and clear fetchedTeams on cancel - UpdateIssueWatch's filter-empty error still listed only the original four fields; bring it in line with the create path so the message matches what filterIsEmpty actually accepts. - linear-issue-watch-fields: clear the fetchedTeams marker on effect cancellation as well as failure, so a remount after a fast teamKey switch can retry instead of being stuck with whatever partial cache the prior effect produced. * fix(linear): address PR #974 reviewer findings - linear-issue-watch-fields: delete the fetchedTeams marker on effect cleanup so rapid team switches (A → B → A) refetch on return instead of being stranded mid-load. Capture the Set in a local so the cleanup closure references the exact instance the effect body added to. - graphql_client: raise the labels/users page cap from 100 to Linear's max of 250 via a shared linearMaxPageSize constant and a $first variable. Documented that a workspace exceeding that would need cursor-pagination here AND lazy-load in the UI. - service_issue_watch.validateFilterBounds + handlers parseSearchNumeric Filters: reject negative estimate values — Linear story points are non-negative, so a -1 would silently match nothing. * fix(linear): collapse duplicate hint text on States/Labels rows When no team was selected the row showed two stacked muted lines — the field description and the multi-select's "Pick a team…" prose — saying overlapping things. Swap the row description based on team selection and let the multi-select render nothing when disabled, so exactly one line is shown in either state. Also tightens the new fields' descriptions to match the brevity of the existing ones (Labels, Estimate min/max). * fix(linear): reject NaN/Inf estimates and preserve team cache after success CodeRabbit + cubic flagged two real issues in the previous round: - strconv.ParseFloat accepts "NaN" / "+Inf" / "-Inf" without erroring, and "f < 0" passes through for NaN. Without an explicit math.IsNaN / math.IsInf guard those values would propagate into the GraphQL request and the eventual json.Marshal would 500 instead of 400. Add the guard for both estimate_min and estimate_max, with a regression test covering NaN, ±Inf, negative, and inverted range. - useTeamsAndStates was deleting the per-team cache marker on every cleanup, so a normal team switch evicted a healthy cache and the next visit re-fetched all three datasets. Track a "loaded" flag and only evict on cleanup when the fetch didn't complete successfully. Also extracts the duplicated "team_key" / "team_key required" wire strings into package-level constants per the repo's "3+ occurrences → constant" convention. * test(linear): add handler tests for /labels and /users endpoints Mirrors the existing TestHTTPListStates_* pair — required team_key returns 400, and a happy path that asserts the team_key reaches the client and the response is 200. Closes the coverage gap CodeRabbit flagged on the two new endpoints introduced in this PR. * feat(linear): make priority filter multi-select Status and label filters are already multi-select; priority being a single Select broke the symmetry and forced single-value thinking. Linear's own filter UI is multi-select per priority, and the GraphQL filter takes priority: { in: [...] } natively, so the wire change is clean. Backend - SearchFilter.Priority *int → Priorities []int - buildIssueFilter emits priority: { in: priorities } when non-empty - validateFilterBounds checks each element ∈ [0,4] - normalizeFilter de-dupes (preserves caller order) - HTTP query param priority → priorities, parsed as CSV - Tests updated, including priority=0 still expressible as Priorities=[0] (matches "No priority" issues only) Frontend - LinearSearchFilter.priority → priorities: LinearPriority[] - FormState.priority → priorities - PRIORITY_OPTIONS dropped the (any) sentinel; "No priority" sits at the end of the chip row - PriorityMultiSelect added next to State/Label multi-selects - Priority moved to its own full-width row matching States/Labels; Creator promoted to a stand-alone CreatorRow Refactor - searchLinearIssues query-param building extracted to a flat table-driven helper to keep cyclomatic complexity ≤ 15 * refactor(linear): regroup watcher dialog fields and add section separators UX pass on the watcher dialog: - Pulled Team out into its own full-width row and paired Assignee + Creator in a 2-col row so the people filters sit together — the old Team+Assignee pairing forced a context switch between scope and people filters mid-form. - Added hairlines between the four conceptual blocks (Destination / Filter / Automation / Prompt / Settings). Each block answers a different question, so a consistent rhythm helps users scan the form by section instead of reading one long stack. No behaviour change; pure layout. * refactor(linear): use shared Separator for watcher dialog section breaks Initially extracted a local SectionDivider, but @kandev/ui/separator (Radix-based, shadcn) already exists and is used in 14 places across the codebase — including the sibling Jira settings page. Use that instead so the styling tracks the rest of the app. * refactor(linear): split parseSearchNumericFilters to satisfy cyclop Extract priority and estimate-bound parsing into helpers so the entry point drops below the project's max cyclomatic complexity (15). * fix(linear): reject non-finite/negative estimates and align fmt - validateFilterBounds rejects NaN/+-Inf in addition to negatives, so a watch config can't be persisted with values that would later crash json.Marshal. Adds focused unit tests. - parseEstimate on the frontend treats negatives as unset so the UI cannot submit estimateMin/Max < 0. - gofmt-only alignment tweak in handlers_test.go test table.
665 lines
19 KiB
Go
665 lines
19 KiB
Go
package linear
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// LinearAPIEndpoint is the single GraphQL endpoint exposed by Linear. There is
|
|
// no per-organization host: auth scopes the request to the right workspace.
|
|
const LinearAPIEndpoint = "https://api.linear.app/graphql"
|
|
|
|
// GraphQLClient talks to Linear's GraphQL API using a Personal API Key. The
|
|
// client holds no state beyond the credential so it can be recreated cheaply
|
|
// per workspace if config changes.
|
|
type GraphQLClient struct {
|
|
http *http.Client
|
|
endpoint string
|
|
apiKey string
|
|
maxBodySize int64
|
|
}
|
|
|
|
// NewGraphQLClient builds a client from a LinearConfig + secret.
|
|
func NewGraphQLClient(_ *LinearConfig, secret string) *GraphQLClient {
|
|
return &GraphQLClient{
|
|
http: &http.Client{
|
|
Timeout: 30 * time.Second,
|
|
},
|
|
endpoint: LinearAPIEndpoint,
|
|
apiKey: secret,
|
|
maxBodySize: 4 << 20, // 4 MB — Linear payloads are small by design.
|
|
}
|
|
}
|
|
|
|
const userAgent = "kandev/1.0 (+https://github.com/kdlbs/kandev)"
|
|
|
|
// graphqlRequest is the standard {query, variables} envelope.
|
|
type graphqlRequest struct {
|
|
Query string `json:"query"`
|
|
Variables map[string]interface{} `json:"variables,omitempty"`
|
|
}
|
|
|
|
// graphqlError captures one entry from the GraphQL `errors` array.
|
|
type graphqlError struct {
|
|
Message string `json:"message"`
|
|
Path []interface{} `json:"path,omitempty"`
|
|
Extensions map[string]interface{} `json:"extensions,omitempty"`
|
|
}
|
|
|
|
// graphqlResponse is the raw envelope; `Data` is decoded into the caller's
|
|
// struct via a second pass to avoid generics.
|
|
type graphqlResponse struct {
|
|
Data json.RawMessage `json:"data"`
|
|
Errors []graphqlError `json:"errors,omitempty"`
|
|
}
|
|
|
|
// do executes a GraphQL operation and decodes `data` into out (may be nil).
|
|
// Non-2xx responses and GraphQL-level errors both surface as *APIError so
|
|
// callers can switch on status. Linear returns 4xx for auth failures and 200
|
|
// with errors[] for everything else.
|
|
func (c *GraphQLClient) do(ctx context.Context, query string, variables map[string]interface{}, out interface{}) error {
|
|
body, err := json.Marshal(graphqlRequest{Query: query, Variables: variables})
|
|
if err != nil {
|
|
return fmt.Errorf("marshal request: %w", err)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
req.Header.Set("User-Agent", userAgent)
|
|
// Linear accepts the API key directly as the Authorization header value.
|
|
req.Header.Set("Authorization", c.apiKey)
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
raw, err := io.ReadAll(io.LimitReader(resp.Body, c.maxBodySize))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return &APIError{StatusCode: resp.StatusCode, Message: summarizeBody(raw)}
|
|
}
|
|
var env graphqlResponse
|
|
if err := json.Unmarshal(raw, &env); err != nil {
|
|
return &APIError{StatusCode: resp.StatusCode, Message: "invalid GraphQL response: " + err.Error()}
|
|
}
|
|
if len(env.Errors) > 0 {
|
|
return &APIError{StatusCode: graphqlErrorStatus(env.Errors), Message: joinGraphQLErrors(env.Errors)}
|
|
}
|
|
if out == nil || len(env.Data) == 0 {
|
|
return nil
|
|
}
|
|
return json.Unmarshal(env.Data, out)
|
|
}
|
|
|
|
// graphqlErrorStatus maps a GraphQL error envelope to an HTTP-like status. Auth
|
|
// failures get 401 so the UI can surface them as "credentials invalid";
|
|
// everything else falls back to 400 (request-level failure rather than server).
|
|
func graphqlErrorStatus(errs []graphqlError) int {
|
|
for _, e := range errs {
|
|
if e.Extensions == nil {
|
|
continue
|
|
}
|
|
if t, ok := e.Extensions["type"].(string); ok {
|
|
switch strings.ToLower(t) {
|
|
case "authentication error", "authentication", "unauthenticated":
|
|
return http.StatusUnauthorized
|
|
case "feature not access", "permission", "forbidden":
|
|
return http.StatusForbidden
|
|
case "invalid input":
|
|
return http.StatusBadRequest
|
|
}
|
|
}
|
|
}
|
|
return http.StatusBadRequest
|
|
}
|
|
|
|
func joinGraphQLErrors(errs []graphqlError) string {
|
|
if len(errs) == 1 {
|
|
return errs[0].Message
|
|
}
|
|
parts := make([]string, 0, len(errs))
|
|
for _, e := range errs {
|
|
parts = append(parts, e.Message)
|
|
}
|
|
return strings.Join(parts, "; ")
|
|
}
|
|
|
|
// summarizeBody trims an error body to a useful length for log/error messages.
|
|
func summarizeBody(raw []byte) string {
|
|
const maxMsg = 500
|
|
s := strings.TrimSpace(string(raw))
|
|
if len(s) > maxMsg {
|
|
return s[:maxMsg] + "…"
|
|
}
|
|
if s == "" {
|
|
return "(empty body)"
|
|
}
|
|
return s
|
|
}
|
|
|
|
// --- viewer / TestAuth ---
|
|
|
|
const viewerQuery = `
|
|
query Viewer {
|
|
viewer {
|
|
id
|
|
name
|
|
displayName
|
|
email
|
|
}
|
|
organization {
|
|
urlKey
|
|
name
|
|
}
|
|
}`
|
|
|
|
type viewerData struct {
|
|
Viewer struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"displayName"`
|
|
Email string `json:"email"`
|
|
} `json:"viewer"`
|
|
Organization struct {
|
|
URLKey string `json:"urlKey"`
|
|
Name string `json:"name"`
|
|
} `json:"organization"`
|
|
}
|
|
|
|
// TestAuth hits the viewer query — the cheapest authenticated query Linear
|
|
// exposes — and returns a structured result so the UI can render a meaningful
|
|
// failure inline.
|
|
func (c *GraphQLClient) TestAuth(ctx context.Context) (*TestConnectionResult, error) {
|
|
var data viewerData
|
|
if err := c.do(ctx, viewerQuery, nil, &data); err != nil {
|
|
var apiErr *APIError
|
|
if errors.As(err, &apiErr) {
|
|
return &TestConnectionResult{OK: false, Error: apiErr.Error()}, nil
|
|
}
|
|
return &TestConnectionResult{OK: false, Error: err.Error()}, nil
|
|
}
|
|
name := data.Viewer.DisplayName
|
|
if name == "" {
|
|
name = data.Viewer.Name
|
|
}
|
|
return &TestConnectionResult{
|
|
OK: true,
|
|
UserID: data.Viewer.ID,
|
|
DisplayName: name,
|
|
Email: data.Viewer.Email,
|
|
OrgSlug: data.Organization.URLKey,
|
|
OrgName: data.Organization.Name,
|
|
}, nil
|
|
}
|
|
|
|
// --- teams ---
|
|
|
|
const teamsQuery = `
|
|
query Teams {
|
|
teams(first: 100, orderBy: updatedAt) {
|
|
nodes { id key name }
|
|
}
|
|
}`
|
|
|
|
type teamsData struct {
|
|
Teams struct {
|
|
Nodes []struct {
|
|
ID string `json:"id"`
|
|
Key string `json:"key"`
|
|
Name string `json:"name"`
|
|
} `json:"nodes"`
|
|
} `json:"teams"`
|
|
}
|
|
|
|
// ListTeams returns up to 100 teams (Linear's max page size). Fine for the
|
|
// settings dropdown; pagination can be added later if needed.
|
|
func (c *GraphQLClient) ListTeams(ctx context.Context) ([]LinearTeam, error) {
|
|
var data teamsData
|
|
if err := c.do(ctx, teamsQuery, nil, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]LinearTeam, 0, len(data.Teams.Nodes))
|
|
for _, t := range data.Teams.Nodes {
|
|
out = append(out, LinearTeam{ID: t.ID, Key: t.Key, Name: t.Name})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// --- workflow states ---
|
|
|
|
const teamStatesQuery = `
|
|
query TeamStates($filter: WorkflowStateFilter!) {
|
|
workflowStates(first: 100, filter: $filter) {
|
|
nodes { id name type color position }
|
|
}
|
|
}`
|
|
|
|
type statesData struct {
|
|
WorkflowStates struct {
|
|
Nodes []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Color string `json:"color"`
|
|
Position float64 `json:"position"`
|
|
} `json:"nodes"`
|
|
} `json:"workflowStates"`
|
|
}
|
|
|
|
// ListStates returns the workflow states for a team identified by its key.
|
|
// Equivalent of Jira's "ListTransitions" but unconditional — the same set of
|
|
// states is available regardless of the issue's current state.
|
|
func (c *GraphQLClient) ListStates(ctx context.Context, teamKey string) ([]LinearWorkflowState, error) {
|
|
if teamKey == "" {
|
|
return nil, fmt.Errorf("teamKey required")
|
|
}
|
|
vars := map[string]interface{}{
|
|
"filter": map[string]interface{}{
|
|
"team": map[string]interface{}{"key": map[string]interface{}{"eq": teamKey}},
|
|
},
|
|
}
|
|
var data statesData
|
|
if err := c.do(ctx, teamStatesQuery, vars, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]LinearWorkflowState, 0, len(data.WorkflowStates.Nodes))
|
|
for _, s := range data.WorkflowStates.Nodes {
|
|
out = append(out, LinearWorkflowState{
|
|
ID: s.ID,
|
|
Name: s.Name,
|
|
Type: s.Type,
|
|
// Linear uses fractional indexing for state ordering — round
|
|
// rather than truncate so adjacent fractional positions don't
|
|
// collapse onto the same int.
|
|
Color: s.Color,
|
|
Position: int(math.Round(s.Position)),
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// --- issues ---
|
|
|
|
// issueFragment is the projection used by both single-issue fetches and search
|
|
// results. Centralised so the wire schema stays consistent.
|
|
const issueFragment = `
|
|
id
|
|
identifier
|
|
title
|
|
description
|
|
url
|
|
updatedAt
|
|
priority
|
|
priorityLabel
|
|
state { id name type color }
|
|
team { id key }
|
|
assignee { name email avatarUrl }
|
|
creator { name avatarUrl }
|
|
`
|
|
|
|
type issueNode struct {
|
|
ID string `json:"id"`
|
|
Identifier string `json:"identifier"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
URL string `json:"url"`
|
|
UpdatedAt string `json:"updatedAt"`
|
|
Priority int `json:"priority"`
|
|
PriorityLab string `json:"priorityLabel"`
|
|
State struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Color string `json:"color"`
|
|
} `json:"state"`
|
|
Team struct {
|
|
ID string `json:"id"`
|
|
Key string `json:"key"`
|
|
} `json:"team"`
|
|
Assignee *struct {
|
|
Name string `json:"name"`
|
|
Email string `json:"email"`
|
|
AvatarURL string `json:"avatarUrl"`
|
|
} `json:"assignee"`
|
|
Creator *struct {
|
|
Name string `json:"name"`
|
|
AvatarURL string `json:"avatarUrl"`
|
|
} `json:"creator"`
|
|
}
|
|
|
|
func issueNodeToIssue(n *issueNode) LinearIssue {
|
|
out := LinearIssue{
|
|
ID: n.ID,
|
|
Identifier: n.Identifier,
|
|
Title: n.Title,
|
|
Description: n.Description,
|
|
StateID: n.State.ID,
|
|
StateName: n.State.Name,
|
|
StateType: n.State.Type,
|
|
StateCategory: stateCategory(n.State.Type),
|
|
TeamID: n.Team.ID,
|
|
TeamKey: n.Team.Key,
|
|
Priority: n.Priority,
|
|
PriorityLabel: n.PriorityLab,
|
|
Updated: n.UpdatedAt,
|
|
URL: n.URL,
|
|
}
|
|
if n.Assignee != nil {
|
|
out.AssigneeName = n.Assignee.Name
|
|
out.AssigneeEmail = n.Assignee.Email
|
|
out.AssigneeIcon = n.Assignee.AvatarURL
|
|
}
|
|
if n.Creator != nil {
|
|
out.CreatorName = n.Creator.Name
|
|
out.CreatorIcon = n.Creator.AvatarURL
|
|
}
|
|
return out
|
|
}
|
|
|
|
// stateCategory maps Linear's state type onto Jira's three-bucket category so
|
|
// the frontend can style status pills uniformly across integrations.
|
|
func stateCategory(stateType string) string {
|
|
switch strings.ToLower(stateType) {
|
|
case "backlog", "unstarted", "triage":
|
|
return "new"
|
|
case "started":
|
|
return "indeterminate"
|
|
case "completed", "canceled":
|
|
return "done"
|
|
default:
|
|
return "new"
|
|
}
|
|
}
|
|
|
|
const issueByIDQuery = `
|
|
query IssueByID($id: String!) {
|
|
issue(id: $id) {` + issueFragment + `}
|
|
}`
|
|
|
|
// GetIssue loads a Linear issue by identifier (e.g. "ENG-123") and attaches
|
|
// the team's available workflow states. Linear's `issue(id)` field accepts
|
|
// either the UUID or the human identifier.
|
|
func (c *GraphQLClient) GetIssue(ctx context.Context, identifier string) (*LinearIssue, error) {
|
|
var data struct {
|
|
Issue *issueNode `json:"issue"`
|
|
}
|
|
if err := c.do(ctx, issueByIDQuery, map[string]interface{}{"id": identifier}, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
if data.Issue == nil {
|
|
return nil, &APIError{StatusCode: http.StatusNotFound, Message: "issue not found: " + identifier}
|
|
}
|
|
issue := issueNodeToIssue(data.Issue)
|
|
states, err := c.ListStates(ctx, issue.TeamKey)
|
|
if err != nil {
|
|
// Caller cancellation / deadline must propagate — returning a
|
|
// partial-success response after the request was abandoned would
|
|
// break downstream correctness.
|
|
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
|
return nil, err
|
|
}
|
|
var apiErr *APIError
|
|
if errors.As(err, &apiErr) && apiErr.StatusCode >= 400 && apiErr.StatusCode < 500 {
|
|
return nil, err
|
|
}
|
|
// Network blip or 5xx: keep the issue and let the UI render without
|
|
// the state selector. The user can still read the issue and refresh.
|
|
} else {
|
|
issue.States = states
|
|
}
|
|
return &issue, nil
|
|
}
|
|
|
|
// --- mutations ---
|
|
|
|
const setStateMutation = `
|
|
mutation SetIssueState($id: String!, $stateId: String!) {
|
|
issueUpdate(id: $id, input: { stateId: $stateId }) {
|
|
success
|
|
}
|
|
}`
|
|
|
|
type setStateData struct {
|
|
IssueUpdate struct {
|
|
Success bool `json:"success"`
|
|
} `json:"issueUpdate"`
|
|
}
|
|
|
|
// SetIssueState moves an issue to a new workflow state. issueID may be either
|
|
// the UUID or the human identifier — Linear accepts both. Mirrors Jira's
|
|
// DoTransition.
|
|
func (c *GraphQLClient) SetIssueState(ctx context.Context, issueID, stateID string) error {
|
|
var data setStateData
|
|
vars := map[string]interface{}{"id": issueID, "stateId": stateID}
|
|
if err := c.do(ctx, setStateMutation, vars, &data); err != nil {
|
|
return err
|
|
}
|
|
if !data.IssueUpdate.Success {
|
|
return &APIError{StatusCode: http.StatusInternalServerError, Message: "issueUpdate returned success=false"}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// --- search ---
|
|
|
|
const searchIssuesQuery = `
|
|
query SearchIssues($filter: IssueFilter, $first: Int!, $after: String) {
|
|
issues(filter: $filter, first: $first, after: $after, orderBy: updatedAt) {
|
|
nodes {` + issueFragment + `}
|
|
pageInfo { hasNextPage endCursor }
|
|
}
|
|
}`
|
|
|
|
type searchIssuesData struct {
|
|
Issues struct {
|
|
Nodes []issueNode `json:"nodes"`
|
|
PageInfo struct {
|
|
HasNextPage bool `json:"hasNextPage"`
|
|
EndCursor string `json:"endCursor"`
|
|
} `json:"pageInfo"`
|
|
} `json:"issues"`
|
|
}
|
|
|
|
// SearchIssues runs a filtered search and returns a page of issues. pageToken
|
|
// is the `endCursor` returned in the previous page; pass "" for the first
|
|
// page. maxResults is capped at 100 (Linear's max).
|
|
func (c *GraphQLClient) SearchIssues(ctx context.Context, filter SearchFilter, pageToken string, maxResults int) (*SearchResult, error) {
|
|
if maxResults <= 0 {
|
|
maxResults = 25
|
|
}
|
|
if maxResults > 100 {
|
|
maxResults = 100
|
|
}
|
|
gqlFilter := buildIssueFilter(filter)
|
|
vars := map[string]interface{}{"filter": gqlFilter, "first": maxResults}
|
|
if pageToken != "" {
|
|
vars["after"] = pageToken
|
|
}
|
|
var data searchIssuesData
|
|
if err := c.do(ctx, searchIssuesQuery, vars, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
out := &SearchResult{
|
|
MaxResults: maxResults,
|
|
IsLast: !data.Issues.PageInfo.HasNextPage,
|
|
NextPageToken: data.Issues.PageInfo.EndCursor,
|
|
Issues: make([]LinearIssue, 0, len(data.Issues.Nodes)),
|
|
}
|
|
for i := range data.Issues.Nodes {
|
|
out.Issues = append(out.Issues, issueNodeToIssue(&data.Issues.Nodes[i]))
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// buildIssueFilter translates our SearchFilter into Linear's IssueFilter input.
|
|
// Empty fields are dropped so we don't send `{ "team": null }` and similar
|
|
// (which Linear treats as a typed null and rejects).
|
|
func buildIssueFilter(f SearchFilter) map[string]interface{} {
|
|
out := map[string]interface{}{}
|
|
if q := strings.TrimSpace(f.Query); q != "" {
|
|
// Linear has no top-level free-text field, but `searchableContent`
|
|
// matches across title and description.
|
|
out["searchableContent"] = map[string]interface{}{"contains": q}
|
|
}
|
|
if f.TeamKey != "" {
|
|
out["team"] = map[string]interface{}{"key": map[string]interface{}{"eq": f.TeamKey}}
|
|
}
|
|
if len(f.StateIDs) > 0 {
|
|
out["state"] = map[string]interface{}{"id": map[string]interface{}{"in": f.StateIDs}}
|
|
}
|
|
switch f.Assigned {
|
|
case "me":
|
|
// `null: false` + assignee filter would require the viewer ID; instead
|
|
// we use the `viewer` shortcut Linear exposes via `assignee.isMe`.
|
|
out["assignee"] = map[string]interface{}{"isMe": map[string]interface{}{"eq": true}}
|
|
case "unassigned":
|
|
out["assignee"] = map[string]interface{}{"null": true}
|
|
}
|
|
if len(f.Priorities) > 0 {
|
|
out["priority"] = map[string]interface{}{"in": f.Priorities}
|
|
}
|
|
if len(f.LabelIDs) > 0 {
|
|
// `labels.some` matches issues having at least one label whose id is
|
|
// in the provided list — Linear's OR semantics for multi-label filter.
|
|
out["labels"] = map[string]interface{}{
|
|
"some": map[string]interface{}{
|
|
"id": map[string]interface{}{"in": f.LabelIDs},
|
|
},
|
|
}
|
|
}
|
|
if f.CreatorID != "" {
|
|
out["creator"] = map[string]interface{}{"id": map[string]interface{}{"eq": f.CreatorID}}
|
|
}
|
|
if f.EstimateMin != nil || f.EstimateMax != nil {
|
|
bounds := map[string]interface{}{}
|
|
if f.EstimateMin != nil {
|
|
bounds["gte"] = *f.EstimateMin
|
|
}
|
|
if f.EstimateMax != nil {
|
|
bounds["lte"] = *f.EstimateMax
|
|
}
|
|
out["estimate"] = bounds
|
|
}
|
|
if len(out) == 0 {
|
|
return nil
|
|
}
|
|
return out
|
|
}
|
|
|
|
// --- labels ---
|
|
|
|
// Linear's GraphQL API caps `first` at 250. We don't paginate labels/users
|
|
// because the watcher dialog renders them as a single dropdown — a workspace
|
|
// with >250 labels or members would have UX problems regardless of how the
|
|
// data is fetched. If this limit is hit in practice, switch to cursor-based
|
|
// pagination here and lazy-load in the UI.
|
|
const linearMaxPageSize = 250
|
|
|
|
const teamLabelsQuery = `
|
|
query TeamLabels($filter: IssueLabelFilter!, $first: Int!) {
|
|
issueLabels(first: $first, filter: $filter) {
|
|
nodes { id name color }
|
|
}
|
|
}`
|
|
|
|
type labelsData struct {
|
|
IssueLabels struct {
|
|
Nodes []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Color string `json:"color"`
|
|
} `json:"nodes"`
|
|
} `json:"issueLabels"`
|
|
}
|
|
|
|
// ListLabels returns the issue labels available for a team identified by its
|
|
// key. Workspace-scoped labels (no team) are included by also fetching the
|
|
// `team: null` set in a second pass when teamKey is empty.
|
|
func (c *GraphQLClient) ListLabels(ctx context.Context, teamKey string) ([]LinearLabel, error) {
|
|
if teamKey == "" {
|
|
return nil, fmt.Errorf("teamKey required")
|
|
}
|
|
vars := map[string]interface{}{
|
|
"filter": map[string]interface{}{
|
|
"team": map[string]interface{}{"key": map[string]interface{}{"eq": teamKey}},
|
|
},
|
|
"first": linearMaxPageSize,
|
|
}
|
|
var data labelsData
|
|
if err := c.do(ctx, teamLabelsQuery, vars, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]LinearLabel, 0, len(data.IssueLabels.Nodes))
|
|
for _, l := range data.IssueLabels.Nodes {
|
|
out = append(out, LinearLabel{ID: l.ID, Name: l.Name, Color: l.Color})
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// --- users ---
|
|
|
|
const teamMembersQuery = `
|
|
query TeamMembers($filter: UserFilter!, $first: Int!) {
|
|
users(first: $first, filter: $filter, orderBy: updatedAt) {
|
|
nodes { id name displayName email avatarUrl }
|
|
}
|
|
}`
|
|
|
|
type usersData struct {
|
|
Users struct {
|
|
Nodes []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
DisplayName string `json:"displayName"`
|
|
Email string `json:"email"`
|
|
AvatarURL string `json:"avatarUrl"`
|
|
} `json:"nodes"`
|
|
} `json:"users"`
|
|
}
|
|
|
|
// ListUsers returns members of the team identified by teamKey. The filter
|
|
// uses Linear's `teamMemberships.some` to scope to that team.
|
|
func (c *GraphQLClient) ListUsers(ctx context.Context, teamKey string) ([]LinearUser, error) {
|
|
if teamKey == "" {
|
|
return nil, fmt.Errorf("teamKey required")
|
|
}
|
|
vars := map[string]interface{}{
|
|
"filter": map[string]interface{}{
|
|
"teamMemberships": map[string]interface{}{
|
|
"some": map[string]interface{}{
|
|
"team": map[string]interface{}{"key": map[string]interface{}{"eq": teamKey}},
|
|
},
|
|
},
|
|
},
|
|
"first": linearMaxPageSize,
|
|
}
|
|
var data usersData
|
|
if err := c.do(ctx, teamMembersQuery, vars, &data); err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]LinearUser, 0, len(data.Users.Nodes))
|
|
for _, u := range data.Users.Nodes {
|
|
out = append(out, LinearUser{
|
|
ID: u.ID,
|
|
Name: u.Name,
|
|
DisplayName: u.DisplayName,
|
|
Email: u.Email,
|
|
AvatarURL: u.AvatarURL,
|
|
})
|
|
}
|
|
return out, nil
|
|
}
|