devboy-jira 0.27.0

Jira provider for devboy-tools — IssueProvider/Provider implementation including project version CRUD over the Jira Cloud REST API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Jira provider metadata types for dynamic schema enrichment.

use serde::{Deserialize, Serialize};

/// Metadata for Jira project(s), used for dynamic schema enrichment.
///
/// Supports both single-project and multi-project configurations.
/// Multi-project unions enum values across projects.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraMetadata {
    /// Jira flavor (affects API version and auth).
    #[serde(default = "default_flavor")]
    pub flavor: JiraFlavor,
    /// Per-project metadata keyed by project key (e.g., "PROJ").
    pub projects: std::collections::HashMap<String, JiraProjectMetadata>,
    /// Structures the integration user can see across the Jira instance.
    ///
    /// `/rest/structure/2.0/structure` is **not** keyed by Jira project — it
    /// returns every structure the caller has read access to. Placed here
    /// (on the instance-level metadata) rather than on `JiraProjectMetadata`.
    /// Empty when the Structure plugin is not installed or the user has no
    /// read access; that is the graceful-degrade signal the schema enricher
    /// keys on to decide whether to enrich Structure tools.
    #[serde(default)]
    pub structures: Vec<JiraStructureRef>,
}

fn default_flavor() -> JiraFlavor {
    JiraFlavor::Cloud
}

/// Jira deployment flavor.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum JiraFlavor {
    /// Jira Cloud (API v3, ADF format, accountId-based users)
    Cloud,
    /// Jira Self-Hosted / Data Center (API v2, plain text, username-based users)
    SelfHosted,
}

