pub mod api;
use std::sync::Arc;
use anyhow::{anyhow, Result};
use colored::Colorize;
use serde_json::Value;
use toon_format::encode_default as toon_encode;
use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
use api::{Case, CasesApi, TeammateDirectory};
pub fn normalize_priority(input: &str) -> Result<String> {
let upper = input.trim().to_uppercase();
if upper.starts_with("CASE_PRIORITY_") {
return Ok(upper);
}
match upper.as_str() {
"P1" | "P2" | "P3" | "P4" | "P5" => Ok(format!("CASE_PRIORITY_{upper}")),
_ => Err(anyhow!(
"invalid priority '{input}': expected one of P1, P2, P3, P4, P5"
)),
}
}
pub fn normalize_initial_status(input: &str) -> Result<String> {
let upper = input.trim().to_uppercase();
let bare = upper.strip_prefix("CASE_STATUS_").unwrap_or(&upper);
match bare {
"ACTIVE" | "ACKNOWLEDGED" => Ok(format!("CASE_STATUS_{bare}")),
_ => Err(anyhow!(
"invalid initial status '{input}': a new case can only start as ACTIVE or ACKNOWLEDGED"
)),
}
}
pub fn parse_label(input: &str) -> Result<(String, String)> {
match input.split_once('=') {
Some((k, v)) if !k.trim().is_empty() => Ok((k.trim().to_string(), v.to_string())),
_ => Err(anyhow!("invalid label '{input}': expected key=value")),
}
}
const MAX_DESCRIPTION_CHARS: usize = 10_000;
fn validate_description_length(description: &str) -> Result<()> {
let len = description.chars().count();
if len > MAX_DESCRIPTION_CHARS {
return Err(anyhow!(
"--description must be at most {MAX_DESCRIPTION_CHARS} characters, got {len}"
));
}
Ok(())
}
const READABLE_ID_POLL_ATTEMPTS: usize = 5;
const READABLE_ID_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
fn has_readable_id(result: &Value) -> bool {
result
.get("case")
.and_then(|c| c.get("readableId"))
.and_then(Value::as_str)
.is_some_and(|r| !r.is_empty())
}
async fn wait_for_readable_id(api: &CasesApi<'_>, mut result: Value) -> Value {
let Some(id) = result
.get("case")
.and_then(|c| c.get("id"))
.and_then(Value::as_str)
.map(String::from)
else {
return result;
};
for _ in 0..READABLE_ID_POLL_ATTEMPTS {
if has_readable_id(&result) {
break;
}
tokio::time::sleep(READABLE_ID_POLL_INTERVAL).await;
match api.get(&id).await {
Ok(fresh) => result = fresh,
Err(_) => break,
}
}
result
}
pub struct CreateCaseArgs<'a> {
pub title: &'a str,
pub description: &'a str,
pub priority: &'a str,
pub labels: &'a [String],
pub assignee: Option<&'a str>,
pub status: Option<&'a str>,
}
fn build_create_body(args: &CreateCaseArgs<'_>) -> Result<Value> {
if args.title.trim().is_empty() {
return Err(anyhow!("--title must not be empty"));
}
if args.description.trim().is_empty() {
return Err(anyhow!(
"--description must not be empty: it is the only context a manual case carries"
));
}
validate_description_length(args.description)?;
let mut body = serde_json::Map::new();
body.insert("title".into(), Value::String(args.title.to_string()));
body.insert(
"description".into(),
Value::String(args.description.to_string()),
);
body.insert(
"priority".into(),
Value::String(normalize_priority(args.priority)?),
);
if !args.labels.is_empty() {
let labels = args
.labels
.iter()
.map(|l| {
parse_label(l).map(|(key, value)| serde_json::json!({ "key": key, "value": value }))
})
.collect::<Result<Vec<_>>>()?;
body.insert("labels".into(), Value::Array(labels));
}
if let Some(s) = args.status {
body.insert("status".into(), Value::String(normalize_initial_status(s)?));
}
Ok(Value::Object(body))
}
fn substitute_assignee_email(value: &mut Value, directory: &TeammateDirectory) {
let Some(assignee) = value.get_mut("assignee").and_then(|v| v.as_object_mut()) else {
return;
};
let Some(uid) = assignee
.get("userId")
.and_then(|v| v.as_str())
.map(String::from)
else {
return;
};
if let Some(email) = directory.email_for(&uid) {
assignee.remove("userId");
assignee.insert("email".to_string(), Value::String(email.to_string()));
}
}
fn substitute_user_emails(value: &mut Value, directory: &TeammateDirectory) {
match value {
Value::Object(map) => {
for v in map.values_mut() {
substitute_user_emails(v, directory);
}
}
Value::Array(arr) => {
for v in arr.iter_mut() {
substitute_user_emails(v, directory);
}
}
Value::String(s) => {
if let Some(email) = directory.email_for(s) {
*s = email.to_string();
}
}
_ => {}
}
}
fn humanize_enum(s: &str) -> String {
for prefix in ["CASE_STATUS_", "CASE_PRIORITY_", "CASE_CATEGORY_"] {
if let Some(rest) = s.strip_prefix(prefix) {
return rest.to_string();
}
}
s.to_string()
}
fn format_event_actor(event: &Value) -> String {
let Some(actor) = event.get("actor").and_then(|v| v.as_object()) else {
return "-".to_string();
};
if let Some(user) = actor.get("user").and_then(|v| v.as_object()) {
return user
.get("email")
.or_else(|| user.get("userId"))
.or_else(|| user.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("user")
.to_string();
}
if actor.contains_key("system") {
return "system".to_string();
}
actor
.keys()
.next()
.cloned()
.unwrap_or_else(|| "-".to_string())
}
fn format_event_details(event: &Value) -> String {
let Some((_kind, payload)) = event
.get("eventData")
.and_then(|v| v.as_object())
.and_then(|m| m.iter().next())
else {
return "-".to_string();
};
let Some(obj) = payload.as_object() else {
return "-".to_string();
};
let get = |k: &str| obj.get(k).and_then(|v| v.as_str()).map(humanize_enum);
if let (Some(old), Some(new)) = (get("oldStatus"), get("newStatus")) {
return format!("{old} → {new}");
}
if let (Some(old), Some(new)) = (get("oldPriority"), get("newPriority")) {
return format!("{old} → {new}");
}
if let Some(priority) = get("priority") {
return priority;
}
if let Some(status) = get("status") {
return status;
}
let pairs: Vec<String> = obj
.iter()
.filter_map(|(k, v)| v.as_str().map(|s| format!("{k}: {}", humanize_enum(s))))
.collect();
if pairs.is_empty() {
"-".to_string()
} else {
pairs.join(", ")
}
}
fn format_delivery_status(delivery: &Value) -> String {
const BOOKKEEPING: [&str; 4] = ["timestamp", "requestNotificationId", "caseId", "profile"];
let Some(obj) = delivery.as_object() else {
return "-".to_string();
};
obj.keys()
.find(|k| !BOOKKEEPING.contains(&k.as_str()))
.map(|k| humanize_camel_case(k))
.unwrap_or_else(|| "-".to_string())
}
fn humanize_camel_case(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 4);
for (i, ch) in s.chars().enumerate() {
if ch.is_uppercase() && i != 0 {
out.push(' ');
out.extend(ch.to_lowercase());
} else if i == 0 {
out.extend(ch.to_uppercase());
} else {
out.push(ch);
}
}
out
}
struct DeliveryRow {
profile: String,
case_id: String,
connector: String,
connector_type: String,
status: String,
evidence_url: String,
timestamp: String,
}
fn delivery_rows(delivery: &Value) -> Vec<DeliveryRow> {
let profile = str_field(delivery, "profile");
let case_id = str_field(delivery, "caseId");
let timestamp = str_field(delivery, "timestamp");
let attempts = delivery
.get("attempted")
.and_then(|a| a.get("attempts"))
.and_then(|v| v.as_array());
let Some(attempts) = attempts.filter(|a| !a.is_empty()) else {
return vec![DeliveryRow {
profile,
case_id,
connector: "-".to_string(),
connector_type: "-".to_string(),
status: format_delivery_status(delivery),
evidence_url: "-".to_string(),
timestamp,
}];
};
attempts
.iter()
.map(|attempt| {
let connector = attempt
.get("connector")
.map(|c| str_field(c, "connectorName"))
.filter(|s| s != "-")
.unwrap_or_else(|| "-".to_string());
let connector_type = attempt
.get("connector")
.and_then(|c| c.get("connectorType"))
.and_then(|v| v.as_str())
.map(|t| t.strip_prefix("CONNECTOR_TYPE_").unwrap_or(t).to_string())
.unwrap_or_else(|| "-".to_string());
let outcome = attempt.get("outcome").and_then(|v| v.as_object());
let status = outcome
.and_then(|o| o.keys().next())
.map(|k| humanize_camel_case(k))
.unwrap_or_else(|| "-".to_string());
let evidence_url = outcome
.and_then(|o| o.values().next())
.map(|v| str_field(v, "evidenceUrl"))
.filter(|s| s != "-")
.unwrap_or_else(|| "-".to_string());
DeliveryRow {
profile: profile.clone(),
case_id: case_id.clone(),
connector,
connector_type,
status,
evidence_url,
timestamp: timestamp.clone(),
}
})
.collect()
}
fn str_field(value: &Value, key: &str) -> String {
value
.get(key)
.and_then(|v| v.as_str())
.unwrap_or("-")
.to_string()
}
pub async fn run_create(
targets: &[Arc<ExecutionTarget>],
args: &CreateCaseArgs<'_>,
output: OutputFormat,
) -> Result<()> {
let base_body = build_create_body(args)?;
eprintln!(
"{}",
format!("Creating case '{}'...", args.title.trim()).dimmed()
);
let assignee = args.assignee.map(String::from);
let per_profile = fan_out(targets, |t| {
let mut body = base_body.clone();
let assignee = assignee.clone();
async move {
let api = CasesApi::new(&t.client);
let mut directory = None;
if let Some(input) = assignee {
let user_id = if input.contains('@') {
let dir = api.teammate_directory().await.map_err(|e| {
anyhow!(
"failed to fetch team members to resolve email '{input}': {e:#}\n\
hint: pass the user ID directly: --assignee <user-id>."
)
})?;
let uid = dir.resolve_to_user_id(&input)?;
directory = Some(dir);
uid
} else {
input
};
body["assignee"] = serde_json::json!({ "userId": user_id });
}
let created = api.create(&body).await?;
let mut result = wait_for_readable_id(&api, created).await;
if let (Some(case), Some(dir)) = (result.get_mut("case"), directory.as_ref()) {
substitute_assignee_email(case, dir);
}
Ok::<_, anyhow::Error>(result)
}
})
.await;
let include_profile = targets.len() > 1;
let mut all_results: Vec<Value> = Vec::new();
for (profile, mut v) in report_errors_and_collect_successes(per_profile)? {
let case = v.get("case");
let id = case
.and_then(|c| c.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("-")
.to_string();
let readable = case
.and_then(|c| c.get("readableId"))
.and_then(|v| v.as_str())
.map(|r| format!(" ({r})"))
.unwrap_or_default();
eprintln!(
"{}",
format!("Created case {id}{readable} in profile '{profile}'.").green()
);
if readable.is_empty() && id != "-" {
eprintln!(
"{}",
"Its readable CASE-… id is not assigned yet; it appears within moments. \
The link below opens the case now."
.yellow()
);
}
if id != "-" {
crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
crate::console_url::case_url(b, &id)
})
.await;
}
if include_profile {
render::tag_get_result(&mut v, &profile);
}
all_results.push(v);
}
match output {
OutputFormat::Json => render::render_json_auto(&all_results)?,
OutputFormat::Toon => {
let toon = toon_encode(&all_results)
.map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
}
}
Ok(())
}
pub async fn run_get(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Fetching case {case_id}...").dimmed());
let include_profile = targets.len() > 1;
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
let (case_res, dir_res) = tokio::join!(api.get(&id), api.teammate_directory());
let case = case_res?;
let directory = dir_res.unwrap_or_default();
Ok::<_, anyhow::Error>((case, directory))
}
})
.await;
let mut all_results: Vec<(Value, TeammateDirectory)> = Vec::new();
for (profile, (mut val, directory)) in report_errors_and_collect_successes(per_profile)? {
if let Some(case) = val.get_mut("case") {
substitute_assignee_email(case, &directory);
}
if include_profile {
render::tag_get_result(&mut val, &profile);
}
crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
crate::console_url::case_url(b, case_id)
})
.await;
all_results.push((val, directory));
}
let values: Vec<Value> = all_results.iter().map(|(v, _)| v.clone()).collect();
match output {
OutputFormat::Json => render::render_json_auto(&values)?,
OutputFormat::Toon => {
let toon =
toon_encode(&values).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
render::render_get_text(
&values,
include_profile,
"Case not found.",
Some(&|val| {
if let Some(case_val) = val.get("case") {
if let Ok(case) = serde_json::from_value::<Case>(case_val.clone()) {
println!(
"{}: {}",
"Title".bold(),
case.title.as_deref().unwrap_or("-")
);
println!(
"{}: {}",
"ID".bold(),
case.id.as_deref().unwrap_or("-")
);
if let Some(rid) = case.readable_id.as_deref() {
println!("{}: {rid}", "Readable ID".bold());
}
println!("{}: {}", "Status".bold(), case.display_status());
println!("{}: {}", "Priority".bold(), case.display_priority());
println!("{}: {}", "Category".bold(), case.display_category());
let assignee = case_val
.get("assignee")
.and_then(|a| {
a.get("email")
.and_then(|v| v.as_str())
.or_else(|| a.get("userId").and_then(|v| v.as_str()))
})
.unwrap_or("-");
println!("{}: {assignee}", "Assignee".bold());
println!(
"{}: {}",
"Created".bold(),
case.create_time.as_deref().unwrap_or("-")
);
if let Some(ack) = case.acknowledge_time.as_deref() {
println!("{}: {ack}", "Acknowledged".bold());
}
if let Some(summary) = case.ai_summary.as_deref() {
if !summary.is_empty() {
println!("{}: {summary}", "AI summary".bold());
}
}
}
}
}),
)?;
}
}
Ok(())
}
fn build_update_patch(
title: Option<&str>,
resolution_reason: Option<&str>,
description: Option<&str>,
) -> Result<Value> {
if title.is_none() && resolution_reason.is_none() && description.is_none() {
return Err(anyhow!(
"specify at least one of --title, --resolution-reason or --description"
));
}
let mut patch = serde_json::Map::new();
if let Some(t) = title {
patch.insert("title".to_string(), Value::String(t.to_string()));
}
if let Some(r) = resolution_reason {
patch.insert("resolutionReason".to_string(), Value::String(r.to_string()));
}
if let Some(d) = description {
if d.trim().is_empty() {
return Err(anyhow!("--description must not be empty"));
}
validate_description_length(d)?;
patch.insert("description".to_string(), Value::String(d.to_string()));
}
Ok(Value::Object(patch))
}
pub async fn run_update(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
title: Option<&str>,
resolution_reason: Option<&str>,
description: Option<&str>,
output: OutputFormat,
) -> Result<()> {
let patch = build_update_patch(title, resolution_reason, description)?;
eprintln!("{}", format!("Updating case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let patch = patch.clone();
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.update(&id, &patch).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Updated case '{case_id}'"),
)
.await
}
pub async fn run_comment(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
text: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Adding comment to case {case_id}...").dimmed()
);
let id = case_id.to_string();
let text = text.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let text = text.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.create_comment(&id, &text).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Added comment to case '{case_id}'"),
)
.await
}
pub async fn run_assign(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
user: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Assigning case {case_id} to {user}...").dimmed()
);
let id = case_id.to_string();
let input = user.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let input = input.clone();
async move {
let api = CasesApi::new(&t.client);
let (user_id, resolved_directory) = if input.contains('@') {
let directory = api.teammate_directory().await.map_err(|e| {
anyhow!(
"failed to fetch team members to resolve email '{input}': {e:#}\n\
hint: resolving an email requires read access to the team \
users directory (GET /mgmt/openapi/5/aaa/teams/v2/{{team_id}}/search). \
If your API key lacks that scope, pass the user ID directly: \
--user <user-id>."
)
})?;
let uid = directory.resolve_to_user_id(&input)?;
(uid, Some(directory))
} else {
(input.clone(), None)
};
let mut result = api.assign(&id, &user_id).await?;
let directory = match resolved_directory {
Some(d) => d,
None => api.teammate_directory().await.unwrap_or_default(),
};
if let Some(case) = result.get_mut("case") {
substitute_assignee_email(case, &directory);
}
Ok::<_, anyhow::Error>(result)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Assigned case '{case_id}' to '{user}'"),
)
.await
}
pub async fn run_unassign(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Unassigning case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.unassign(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Unassigned case '{case_id}'"),
)
.await
}
pub async fn run_acknowledge(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Acknowledging case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.acknowledge(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Acknowledged case '{case_id}'"),
)
.await
}
pub async fn run_unacknowledge(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Unacknowledging case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.unacknowledge(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Unacknowledged case '{case_id}'"),
)
.await
}
pub async fn run_resolve(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
reason: Option<&str>,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Resolving case {case_id}...").dimmed());
let id = case_id.to_string();
let reason_owned = reason.map(String::from);
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let reason = reason_owned.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.resolve(&id, reason.as_deref()).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Resolved case '{case_id}'"),
)
.await
}
pub async fn run_close(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Closing case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.close(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Closed case '{case_id}'"),
)
.await
}
pub async fn run_set_priority(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
priority: &str,
output: OutputFormat,
) -> Result<()> {
let normalized = normalize_priority(priority)?;
eprintln!(
"{}",
format!("Overriding priority of case {case_id} -> {normalized}...").dimmed()
);
let id = case_id.to_string();
let prio = normalized.clone();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let prio = prio.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.set_priority(&id, &prio).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Set priority of case '{case_id}' to {normalized}"),
)
.await
}
pub async fn run_clear_priority(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Clearing priority override of case {case_id}...").dimmed()
);
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.clear_priority(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Cleared priority override of case '{case_id}'"),
)
.await
}
pub async fn run_mute(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Muting case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.mute(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Muted case '{case_id}'"),
)
.await
}
pub async fn run_unmute(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Unmuting case {case_id}...").dimmed());
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.unmute(&id).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Unmuted case '{case_id}'"),
)
.await
}
pub async fn run_set_parent(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
parent_id: &str,
mute_child: bool,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Making case {case_id} a child of {parent_id}...").dimmed()
);
let id = case_id.to_string();
let parent = parent_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let parent = parent.clone();
async move {
let api = CasesApi::new(&t.client);
let parent_uuid = api.resolve_case_uuid(&parent).await?;
Ok(api.set_parent(&id, &parent_uuid, mute_child).await?)
}
})
.await;
let muted = if mute_child { ", muted" } else { "" };
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Case '{case_id}' is now a child of '{parent_id}'{muted}"),
)
.await
}
pub async fn run_unlink(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
linked_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Unlinking case {case_id} from {linked_id}...").dimmed()
);
let id = case_id.to_string();
let linked = linked_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
let linked = linked.clone();
async move {
let api = CasesApi::new(&t.client);
let linked_uuid = api.resolve_case_uuid(&linked).await?;
Ok(api.unlink(&id, &linked_uuid).await?)
}
})
.await;
finish_lifecycle(
targets,
case_id,
per_profile,
targets.len() > 1,
output,
&format!("Unlinked case '{case_id}' from '{linked_id}'"),
)
.await
}
fn has_linked_cases(v: &Value) -> bool {
let links = &v["linkedCases"];
!links["parent"]["case"].is_null()
|| links["children"]["cases"]
.as_array()
.is_some_and(|c| !c.is_empty())
}
pub async fn run_linked(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Fetching cases linked to {case_id}...").dimmed()
);
let include_profile = targets.len() > 1;
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.list_linked(&id).await?)
}
})
.await;
let mut all_results: Vec<Value> = Vec::new();
for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
if include_profile {
render::tag_get_result(&mut val, &profile);
}
all_results.push(val);
}
match output {
OutputFormat::Json => render::render_json_auto(&all_results)?,
OutputFormat::Toon => {
let toon = toon_encode(&all_results)
.map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
let linked: Vec<Value> = all_results.into_iter().filter(has_linked_cases).collect();
render::render_get_text(&linked, include_profile, "No linked cases found.", None)?;
}
}
Ok(())
}
pub async fn run_events_list(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
include_children: bool,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Fetching events for case {case_id}...").dimmed()
);
let include_profile = targets.len() > 1;
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
let (events_res, dir_res) = tokio::join!(
api.list_events(&id, include_children),
api.teammate_directory()
);
let events = events_res?;
let directory = dir_res.unwrap_or_default();
Ok::<_, anyhow::Error>((events, directory))
}
})
.await;
let mut all_json: Vec<Value> = Vec::new();
for (profile, (resp, directory)) in report_errors_and_collect_successes(per_profile)? {
for mut event in resp.events {
substitute_user_emails(&mut event, &directory);
if include_profile {
if let Value::Object(ref mut m) = event {
m.insert("profile".to_string(), Value::String(profile.clone()));
}
}
all_json.push(event);
}
}
match output {
OutputFormat::Json => render::render_json(&all_json)?,
OutputFormat::Toon => {
let toon =
toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
if all_json.is_empty() {
render::print_no_results("No case events found.");
return Ok(());
}
let rows: Vec<Vec<String>> = all_json
.iter()
.map(|event| {
let profile = event
.get("profile")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let event_id = event
.get("eventId")
.or_else(|| event.get("id"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let event_type = event
.get("eventData")
.and_then(|v| v.as_object())
.and_then(|m| m.keys().next())
.map(|k| k.to_string())
.unwrap_or_default();
let created = event
.get("createTime")
.or_else(|| event.get("create_time"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let actor = format_event_actor(event);
let details = format_event_details(event);
let mut row = vec![profile];
if include_children {
row.push(
event
.get("caseId")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
);
}
row.extend([event_id, event_type, actor, details, created]);
row
})
.collect();
let mut headers = vec!["Event ID", "Type", "Actor", "Details", "Timestamp"];
if include_children {
headers.insert(0, "Case ID");
}
render::render_table(&headers, rows, include_profile);
}
}
Ok(())
}
pub async fn run_event_get(
targets: &[Arc<ExecutionTarget>],
event_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!("{}", format!("Fetching event {event_id}...").dimmed());
let include_profile = targets.len() > 1;
let id = event_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
let (event_res, dir_res) = tokio::join!(api.get_event(&id), api.teammate_directory());
let mut event = event_res?;
let directory = dir_res.unwrap_or_default();
substitute_user_emails(&mut event, &directory);
Ok::<_, anyhow::Error>(event)
}
})
.await;
let mut all_results: Vec<Value> = Vec::new();
for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
if include_profile {
render::tag_get_result(&mut val, &profile);
}
all_results.push(val);
}
match output {
OutputFormat::Json => render::render_json_auto(&all_results)?,
OutputFormat::Toon => {
let toon = toon_encode(&all_results)
.map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
render::render_get_text(&all_results, include_profile, "Event not found.", None)?;
}
}
Ok(())
}
pub async fn run_deep_links(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!("Fetching deep links for {case_id}...").dimmed()
);
let include_profile = targets.len() > 1;
let id = case_id.to_string();
let per_profile = fan_out(targets, |t| {
let id = id.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.deep_links(&id).await?)
}
})
.await;
let mut all_results: Vec<Value> = Vec::new();
for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
if include_profile {
render::tag_get_result(&mut val, &profile);
}
all_results.push(val);
}
match output {
OutputFormat::Json => render::render_json_auto(&all_results)?,
OutputFormat::Toon => {
let toon = toon_encode(&all_results)
.map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
render::render_get_text(&all_results, include_profile, "No deep links found.", None)?;
}
}
Ok(())
}
pub async fn run_notifications(
targets: &[Arc<ExecutionTarget>],
case_ids: &[String],
output: OutputFormat,
) -> Result<()> {
eprintln!(
"{}",
format!(
"Fetching notification deliveries for {} case(s)...",
case_ids.len()
)
.dimmed()
);
let include_profile = targets.len() > 1;
let ids = case_ids.to_vec();
let per_profile = fan_out(targets, |t| {
let ids = ids.clone();
async move {
let api = CasesApi::new(&t.client);
Ok(api.list_notification_deliveries(&ids).await?)
}
})
.await;
let mut all_json: Vec<Value> = Vec::new();
for (profile, val) in report_errors_and_collect_successes(per_profile)? {
let map = val.get("deliveriesByCase").and_then(|v| v.as_object());
if let Some(map) = map {
for (case_id, payload) in map {
let deliveries = payload
.get("notificationDeliveries")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
for mut delivery in deliveries {
if let Value::Object(ref mut m) = delivery {
m.insert("caseId".to_string(), Value::String(case_id.clone()));
if include_profile {
m.insert("profile".to_string(), Value::String(profile.clone()));
}
}
all_json.push(delivery);
}
}
}
}
match output {
OutputFormat::Json => render::render_json(&all_json)?,
OutputFormat::Toon => {
let toon =
toon_encode(&all_json).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
if all_json.is_empty() {
render::print_no_results("No notification deliveries found.");
return Ok(());
}
let include_case_id = case_ids.len() > 1;
let rows: Vec<Vec<String>> = all_json
.iter()
.flat_map(delivery_rows)
.map(|r| {
let mut row = Vec::with_capacity(6);
row.push(r.profile);
if include_case_id {
row.push(r.case_id);
}
row.push(r.connector);
row.push(r.connector_type);
row.push(r.status);
row.push(r.evidence_url);
row.push(r.timestamp);
row
})
.collect();
let headers: &[&str] = if include_case_id {
&[
"Case ID",
"Connector",
"Type",
"Status",
"Evidence URL",
"Timestamp",
]
} else {
&["Connector", "Type", "Status", "Evidence URL", "Timestamp"]
};
render::render_table(headers, rows, include_profile);
}
}
Ok(())
}
async fn finish_lifecycle(
targets: &[Arc<ExecutionTarget>],
case_id: &str,
per_profile: Vec<(String, Result<Value>)>,
include_profile: bool,
output: OutputFormat,
success_label: &str,
) -> Result<()> {
let mut all_results: Vec<Value> = Vec::new();
for (profile, mut v) in report_errors_and_collect_successes(per_profile)? {
if include_profile {
render::tag_get_result(&mut v, &profile);
}
eprintln!(
"{}",
format!("{success_label} in profile '{profile}'.").green()
);
crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
crate::console_url::case_url(b, case_id)
})
.await;
all_results.push(v);
}
match output {
OutputFormat::Json => render::render_json_auto(&all_results)?,
OutputFormat::Toon => {
let toon = toon_encode(&all_results)
.map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
println!("{toon}");
}
OutputFormat::Text => {
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn has_linked_cases_detects_parent_or_children() {
assert!(!has_linked_cases(&json!({ "pbacTruncated": false })));
assert!(!has_linked_cases(
&json!({ "linkedCases": { "children": { "cases": [] } } })
));
assert!(has_linked_cases(
&json!({ "linkedCases": { "parent": { "case": { "id": "p1" } } } })
));
assert!(has_linked_cases(
&json!({ "linkedCases": { "children": { "cases": [{ "id": "c1" }] } } })
));
}
#[test]
fn normalize_priority_accepts_shorthand() {
assert_eq!(normalize_priority("P1").unwrap(), "CASE_PRIORITY_P1");
assert_eq!(normalize_priority("p3").unwrap(), "CASE_PRIORITY_P3");
}
#[test]
fn normalize_priority_passes_through_full_enum() {
assert_eq!(
normalize_priority("CASE_PRIORITY_P2").unwrap(),
"CASE_PRIORITY_P2"
);
}
#[test]
fn normalize_priority_rejects_invalid() {
assert!(normalize_priority("CRITICAL").is_err());
assert!(normalize_priority("P9").is_err());
}
#[test]
fn normalize_initial_status_accepts_only_active_and_acknowledged() {
assert_eq!(
normalize_initial_status("active").unwrap(),
"CASE_STATUS_ACTIVE"
);
assert_eq!(
normalize_initial_status("CASE_STATUS_ACKNOWLEDGED").unwrap(),
"CASE_STATUS_ACKNOWLEDGED"
);
assert!(normalize_initial_status("RESOLVED").is_err());
}
#[test]
fn parse_label_splits_on_first_equals() {
assert_eq!(
parse_label("routing.team=a=b").unwrap(),
("routing.team".to_string(), "a=b".to_string())
);
assert!(parse_label("no-equals").is_err());
assert!(parse_label("=value").is_err());
}
#[test]
fn build_create_body_normalizes_fields() {
let labels = vec!["service=payments".to_string()];
let body = build_create_body(&CreateCaseArgs {
title: "Payments latency",
description: "p99 up 3x since 10:00",
priority: "p2",
labels: &labels,
assignee: None,
status: Some("acknowledged"),
})
.unwrap();
assert_eq!(
body,
serde_json::json!({
"title": "Payments latency",
"description": "p99 up 3x since 10:00",
"priority": "CASE_PRIORITY_P2",
"labels": [{ "key": "service", "value": "payments" }],
"status": "CASE_STATUS_ACKNOWLEDGED"
})
);
}
#[test]
fn build_update_patch_sends_only_given_fields() {
let patch = build_update_patch(None, None, Some("Root cause: bad deploy")).unwrap();
assert_eq!(
patch,
serde_json::json!({ "description": "Root cause: bad deploy" })
);
let patch = build_update_patch(Some("t"), Some("r"), Some("d")).unwrap();
assert_eq!(
patch,
serde_json::json!({ "title": "t", "resolutionReason": "r", "description": "d" })
);
}
#[test]
fn build_update_patch_rejects_blank_or_oversized_description() {
let err = build_update_patch(None, None, Some(" ")).unwrap_err();
assert!(err.to_string().contains("--description must not be empty"));
let long = "x".repeat(MAX_DESCRIPTION_CHARS + 1);
let err = build_update_patch(None, None, Some(&long)).unwrap_err();
assert!(err
.to_string()
.contains("at most 10000 characters, got 10001"));
}
#[test]
fn build_update_patch_requires_a_field() {
let err = build_update_patch(None, None, None).unwrap_err();
assert!(err.to_string().contains("--description"));
}
#[test]
fn build_create_body_rejects_blank_description() {
let err = build_create_body(&CreateCaseArgs {
title: "t",
description: " ",
priority: "P3",
labels: &[],
assignee: None,
status: None,
})
.unwrap_err();
assert!(err.to_string().contains("--description"));
}
fn directory() -> TeammateDirectory {
TeammateDirectory::from_users(vec![api::TeamUser {
user_id: Some("uid-known".into()),
username: Some("alice@example.com".into()),
}])
}
#[test]
fn substitute_user_emails_maps_known_ids_in_event() {
let mut event = serde_json::json!({
"eventId": "e1",
"actor": { "user": { "userId": "uid-known" } },
"eventData": {
"assigned": {
"assigneeUserId": "uid-known",
"previousAssigneeUserId": "uid-unknown"
}
}
});
substitute_user_emails(&mut event, &directory());
assert_eq!(
event["actor"]["user"]["userId"], "alice@example.com",
"actor user ID should resolve to email"
);
assert_eq!(
event["eventData"]["assigned"]["assigneeUserId"],
"alice@example.com"
);
assert_eq!(
event["eventData"]["assigned"]["previousAssigneeUserId"],
"uid-unknown"
);
}
#[test]
fn substitute_user_emails_is_a_noop_without_matches() {
let mut event = serde_json::json!({
"eventData": { "statusChanged": { "oldStatus": "ACTIVE", "newStatus": "RESOLVED" } }
});
let before = event.clone();
substitute_user_emails(&mut event, &directory());
assert_eq!(event, before);
}
}