use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::error::OpError;
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ContextRequest {
#[serde(default)]
pub ticket_id: String,
#[serde(default)]
pub ticket_number: i64,
#[serde(default)]
pub subject: String,
#[serde(default)]
pub ticket_type_id: Option<String>,
#[serde(default)]
pub requester_id: String,
#[serde(default)]
pub organization_id: Option<String>,
#[serde(default)]
pub candidate_emails: Vec<String>,
}
impl ContextRequest {
pub fn primary_email(&self) -> Option<&str> {
self.candidate_emails.first().map(String::as_str)
}
pub fn emails(&self) -> impl Iterator<Item = &str> {
self.candidate_emails.iter().map(String::as_str)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Field {
pub label: String,
pub value: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub kind: String,
}
pub const FIELD_KIND_DATE: &str = "date";
pub const FIELD_KIND_TABLE: &str = "table";
#[derive(Serialize)]
struct TableData {
columns: Vec<String>,
rows: Vec<Vec<String>>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Action {
pub label: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub url: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub op: String,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub params: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub fields: Vec<ActionField>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub confirm: String,
}
impl Action {
pub fn link(label: impl Into<String>, url: impl Into<String>) -> Self {
Self { label: label.into(), url: url.into(), ..Default::default() }
}
pub fn run(label: impl Into<String>, op: impl Into<String>) -> Self {
Self { label: label.into(), op: op.into(), ..Default::default() }
}
pub fn param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.params.insert(key.into(), value.into());
self
}
pub fn input(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_TEXT);
f.required = required;
self.fields.push(f);
self
}
pub fn textarea(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_TEXTAREA);
f.required = required;
self.fields.push(f);
self
}
pub fn select(mut self, key: impl Into<String>, label: impl Into<String>, required: bool, options_op: impl Into<String>) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_SELECT);
f.required = required;
f.options_op = options_op.into();
self.fields.push(f);
self
}
pub fn multiselect(mut self, key: impl Into<String>, label: impl Into<String>, required: bool, options_op: impl Into<String>) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_MULTISELECT);
f.required = required;
f.options_op = options_op.into();
self.fields.push(f);
self
}
pub fn number(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_NUMBER);
f.required = required;
self.fields.push(f);
self
}
pub fn date(mut self, key: impl Into<String>, label: impl Into<String>, required: bool) -> Self {
let mut f = FieldSpec::new(key, label, FIELD_DATE);
f.required = required;
self.fields.push(f);
self
}
pub fn placeholder(mut self, hint: impl Into<String>) -> Self {
if let Some(last) = self.fields.last_mut() {
last.placeholder = hint.into();
}
self
}
pub fn depends_on(mut self, field_key: impl Into<String>) -> Self {
if let Some(last) = self.fields.last_mut() {
last.depends_on = field_key.into();
}
self
}
pub fn options(mut self, options: Vec<FieldOption>) -> Self {
if let Some(last) = self.fields.last_mut() {
last.options = options;
}
self
}
pub fn reloads_form(mut self) -> Self {
if let Some(last) = self.fields.last_mut() {
last.reloads_form = true;
}
self
}
pub fn rich_text_format(mut self, format: impl Into<String>) -> Self {
if let Some(last) = self.fields.last_mut() {
last.rich_text_format = format.into();
}
self
}
pub fn confirm(mut self, question: impl Into<String>) -> Self {
self.confirm = question.into();
self
}
}
pub const FIELD_TEXT: &str = "text";
pub const FIELD_TEXTAREA: &str = "textarea";
pub const FIELD_SELECT: &str = "select";
pub const FIELD_NUMBER: &str = "number";
pub const FIELD_MULTISELECT: &str = "multiselect";
pub const FIELD_DATE: &str = "date";
pub const RICH_TEXT_FORMAT_MARKDOWN: &str = "markdown";
pub const RICH_TEXT_FORMAT_JIRA_WIKI: &str = "jira_wiki";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldSpec {
pub key: String,
pub label: String,
pub kind: String,
#[serde(default, skip_serializing_if = "is_false")]
pub required: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub placeholder: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub options_op: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub depends_on: String,
#[serde(default, skip_serializing_if = "is_false")]
pub numeric: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub options: Vec<FieldOption>,
#[serde(default, skip_serializing_if = "is_false")]
pub reloads_form: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub rich_text_format: String,
}
impl FieldSpec {
fn new(key: impl Into<String>, label: impl Into<String>, kind: &str) -> Self {
Self {
key: key.into(),
label: label.into(),
kind: kind.into(),
required: false,
placeholder: String::new(),
options_op: String::new(),
depends_on: String::new(),
numeric: false,
options: Vec::new(),
reloads_form: false,
rich_text_format: String::new(),
}
}
pub fn text(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_TEXT)
}
pub fn textarea(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_TEXTAREA)
}
pub fn select(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_SELECT)
}
pub fn multiselect(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_MULTISELECT)
}
pub fn number(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_NUMBER)
}
pub fn date(key: impl Into<String>, label: impl Into<String>) -> Self {
Self::new(key, label, FIELD_DATE)
}
pub fn required(mut self) -> Self {
self.required = true;
self
}
pub fn placeholder(mut self, hint: impl Into<String>) -> Self {
self.placeholder = hint.into();
self
}
pub fn options_op(mut self, op: impl Into<String>) -> Self {
self.options_op = op.into();
self
}
pub fn depends_on(mut self, field_key: impl Into<String>) -> Self {
self.depends_on = field_key.into();
self
}
pub fn numeric(mut self) -> Self {
self.numeric = true;
self
}
pub fn options(mut self, options: Vec<FieldOption>) -> Self {
self.options = options;
self
}
pub fn reloads_form(mut self) -> Self {
self.reloads_form = true;
self
}
pub fn rich_text_format(mut self, format: impl Into<String>) -> Self {
self.rich_text_format = format.into();
self
}
}
pub type ActionField = FieldSpec;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldOption {
pub value: String,
pub label: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Actor {
#[serde(default)]
pub name: String,
#[serde(default)]
pub email: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct TicketRef {
#[serde(default)]
pub id: String,
#[serde(default)]
pub number: i64,
#[serde(default)]
pub subject: String,
#[serde(default)]
pub url: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct ActionRequest {
#[serde(default)]
pub params: BTreeMap<String, String>,
#[serde(default)]
pub inputs: BTreeMap<String, String>,
#[serde(default)]
pub actor: Actor,
#[serde(default)]
pub ticket: TicketRef,
#[serde(default)]
pub occurred_at: String,
}
impl ActionRequest {
pub fn param(&self, key: &str) -> Result<&str, OpError> {
match self.params.get(key).map(String::as_str).filter(|v| !v.is_empty()) {
Some(v) => Ok(v),
None => Err(OpError::Other(format!("action is missing the {key:?} parameter"))),
}
}
pub fn opt_param(&self, key: &str) -> Option<&str> {
self.params.get(key).map(String::as_str).filter(|v| !v.is_empty())
}
pub fn input(&self, key: &str) -> Result<&str, OpError> {
match self.inputs.get(key).map(|v| v.trim()).filter(|v| !v.is_empty()) {
Some(v) => Ok(v),
None => Err(OpError::Other(format!("{key:?} is required"))),
}
}
pub fn opt_input(&self, key: &str) -> Option<&str> {
self.inputs.get(key).map(|v| v.trim()).filter(|v| !v.is_empty())
}
pub fn signature(&self) -> String {
let who = if self.actor.name.is_empty() { self.actor.email.clone() } else { self.actor.name.clone() };
let mut out = format!("Logged by {who}");
if !self.actor.email.is_empty() && !self.actor.name.is_empty() {
out.push_str(&format!(" <{}>", self.actor.email));
}
if self.ticket.number > 0 {
out.push_str(&format!(" from support ticket #{}", self.ticket.number));
}
if !self.ticket.subject.is_empty() {
out.push_str(&format!(" — {}", self.ticket.subject));
}
if !self.occurred_at.is_empty() {
out.push_str(&format!(" · {}", self.occurred_at));
}
out
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ActionOutcome {
pub message: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub url: String,
}
impl ActionOutcome {
pub fn new(message: impl Into<String>) -> Self {
Self { message: message.into(), url: String::new() }
}
pub fn url(mut self, url: impl Into<String>) -> Self {
self.url = url.into();
self
}
}
pub type ActionResult = Result<ActionOutcome, OpError>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextBlock {
pub title: String,
#[serde(default)]
pub fields: Vec<Field>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub actions: Vec<Action>,
}
impl ContextBlock {
pub fn new(title: impl Into<String>) -> Self {
Self { title: title.into(), fields: Vec::new(), actions: Vec::new() }
}
pub fn field(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
self.fields.push(Field { label: label.into(), value: value.into(), kind: String::new() });
self
}
pub fn field_opt(self, label: impl Into<String>, value: Option<impl Into<String>>) -> Self {
match value {
Some(v) => {
let v: String = v.into();
if v.trim().is_empty() {
self
} else {
self.field(label, v)
}
}
None => self,
}
}
pub fn field_date(mut self, label: impl Into<String>, value: impl Into<String>) -> Self {
self.fields.push(Field { label: label.into(), value: value.into(), kind: FIELD_KIND_DATE.into() });
self
}
pub fn field_date_opt(self, label: impl Into<String>, value: Option<impl Into<String>>) -> Self {
match value {
Some(v) => {
let v: String = v.into();
if v.trim().is_empty() {
self
} else {
self.field_date(label, v)
}
}
None => self,
}
}
pub fn field_table(mut self, label: impl Into<String>, columns: Vec<String>, rows: Vec<Vec<String>>) -> Self {
let value = serde_json::to_string(&TableData { columns, rows }).unwrap_or_default();
self.fields.push(Field { label: label.into(), value, kind: FIELD_KIND_TABLE.into() });
self
}
pub fn action(mut self, label: impl Into<String>, url: impl Into<String>) -> Self {
self.actions.push(Action::link(label, url));
self
}
pub fn run(mut self, action: Action) -> Self {
self.actions.push(action);
self
}
pub fn is_empty(&self) -> bool {
self.fields.is_empty() && self.actions.is_empty()
}
}
pub type ContextResult = Result<Vec<ContextBlock>, OpError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn block_serializes_to_the_go_wire_shape() {
let block = ContextBlock::new("Contact")
.field("Name", "Ada Lovelace")
.field_opt("Phone", Some("+44 20 7946 0958"))
.field_opt("Fax", None::<String>)
.field_opt("Blank", Some(" "))
.action("Open in CRM", "https://crm.example.com/1");
let got = serde_json::to_value(&block).expect("serialize");
let want = serde_json::json!({
"title": "Contact",
"fields": [
{"label": "Name", "value": "Ada Lovelace"},
{"label": "Phone", "value": "+44 20 7946 0958"},
],
"actions": [{"label": "Open in CRM", "url": "https://crm.example.com/1"}],
});
assert_eq!(got, want);
}
#[test]
fn a_date_field_carries_its_kind_and_a_plain_one_omits_it() {
let block = ContextBlock::new("Issue")
.field("Key", "PROJ-1")
.field_date("Updated", "2026-08-15T03:52:49Z")
.field_date_opt("Due", None::<String>);
let got = serde_json::to_value(&block).expect("serialize");
let want = serde_json::json!({
"title": "Issue",
"fields": [
{"label": "Key", "value": "PROJ-1"},
{"label": "Updated", "value": "2026-08-15T03:52:49Z", "kind": "date"},
],
});
assert_eq!(got, want);
}
#[test]
fn empty_actions_are_omitted() {
let got = serde_json::to_value(ContextBlock::new("Contact").field("a", "b")).expect("serialize");
assert!(got.get("actions").is_none(), "actions must be omitted when empty, got {got}");
}
#[test]
fn request_decodes_the_host_input() {
let req: ContextRequest =
serde_json::from_str(r#"{"ticket_type_id":"9f1c","candidate_emails":["a@x.com","b@x.com"]}"#)
.expect("decode");
assert_eq!(req.ticket_type_id.as_deref(), Some("9f1c"));
assert_eq!(req.primary_email(), Some("a@x.com"));
assert_eq!(req.emails().collect::<Vec<_>>(), vec!["a@x.com", "b@x.com"]);
}
#[test]
fn a_link_action_keeps_the_original_two_key_shape() {
let got = serde_json::to_value(Action::link("Open in CRM", "https://crm.example.com/1")).expect("serialize");
assert_eq!(got, serde_json::json!({"label": "Open in CRM", "url": "https://crm.example.com/1"}));
}
#[test]
fn an_executable_action_serializes_to_the_go_wire_shape() {
let action = Action::run("Log a note", "log_note")
.param("contact_id", "701")
.textarea("body", "Note", true)
.placeholder("What should the salesperson know?")
.confirm("This writes into the CRM. Continue?");
let got = serde_json::to_value(&action).expect("serialize");
let want = serde_json::json!({
"label": "Log a note",
"op": "log_note",
"params": {"contact_id": "701"},
"fields": [{
"key": "body",
"label": "Note",
"kind": "textarea",
"required": true,
"placeholder": "What should the salesperson know?",
}],
"confirm": "This writes into the CRM. Continue?",
});
assert_eq!(got, want);
}
#[test]
fn action_request_decodes_and_signs() {
let req: ActionRequest = serde_json::from_str(
r#"{"params":{"contact_id":"701"},"inputs":{"body":" call them back "},
"actor":{"name":"Ada Lovelace","email":"ada@help.example"},
"ticket":{"number":42,"subject":"Renewal question","url":"https://help.example/tickets/1"},
"occurred_at":"2026-08-11T09:30:00Z"}"#,
)
.expect("decode");
assert_eq!(req.param("contact_id").expect("param"), "701");
assert_eq!(req.input("body").expect("input"), "call them back");
assert!(req.opt_param("deal_id").is_none());
assert_eq!(
req.signature(),
"Logged by Ada Lovelace <ada@help.example> from support ticket #42 — Renewal question · 2026-08-11T09:30:00Z"
);
}
#[test]
fn a_blank_required_input_is_refused() {
let req = ActionRequest { inputs: BTreeMap::from([("body".into(), " ".into())]), ..Default::default() };
assert!(req.input("body").is_err());
assert!(req.opt_input("body").is_none());
}
#[test]
fn request_decodes_without_a_ticket_type() {
let req: ContextRequest = serde_json::from_str(r#"{"candidate_emails":[]}"#).expect("decode");
assert!(req.ticket_type_id.is_none());
assert_eq!(req.primary_email(), None);
}
}