1use 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#[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#[derive(Serialize, Deserialize, Debug)]
62struct JiraSession {
63 name: String,
64 value: String,
65}
66
67#[derive(Serialize, Deserialize, Debug)]
69pub struct JiraIssue {
70 pub id: String,
72 pub key: String,
74 pub fields: JiraIssueFields,
75}
76
77#[derive(Serialize, Deserialize, Debug)]
79pub struct JiraIssueFields {
80 pub summary: String,
82 #[serde(default)]
84 pub description: Option<String>,
85 pub status: JiraStatus,
87 #[serde(default)]
89 pub resolutiondate: Option<String>,
90 #[serde(default)]
92 pub priority: Option<JiraPriority>,
93 #[serde(default)]
95 pub updated: Option<String>,
96 #[serde(flatten)]
98 pub extra: HashMap<String, Value>,
99}
100
101#[derive(Serialize, Deserialize, Debug, Clone)]
103pub struct JiraStatus {
104 #[serde(default, deserialize_with = "deserialize_jira_id")]
106 pub id: String,
107 pub name: String,
109}
110
111fn 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#[derive(Serialize, Deserialize, Debug, Clone)]
129pub struct JiraPriority {
130 pub name: String,
132 #[serde(default)]
134 pub id: Option<String>,
135}
136
137#[derive(Serialize, Deserialize, Debug)]
139pub struct JiraSearchResults {
140 #[serde(default, rename = "startAt")]
142 pub start_at: u32,
143 #[serde(default, rename = "maxResults")]
145 pub max_results: u32,
146 #[serde(default)]
148 pub total: u32,
149 pub issues: Vec<JiraIssue>,
151}
152
153#[derive(Debug)]
155pub struct Jira {
156 client: Client,
157 config: JiraConfig,
158 credentials: Option<LoginCredentials>,
160 retries: i32,
161}
162
163impl Session for Jira {
164 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 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 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 async fn fetch_completed_pages(&self, session_id: &str, date: &NaiveDate) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
283 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 pub async fn get_assigned_open_issues(&mut self, extra_field_ids: &[String]) -> Result<Vec<JiraIssue>> {
348 let mut local_retries = 0;
349 loop {
350 let session_id = match self.get_session_id().await {
351 Ok(id) => id,
352 Err(_) => return Ok(Vec::new()),
353 };
354
355 match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
356 Ok(issues) => return Ok(issues),
357 Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
358 let _ = self.delete_session_id();
359 local_retries += 1;
360 tokio::time::sleep(Duration::from_secs(1)).await;
361 }
362 Err(_) => return Ok(Vec::new()),
363 }
364 }
365 }
366
367 pub async fn get_assigned_open_issues_noninteractive(&mut self, extra_field_ids: &[String]) -> Result<Option<Vec<JiraIssue>>> {
373 let mut local_retries = 0;
374 loop {
375 let Some(session_id) = self.session_id_noninteractive().await? else {
376 return Ok(None);
377 };
378
379 match self.fetch_assigned_open_pages(&session_id, extra_field_ids).await {
380 Ok(issues) => return Ok(Some(issues)),
381 Err(SearchPageError::Unauthorized) if local_retries < MAX_RETRY_COUNT => {
382 let _ = self.delete_session_id();
383 local_retries += 1;
384 tokio::time::sleep(Duration::from_secs(1)).await;
385 }
386 Err(_) => return Ok(Some(Vec::new())),
387 }
388 }
389 }
390
391 async fn fetch_assigned_open_pages(&self, session_id: &str, extra_field_ids: &[String]) -> std::result::Result<Vec<JiraIssue>, SearchPageError> {
393 let jql = "assignee = currentUser() AND resolution is EMPTY ORDER BY priority ASC, updated DESC";
394 let fields = build_search_fields(extra_field_ids);
395 let url = format!("{}/{}", self.config.api_url, SEARCH_URL);
396
397 let mut all = Vec::new();
398 let mut start_at: u32 = 0;
399
400 loop {
401 let mut headers = HeaderMap::new();
402 headers.insert(
403 COOKIE,
404 HeaderValue::from_str(session_id).map_err(|e| SearchPageError::Other(format!("invalid session cookie: {e}")))?,
405 );
406
407 let res = self
408 .client
409 .get(&url)
410 .headers(headers)
411 .query(&[
412 ("jql", jql),
413 ("fields", fields.as_str()),
414 ("startAt", &start_at.to_string()),
415 ("maxResults", &SEARCH_PAGE_SIZE.to_string()),
416 ])
417 .send()
418 .await
419 .map_err(|e| SearchPageError::Other(format!("request failed: {e}")))?;
420
421 match res.status() {
422 StatusCode::UNAUTHORIZED => return Err(SearchPageError::Unauthorized),
423 status if !status.is_success() => {
424 let body = res.text().await.unwrap_or_default();
425 return Err(SearchPageError::Other(format!("HTTP {status}: {body}")));
426 }
427 _ => {}
428 }
429
430 let page: JiraSearchResults = res.json().await.map_err(|e| SearchPageError::Other(format!("invalid JSON: {e}")))?;
431 let batch_len = page.issues.len() as u32;
432 all.extend(page.issues);
433
434 start_at += batch_len;
435 if batch_len == 0 || start_at >= page.total {
436 break;
437 }
438 }
439
440 Ok(all)
441 }
442
443 async fn session_id_noninteractive(&mut self) -> Result<Option<String>> {
445 let session_id_file_path = crate::libs::data_storage::DataStorage::new().get_path(SESSION_ID_FILE)?;
446 let path_str = session_id_file_path.to_str().unwrap_or_default();
447
448 if let Ok(session_id) = Self::read_session_id(path_str) {
449 return Ok(Some(session_id));
450 }
451
452 let Some(password) = self.secret().try_get_cached() else {
453 return Ok(None);
454 };
455
456 self.set_credentials(&password)?;
457 match self.login().await {
458 Ok(session_id) => {
459 let _ = Self::write_session_id(path_str, &session_id);
460 self.reset_retry();
461 Ok(Some(session_id))
462 }
463 Err(_) => Ok(None),
464 }
465 }
466
467 pub fn issue_browse_url(&self, key: &str) -> String {
469 let base = self.config.api_url.trim_end_matches('/');
470 format!("{}/browse/{}", base, key)
471 }
472
473 pub fn priority_rank(priority: &Option<JiraPriority>) -> i32 {
475 priority
476 .as_ref()
477 .and_then(|p| p.id.as_ref())
478 .and_then(|id| id.parse::<i32>().ok())
479 .unwrap_or(999)
480 }
481
482 pub fn extract_number(value: &Value) -> Option<f64> {
486 match value {
487 Value::Number(n) => n.as_f64(),
488 Value::String(s) => s.trim().parse().ok(),
489 Value::Object(map) => map
490 .get("value")
491 .and_then(Self::extract_number)
492 .or_else(|| map.get("amount").and_then(Self::extract_number)),
493 _ => None,
494 }
495 }
496
497 pub fn sort_value_from_issue(issue: &JiraIssue, field_id: &str) -> Option<f64> {
499 issue.fields.extra.get(field_id).and_then(Self::extract_number)
500 }
501}
502
503enum SearchPageError {
505 Unauthorized,
506 Other(String),
507}
508
509fn build_search_fields(extra_field_ids: &[String]) -> String {
510 let mut fields = vec!["summary".to_string(), "status".to_string(), "priority".to_string(), "updated".to_string()];
511 for id in extra_field_ids {
512 let trimmed = id.trim();
513 if !trimmed.is_empty() && !fields.iter().any(|f| f == trimmed) {
514 fields.push(trimmed.to_string());
515 }
516 }
517 fields.join(",")
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523 use serde_json::json;
524
525 #[test]
526 fn extract_number_from_primitives_and_objects() {
527 assert_eq!(Jira::extract_number(&json!(12.5)), Some(12.5));
528 assert_eq!(Jira::extract_number(&json!("42")), Some(42.0));
529 assert_eq!(Jira::extract_number(&json!({"value": 7})), Some(7.0));
530 assert_eq!(Jira::extract_number(&json!({"amount": "3.5"})), Some(3.5));
531 assert_eq!(Jira::extract_number(&json!(null)), None);
532 }
533
534 #[test]
535 fn build_search_fields_includes_custom_ids() {
536 let fields = build_search_fields(&["customfield_10001".to_string(), "summary".to_string()]);
537 assert!(fields.contains("summary"));
538 assert!(fields.contains("customfield_10001"));
539 assert_eq!(fields.matches("summary").count(), 1);
540 }
541}
542
543#[derive(Serialize, Deserialize, Clone, Debug)]
545pub struct JiraConfig {
546 pub login: String,
548
549 pub api_url: String,
551
552 #[serde(default = "default_completed_statuses")]
558 pub completed_statuses: Vec<String>,
559}
560
561fn default_completed_statuses() -> Vec<String> {
563 Vec::new()
564}
565
566impl JiraConfig {
567 pub fn module() -> ConfigModule {
569 ConfigModule {
570 key: "jira".to_string(),
571 name: "Jira".to_string(),
572 }
573 }
574
575 pub fn init(config: &Option<Self>) -> Result<Self> {
592 let config = config.clone().unwrap_or(Self {
594 login: "".to_string(),
595 api_url: "".to_string(),
596 completed_statuses: default_completed_statuses(),
597 });
598
599 msg_print!(Message::ConfigModuleJira);
601
602 Ok(Self {
604 completed_statuses: config.completed_statuses.clone(),
605 login: Input::with_theme(&ColorfulTheme::default())
606 .with_prompt("Enter your Jira login")
607 .default(config.login)
608 .interact_text()?,
609 api_url: Input::with_theme(&ColorfulTheme::default())
610 .with_prompt("Enter the Jira API URL")
611 .default(config.api_url)
612 .interact_text()?,
613 })
614 }
615}