Skip to main content

kasl/api/
jira.rs

1//! Jira client: completed issues for task discovery, assigned open
2//! issues for the inbox poller.
3//!
4//! ```rust,no_run
5//! # use kasl::api::jira::{Jira, JiraConfig};
6//! # use chrono::Local;
7//! # async fn f() -> anyhow::Result<()> {
8//! let config = JiraConfig {
9//!     login: "username".to_string(),
10//!     api_url: "https://jira.company.com".to_string(),
11//!     completed_statuses: Vec::new(),
12//! };
13//!
14//! let mut jira = Jira::new(&config);
15//! let today = Local::now().date_naive();
16//! let issues = jira.get_completed_issues(&today).await?;
17//! # Ok(())
18//! # }
19//! ```
20
21use super::Session;
22use crate::libs::{config::ConfigModule, messages::Message, secret::Secret};
23use crate::msg_print;
24use anyhow::Result;
25use chrono::NaiveDate;
26use dialoguer::{Input, theme::ColorfulTheme};
27use reqwest::{
28    Client, StatusCode,
29    header::{COOKIE, HeaderMap, HeaderValue},
30};
31use serde::{Deserialize, Deserializer, Serialize};
32use serde_json::Value;
33use std::collections::HashMap;
34use std::time::Duration;
35
36const MAX_RETRY_COUNT: i32 = 3;
37
38const SEARCH_PAGE_SIZE: u32 = 100;
39
40const SESSION_ID_FILE: &str = ".jira_session_id";
41
42const SECRET_FILE: &str = ".jira_secret";
43
44const AUTH_URL: &str = "rest/auth/1/session";
45
46const SEARCH_URL: &str = "rest/api/2/search";
47
48/// Login pair, held in memory only while authenticating.
49#[derive(Serialize, Clone, Debug)]
50pub struct LoginCredentials {
51    username: String,
52    password: String,
53}
54
55#[derive(Serialize, Deserialize, Debug)]
56struct JiraSessionResponse {
57    session: JiraSession,
58}
59
60/// Session cookie (typically `JSESSIONID`) sent on every API request.
61#[derive(Serialize, Deserialize, Debug)]
62struct JiraSession {
63    name: String,
64    value: String,
65}
66
67/// The slice of a Jira issue kasl works with.
68#[derive(Serialize, Deserialize, Debug)]
69pub struct JiraIssue {
70    /// Numeric issue id assigned by Jira.
71    pub id: String,
72    /// Human-readable key, e.g. "PROJECT-123".
73    pub key: String,
74    pub fields: JiraIssueFields,
75}
76
77/// The fields kasl reads; custom fields land in `extra` via flatten.
78#[derive(Serialize, Deserialize, Debug)]
79pub struct JiraIssueFields {
80    /// Issue title/summary (required field in Jira)
81    pub summary: String,
82    /// Detailed description (may be empty or contain rich text)
83    #[serde(default)]
84    pub description: Option<String>,
85    /// Current workflow status information
86    pub status: JiraStatus,
87    /// Date when the issue was resolved (ISO format if completed)
88    #[serde(default)]
89    pub resolutiondate: Option<String>,
90    /// Issue priority (Highest / High / Medium / …)
91    #[serde(default)]
92    pub priority: Option<JiraPriority>,
93    /// Last update timestamp from Jira (ISO-8601)
94    #[serde(default)]
95    pub updated: Option<String>,
96    /// Custom and other fields keyed by Jira field id (e.g. `customfield_12345`).
97    #[serde(flatten)]
98    pub extra: HashMap<String, Value>,
99}
100
101/// Workflow status; names vary by configuration and locale.
102#[derive(Serialize, Deserialize, Debug, Clone)]
103pub struct JiraStatus {
104    /// Stable status id from Jira (preferred for storage / joins)
105    #[serde(default, deserialize_with = "deserialize_jira_id")]
106    pub id: String,
107    /// Status name (e.g., "Done", "In Progress", "Решена" for Russian locale)
108    pub name: String,
109}
110
111/// Accepts Jira ids as JSON string or number (`"3"` / `3`).
112fn deserialize_jira_id<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
113where
114    D: Deserializer<'de>,
115{
116    let value = Option::<Value>::deserialize(deserializer)?;
117    Ok(match value {
118        Some(Value::String(s)) => s,
119        Some(Value::Number(n)) => n.to_string(),
120        _ => String::new(),
121    })
122}
123
124/// Jira issue priority.
125///
126/// Classic Jira uses numeric ids where lower means higher urgency
127/// (e.g. `"1"` = Highest). Used for inbox sorting.
128#[derive(Serialize, Deserialize, Debug, Clone)]
129pub struct JiraPriority {
130    /// Priority display name (e.g. "High", "Highest")
131    pub name: String,
132    /// Numeric priority id as string (lower = more urgent in classic schemes)
133    #[serde(default)]
134    pub id: Option<String>,
135}
136
137/// One page of a JQL search.
138#[derive(Serialize, Deserialize, Debug)]
139pub struct JiraSearchResults {
140    /// Index of the first issue in this page
141    #[serde(default, rename = "startAt")]
142    pub start_at: u32,
143    /// Requested page size
144    #[serde(default, rename = "maxResults")]
145    pub max_results: u32,
146    /// Total matching issues across all pages
147    #[serde(default)]
148    pub total: u32,
149    /// Array of issues matching the search criteria
150    pub issues: Vec<JiraIssue>,
151}
152
153/// Jira client with cached-session management via the [`Session`] trait.
154#[derive(Debug)]
155pub struct Jira {
156    client: Client,
157    config: JiraConfig,
158    /// Held in memory only while authenticating.
159    credentials: Option<LoginCredentials>,
160    retries: i32,
161}
162
163impl Session for Jira {
164    /// Logs in and returns the session cookie as `name=value`.
165    async fn login(&self) -> Result<String> {
166        let credentials = self.credentials.clone().expect("Credentials not set!");
167
168        let auth_url = format!("{}/{}", self.config.api_url, AUTH_URL);
169        let auth_res = self.client.post(auth_url).json(&credentials).send().await?;
170
171        if !auth_res.status().is_success() {
172            anyhow::bail!("Jira authenticate failed")
173        }
174
175        let session_res = auth_res.json::<JiraSessionResponse>().await?;
176
177        let session_id = format!("{}={}", session_res.session.name, session_res.session.value);
178        Ok(session_id)
179    }
180
181    fn set_credentials(&mut self, password: &str) -> Result<()> {
182        self.credentials = Some(LoginCredentials {
183            username: self.config.login.to_string(),
184            password: password.to_owned(),
185        });
186        Ok(())
187    }
188
189    fn session_id_file(&self) -> &str {
190        SESSION_ID_FILE
191    }
192
193    fn secret(&self) -> Secret {
194        Secret::new(SECRET_FILE, "Enter your Jira password")
195    }
196
197    fn retry(&self) -> i32 {
198        self.retries
199    }
200
201    fn inc_retry(&mut self) {
202        self.retries += 1;
203    }
204
205    fn reset_retry(&mut self) {
206        self.retries = 0;
207    }
208}
209
210impl Jira {
211    /// Builds a client from the config; no network activity yet.
212    ///
213    /// ```rust,no_run
214    /// use kasl::api::jira::{Jira, JiraConfig};
215    ///
216    /// let config = JiraConfig {
217    ///     login: "username".to_string(),
218    ///     api_url: "https://jira.company.com".to_string(),
219    ///     completed_statuses: Vec::new(),
220    /// };
221    /// let jira = Jira::new(&config);
222    /// ```
223    pub fn new(config: &JiraConfig) -> Self {
224        Self {
225            client: Client::new(),
226            config: config.clone(),
227            credentials: None,
228            retries: 0,
229        }
230    }
231
232    /// Fetches the user's issues resolved on `date` (full-day range).
233    ///
234    /// A 401 drops the cached session and retries up to the limit; other
235    /// failures propagate - completed issues feed the report, so a silent
236    /// empty result would hide real problems.
237    ///
238    /// ```rust,no_run
239    /// # use kasl::api::jira::{Jira, JiraConfig};
240    /// # use chrono::NaiveDate;
241    /// # use anyhow::Result;
242    /// # async fn example() -> Result<()> {
243    /// let config = JiraConfig {
244    ///     login: "username".to_string(),
245    ///     api_url: "https://jira.company.com".to_string(),
246    ///     completed_statuses: Vec::new(),
247    /// };
248    /// let mut jira = Jira::new(&config);
249    ///
250    /// let today = chrono::Local::now().date_naive();
251    /// let issues = jira.get_completed_issues(&today).await?;
252    ///
253    /// for issue in issues {
254    ///     println!("Completed: {} - {}", issue.key, issue.fields.summary);
255    /// }
256    /// # Ok(())
257    /// # }
258    /// ```
259    pub async fn get_completed_issues(&mut self, date: &NaiveDate) -> Result<Vec<JiraIssue>> {
260        let mut local_retries = 0;
261        loop {
262            let session_id = self.get_session_id().await?;
263
264            match self.fetch_completed_pages(&session_id, date).await {
265                Ok(issues) => return Ok(issues),
266                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
267                    let _ = self.delete_session_id();
268                    local_retries += 1;
269                    tokio::time::sleep(Duration::from_secs(1)).await;
270                }
271                Err(SearchPageError::Unauthorized) => {
272                    anyhow::bail!("Jira session unauthorized after retries")
273                }
274                Err(SearchPageError::Other(msg)) => {
275                    anyhow::bail!("Jira completed-issues search failed: {msg}")
276                }
277            }
278        }
279    }
280
281    /// Fetches all pages of completed issues for a valid session cookie.
282    async fn fetch_completed_pages(&self, session_id: &str, date: &NaiveDate) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
283        // Filter by resolution date only. Do not use `status in (...)` with English
284        // defaults like "Done"/"Resolved": on localized Jira those names are invalid
285        // and the whole JQL fails (HTTP 400), which used to look like "no issues".
286        let date_str = date.format("%Y-%m-%d").to_string();
287        let jql = format!(
288            "assignee = currentUser() AND resolved >= \"{}\" AND resolved <= \"{} 23:59\"",
289            date_str, date_str
290        );
291        let url = format!("{}/{}", self.config.api_url, SEARCH_URL);
292
293        let mut all = Vec::new();
294        let mut start_at: u32 = 0;
295
296        loop {
297            let mut headers = HeaderMap::new();
298            headers.insert(
299                COOKIE,
300                HeaderValue::from_str(session_id).map_err(|e| SearchPageError::Other(format!("invalid session cookie: {e}")))?,
301            );
302
303            let res = self
304                .client
305                .get(&url)
306                .headers(headers)
307                .query(&[
308                    ("jql", jql.as_str()),
309                    ("fields", "summary,status,priority,updated,resolutiondate"),
310                    ("startAt", &start_at.to_string()),
311                    ("maxResults", &SEARCH_PAGE_SIZE.to_string()),
312                ])
313                .send()
314                .await
315                .map_err(|e| SearchPageError::Other(format!("request failed: {e}")))?;
316
317            match res.status() {
318                StatusCode::UNAUTHORIZED => return Err(SearchPageError::Unauthorized),
319                status if !status.is_success() => {
320                    let body = res.text().await.unwrap_or_default();
321                    return Err(SearchPageError::Other(format!("HTTP {status}: {body}")));
322                }
323                _ => {}
324            }
325
326            let page: JiraSearchResults = res.json().await.map_err(|e| SearchPageError::Other(format!("invalid JSON: {e}")))?;
327            let batch_len = page.issues.len() as u32;
328            all.extend(page.issues);
329
330            start_at += batch_len;
331            if batch_len == 0 || start_at >= page.total {
332                break;
333            }
334        }
335
336        Ok(all)
337    }
338
339    /// Fetches open issues currently assigned to the authenticated user.
340    ///
341    /// Uses JQL `assignee = currentUser() AND resolution is EMPTY`. Paginates
342    /// through all matching issues (`startAt` / `total`). Extra field ids
343    /// (custom fields such as Scoring) are included in the `fields` query.
344    ///
345    /// A poll that fails is an error, never an empty list. The caller
346    /// reconciles the inbox against whatever comes back, so an empty answer
347    /// for a dropped VPN would mark every issue gone - and the next good poll
348    /// would bring all of them "back", one change toast per issue.
349    pub async fn get_assigned_open_issues(&mut self, extra_field_ids: &[String]) -> Result<Vec<JiraIssue>> {
350        let mut local_retries = 0;
351        loop {
352            let session_id = self.get_session_id().await?;
353
354            match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
355                Ok(issues) => return Ok(issues),
356                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
357                    let _ = self.delete_session_id();
358                    local_retries += 1;
359                    tokio::time::sleep(Duration::from_secs(1)).await;
360                }
361                Err(e) => return Err(e.into_poll_error()),
362            }
363        }
364    }
365
366    /// Like [`get_assigned_open_issues`], but never prompts for a password.
367    ///
368    /// Uses a cached session cookie and/or the keyring secret. Returns
369    /// `Ok(None)` when neither is available so background daemons can skip
370    /// the poll without blocking on stdin. A poll that fails is an error, for
371    /// the same reason as in [`get_assigned_open_issues`]: the daemon must
372    /// skip the reconcile, not reconcile against nothing.
373    pub async fn get_assigned_open_issues_noninteractive(&mut self, extra_field_ids: &[String]) -> Result<Option<Vec<JiraIssue>>> {
374        let mut local_retries = 0;
375        loop {
376            let Some(session_id) = self.session_id_noninteractive().await? else {
377                return Ok(None);
378            };
379
380            match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
381                Ok(issues) => return Ok(Some(issues)),
382                Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
383                    let _ = self.delete_session_id();
384                    local_retries += 1;
385                    tokio::time::sleep(Duration::from_secs(1)).await;
386                }
387                Err(e) => return Err(e.into_poll_error()),
388            }
389        }
390    }
391
392    /// Fetches all pages of assigned open issues for a valid session cookie.
393    async fn fetch_assigned_open_pages(&self, session_id: &str, extra_field_ids: &[String]) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
394        let jql = "assignee = currentUser() AND resolution is EMPTY ORDER BY priority ASC, updated DESC";
395        let fields = build_search_fields(extra_field_ids);
396        let url = format!("{}/{}", self.config.api_url, SEARCH_URL);
397
398        let mut all = Vec::new();
399        let mut start_at: u32 = 0;
400
401        loop {
402            let mut headers = HeaderMap::new();
403            headers.insert(
404                COOKIE,
405                HeaderValue::from_str(session_id).map_err(|e| SearchPageError::Other(format!("invalid session cookie: {e}")))?,
406            );
407
408            let res = self
409                .client
410                .get(&url)
411                .headers(headers)
412                .query(&[
413                    ("jql", jql),
414                    ("fields", fields.as_str()),
415                    ("startAt", &start_at.to_string()),
416                    ("maxResults", &SEARCH_PAGE_SIZE.to_string()),
417                ])
418                .send()
419                .await
420                .map_err(|e| SearchPageError::Other(format!("request failed: {e}")))?;
421
422            match res.status() {
423                StatusCode::UNAUTHORIZED => return Err(SearchPageError::Unauthorized),
424                status if !status.is_success() => {
425                    let body = res.text().await.unwrap_or_default();
426                    return Err(SearchPageError::Other(format!("HTTP {status}: {body}")));
427                }
428                _ => {}
429            }
430
431            let page: JiraSearchResults = res.json().await.map_err(|e| SearchPageError::Other(format!("invalid JSON: {e}")))?;
432            let batch_len = page.issues.len() as u32;
433            all.extend(page.issues);
434
435            start_at += batch_len;
436            if batch_len == 0 || start_at >= page.total {
437                break;
438            }
439        }
440
441        Ok(all)
442    }
443
444    /// Resolves a session from cache / secret without prompting.
445    async fn session_id_noninteractive(&mut self) -> Result<Option<String>> {
446        let session_id_file_path = crate::libs::data_storage::DataStorage::new().get_path(SESSION_ID_FILE)?;
447        let path_str = session_id_file_path.to_str().unwrap_or_default();
448
449        if let Ok(session_id) = Self::read_session_id(path_str) {
450            return Ok(Some(session_id));
451        }
452
453        let Some(password) = self.secret().try_get_cached() else {
454            return Ok(None);
455        };
456
457        self.set_credentials(&password)?;
458        match self.login().await {
459            Ok(session_id) => {
460                let _ = Self::write_session_id(path_str, &session_id);
461                self.reset_retry();
462                Ok(Some(session_id))
463            }
464            Err(_) => Ok(None),
465        }
466    }
467
468    /// Builds the issue-navigator URL listing the user's open issues.
469    ///
470    /// Summary toasts point here: they speak for many issues at once, so no
471    /// single browse URL fits.
472    pub fn open_issues_url(&self) -> String {
473        let base = self.config.api_url.trim_end_matches('/');
474        format!("{base}/issues/?jql=assignee%20%3D%20currentUser()%20AND%20resolution%20is%20EMPTY")
475    }
476
477    /// Builds a browse URL for an issue key using this client's API base.
478    pub fn issue_browse_url(&self, key: &str) -> String {
479        let base = self.config.api_url.trim_end_matches('/');
480        format!("{}/browse/{}", base, key)
481    }
482
483    /// Maps a Jira priority id to a sortable rank (lower = more urgent).
484    pub fn priority_rank(priority: &Option<JiraPriority>) -> i32 {
485        priority
486            .as_ref()
487            .and_then(|p| p.id.as_ref())
488            .and_then(|id| id.parse::<i32>().ok())
489            .unwrap_or(999)
490    }
491
492    /// Extracts a numeric value from a Jira custom-field JSON value.
493    ///
494    /// Supports bare numbers, numeric strings, and objects with `value` / `amount`.
495    pub fn extract_number(value: &Value) -> Option<f64> {
496        match value {
497            Value::Number(n) => n.as_f64(),
498            Value::String(s) => s.trim().parse().ok(),
499            Value::Object(map) => map
500                .get("value")
501                .and_then(Self::extract_number)
502                .or_else(|| map.get("amount").and_then(Self::extract_number)),
503            _ => None,
504        }
505    }
506
507    /// Reads a numeric custom field from issue extras by field id.
508    pub fn sort_value_from_issue(issue: &JiraIssue, field_id: &str) -> Option<f64> {
509        issue.fields.extra.get(field_id).and_then(Self::extract_number)
510    }
511}
512
513/// Internal error for paginated search (auth vs other failures).
514enum SearchPageError {
515    Unauthorized,
516    Other(String),
517}
518
519impl SearchPageError {
520    /// Names what went wrong with an inbox poll, and what fixes it.
521    fn into_poll_error(self) -> anyhow::Error {
522        match self {
523            SearchPageError::Unauthorized => {
524                anyhow::anyhow!("Jira rejected the session {MAX_RETRY_COUNT} times; run `kasl inbox sync` to sign in again")
525            }
526            SearchPageError::Other(msg) => anyhow::anyhow!("Jira inbox poll failed: {msg}"),
527        }
528    }
529}
530
531fn build_search_fields(extra_field_ids: &[String]) -> String {
532    let mut fields = vec!["summary".to_string(), "status".to_string(), "priority".to_string(), "updated".to_string()];
533    for id in extra_field_ids {
534        let trimmed = id.trim();
535        if !trimmed.is_empty() && !fields.iter().any(|f| f == trimmed) {
536            fields.push(trimmed.to_string());
537        }
538    }
539    fields.join(",")
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545    use serde_json::json;
546
547    #[test]
548    fn extract_number_from_primitives_and_objects() {
549        assert_eq!(Jira::extract_number(&json!(12.5)), Some(12.5));
550        assert_eq!(Jira::extract_number(&json!("42")), Some(42.0));
551        assert_eq!(Jira::extract_number(&json!({"value": 7})), Some(7.0));
552        assert_eq!(Jira::extract_number(&json!({"amount": "3.5"})), Some(3.5));
553        assert_eq!(Jira::extract_number(&json!(null)), None);
554    }
555
556    #[test]
557    fn build_search_fields_includes_custom_ids() {
558        let fields = build_search_fields(&["customfield_10001".to_string(), "summary".to_string()]);
559        assert!(fields.contains("summary"));
560        assert!(fields.contains("customfield_10001"));
561        assert_eq!(fields.matches("summary").count(), 1);
562    }
563}
564
565/// Jira connection settings; passwords are never stored here.
566#[derive(Serialize, Deserialize, Clone, Debug)]
567pub struct JiraConfig {
568    /// Username (email for Atlassian Cloud accounts).
569    pub login: String,
570
571    /// Instance root URL, without the `/rest/api/` path.
572    pub api_url: String,
573
574    /// Deprecated: previously used in `status in (...)` for completed-issue search.
575    ///
576    /// Kept for config compatibility. Discovery now filters by `resolved` date only,
577    /// because non-existent status names (e.g. English "Done" on a Russian Jira)
578    /// make the whole JQL fail.
579    #[serde(default = "default_completed_statuses")]
580    pub completed_statuses: Vec<String>,
581}
582
583/// Empty default — status names are no longer used in completed-issue JQL.
584fn default_completed_statuses() -> Vec<String> {
585    Vec::new()
586}
587
588impl JiraConfig {
589    /// Module metadata for the setup wizard.
590    pub fn module() -> ConfigModule {
591        ConfigModule {
592            key: "jira".to_string(),
593            name: "Jira".to_string(),
594        }
595    }
596
597    /// Interactive setup; existing values become the prompt defaults.
598    ///
599    /// ```rust,no_run
600    /// # use kasl::api::JiraConfig;
601    /// # use anyhow::Result;
602    /// # fn example() -> Result<()> {
603    /// let existing_config = Some(JiraConfig {
604    ///     login: "olduser".to_string(),
605    ///     api_url: "https://old-jira.com".to_string(),
606    ///     completed_statuses: Vec::new(),
607    /// });
608    ///
609    /// let new_config = JiraConfig::init(&existing_config)?;
610    /// # Ok(())
611    /// # }
612    /// ```
613    pub fn init(config: &Option<Self>) -> Result<Self> {
614        // Use existing configuration as defaults, or create empty defaults
615        let config = config.clone().unwrap_or(Self {
616            login: "".to_string(),
617            api_url: "".to_string(),
618            completed_statuses: default_completed_statuses(),
619        });
620
621        // Display configuration module header
622        msg_print!(Message::ConfigModuleJira);
623
624        // Interactive configuration with existing values as defaults
625        Ok(Self {
626            completed_statuses: config.completed_statuses.clone(),
627            login: Input::with_theme(&ColorfulTheme::default())
628                .with_prompt("Enter your Jira login")
629                .default(config.login)
630                .interact_text()?,
631            api_url: Input::with_theme(&ColorfulTheme::default())
632                .with_prompt("Enter the Jira API URL")
633                .default(config.api_url)
634                .interact_text()?,
635        })
636    }
637}