/// Metadata for a single Jira project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraProjectMetadata {
    /// Available issue types (filter out subtask types for create_issue).
    #[serde(default)]
    pub issue_types: Vec<JiraIssueType>,
    #[serde(default)]
    pub components: Vec<JiraComponent>,
    #[serde(default)]
    pub priorities: Vec<JiraPriority>,
    #[serde(default)]
    pub link_types: Vec<JiraLinkType>,
    #[serde(default)]
    pub custom_fields: Vec<JiraCustomField>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraIssueType {
    pub id: String,
    pub name: String,
    /// Whether this is a subtask type (exclude from create_issue enum).
    #[serde(default)]
    pub subtask: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraComponent {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraPriority {
    pub id: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraLinkType {
    pub id: String,
    pub name: String,
    /// Outward description (e.g., "blocks").
    #[serde(default)]
    pub outward: Option<String>,
    /// Inward description (e.g., "is blocked by").
    #[serde(default)]
    pub inward: Option<String>,
}

/// Jira custom field definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraCustomField {
    /// Field ID in Jira (e.g., "customfield_10001").
    pub id: String,
    /// Human-readable name.
    pub name: String,
    pub field_type: JiraFieldType,
    /// Whether this field is required.
    #[serde(default)]
    pub required: bool,
    /// Options for option/array fields.
    #[serde(default)]
    pub options: Vec<JiraFieldOption>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum JiraFieldType {
    /// Single select → name → `{ id: option_id }`.
    Option,
    /// Multi-select → name array → `[{ id }, ...]`.
    Array,
    /// Numeric → pass-through.
    Number,
    /// Date (YYYY-MM-DD) → pass-through.
    Date,
    /// DateTime (ISO 8601) → pass-through.
    DateTime,
    /// Free text → pass-through.
    String,
    /// Catch-all (epic link, etc.) → pass-through as string key.
    Any,
}

/// Option for Jira option/array custom fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JiraFieldOption {
    pub id: String,
    pub name: String,
}

/// Reference to a Jira Structure the integration user can access.
///
/// Populated from `/rest/structure/2.0/structure`. Stored in
/// [`JiraMetadata::structures`] and consumed by `JiraSchemaEnricher` to
/// add description-based hints for the `structureId` parameter on the 7
/// Structure tools that take it (the strict JSON Schema `enum` is deferred
/// until `PropertySchema.enum_values` supports non-string variants).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct JiraStructureRef {
    pub id: u64,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl JiraCustomField {
    /// Convert a human-readable value to Jira API format.
    ///
    /// - Option: name → `{ "id": "option_id" }`
    /// - Array: name array → `[{ "id": "id1" }, { "id": "id2" }]`
    /// - Other types: pass-through
    pub fn transform_value(&self, value: &serde_json::Value) -> serde_json::Value {
        match self.field_type {
            JiraFieldType::Option => {
                if let Some(name) = value.as_str()
                    && let Some(opt) = self
                        .options
                        .iter()
                        .find(|o| o.name.eq_ignore_ascii_case(name))
                {
                    return serde_json::json!({ "id": opt.id });
                }
                value.clone()
            }
            JiraFieldType::Array => {
                if let Some(names) = value.as_array() {
                    let ids: Vec<serde_json::Value> = names
                        .iter()
                        .filter_map(|n| {
                            let name = n.as_str()?;
                            self.options
                                .iter()
                                .find(|o| o.name.eq_ignore_ascii_case(name))
                                .map(|o| serde_json::json!({ "id": o.id }))
                        })
                        .collect();
                    return serde_json::json!(ids);
                }
                value.clone()
            }
            _ => value.clone(),
        }
    }
}

impl JiraMetadata {
    /// Whether this is a single-project configuration.
    pub fn is_single_project(&self) -> bool {
        self.projects.len() == 1
    }

    /// Get project keys.
    pub fn project_keys(&self) -> Vec<&str> {
        self.projects.keys().map(|k| k.as_str()).collect()
    }

    /// Get union of all issue types across projects (non-subtask only).
    pub fn all_issue_types(&self) -> Vec<String> {
        let mut types: Vec<String> = self
            .projects
            .values()
            .flat_map(|p| {
                p.issue_types
                    .iter()
                    .filter(|t| !t.subtask)
                    .map(|t| t.name.clone())
            })
            .collect();
        types.sort();
        types.dedup();
        types
    }

    /// Get union of all priorities across projects.
    pub fn all_priorities(&self) -> Vec<String> {
        let mut prios: Vec<String> = self
            .projects
            .values()
            .flat_map(|p| p.priorities.iter().map(|pr| pr.name.clone()))
            .collect();
        prios.sort();
        prios.dedup();
        prios
    }

    /// Get union of all components across projects.
    pub fn all_components(&self) -> Vec<String> {
        let mut comps: Vec<String> = self
            .projects
            .values()
            .flat_map(|p| p.components.iter().map(|c| c.name.clone()))
            .collect();
        comps.sort();
        comps.dedup();
        comps
    }

    /// Get union of all link types across projects.
    pub fn all_link_types(&self) -> Vec<String> {
        let mut types: Vec<String> = self
            .projects
            .values()
            .flat_map(|p| p.link_types.iter().map(|lt| lt.name.clone()))
            .collect();
        types.sort();
        types.dedup();
        types
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn sample_option_field() -> JiraCustomField {
        JiraCustomField {
            id: "customfield_10001".into(),
            name: "Sprint".into(),
            field_type: JiraFieldType::Option,
            required: false,
            options: vec![
                JiraFieldOption {
                    id: "1".into(),
                    name: "Sprint 1".into(),
                },
                JiraFieldOption {
                    id: "2".into(),
                    name: "Sprint 2".into(),
                },
            ],
        }
    }

    #[test]
    fn test_jira_option_transform() {
        let field = sample_option_field();
        assert_eq!(
            field.transform_value(&json!("Sprint 1")),
            json!({ "id": "1" })
        );
    }

    #[test]
    fn test_jira_option_case_insensitive() {
        let field = sample_option_field();
        assert_eq!(
            field.transform_value(&json!("sprint 2")),
            json!({ "id": "2" })
        );
    }

    #[test]
    fn test_jira_array_transform() {
        let field = JiraCustomField {
            id: "customfield_10002".into(),
            name: "Fix Versions".into(),
            field_type: JiraFieldType::Array,
            required: false,
            options: vec![
                JiraFieldOption {
                    id: "v1".into(),
                    name: "1.0".into(),
                },
                JiraFieldOption {
                    id: "v2".into(),
                    name: "2.0".into(),
                },
            ],
        };
        assert_eq!(
            field.transform_value(&json!(["1.0", "2.0"])),
            json!([{ "id": "v1" }, { "id": "v2" }])
        );
    }

    #[test]
    fn test_metadata_single_project() {
        let meta = JiraMetadata {
            flavor: JiraFlavor::Cloud,
            projects: [(
                "PROJ".into(),
                JiraProjectMetadata {
                    issue_types: vec![],
                    components: vec![],
                    priorities: vec![],
                    link_types: vec![],
                    custom_fields: vec![],
                },
            )]
            .into_iter()
            .collect(),
            structures: vec![],
        };
        assert!(meta.is_single_project());
    }

    #[test]
    fn test_metadata_all_issue_types_deduped() {
        let meta = JiraMetadata {
            flavor: JiraFlavor::Cloud,
            projects: [
                (
                    "PROJ".into(),
                    JiraProjectMetadata {
                        issue_types: vec![
                            JiraIssueType {
                                id: "1".into(),
                                name: "Task".into(),
                                subtask: false,
                            },
                            JiraIssueType {
                                id: "2".into(),
                                name: "Bug".into(),
                                subtask: false,
                            },
                            JiraIssueType {
                                id: "3".into(),
                                name: "Sub-task".into(),
                                subtask: true,
                            },
                        ],
                        components: vec![],
                        priorities: vec![],
                        link_types: vec![],
                        custom_fields: vec![],
                    },
                ),
                (
                    "INFRA".into(),
                    JiraProjectMetadata {
                        issue_types: vec![
                            JiraIssueType {
                                id: "1".into(),
                                name: "Task".into(),
                                subtask: false,
                            },
                            JiraIssueType {
                                id: "4".into(),
                                name: "Epic".into(),
                                subtask: false,
                            },
                        ],
                        components: vec![],
                        priorities: vec![],
                        link_types: vec![],
                        custom_fields: vec![],
                    },
                ),
            ]
            .into_iter()
            .collect(),
            structures: vec![],
        };
        let types = meta.all_issue_types();
        assert_eq!(types, vec!["Bug", "Epic", "Task"]); // sorted, deduped, no subtask
    }

    #[test]
    fn jira_metadata_deserialises_without_structures_field() {
        // Back-compat: pre-existing persisted metadata does not carry the
        // new `structures` field. `#[serde(default)]` must fill in an
        // empty vec so old payloads still round-trip cleanly.
        let raw = serde_json::json!({
            "flavor": "cloud",
            "projects": {}
        });
        let meta: JiraMetadata = serde_json::from_value(raw).unwrap();
        assert!(meta.structures.is_empty());
    }

    #[test]
    fn jira_metadata_roundtrips_structures_list() {
        let meta = JiraMetadata {
            flavor: JiraFlavor::Cloud,
            projects: Default::default(),
            structures: vec![
                JiraStructureRef {
                    id: 7,
                    name: "Q1 Planning".into(),
                    description: Some("Top-level roadmap".into()),
                },
                JiraStructureRef {
                    id: 42,
                    name: "Sprint Board".into(),
                    description: None,
                },
            ],
        };

        let json = serde_json::to_value(&meta).unwrap();
        // `description: None` is skipped on serialize for compactness.
        assert_eq!(json["structures"][1].get("description"), None);

        let restored: JiraMetadata = serde_json::from_value(json).unwrap();
        assert_eq!(restored.structures, meta.structures);
    }
}