use std::collections::BTreeMap;
use serde_json::Value;
use super::capsule::*;
use super::check::Error;
use super::names::*;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Decide {
pub disposition: Disposition,
pub effect_type: String,
pub irreversibility_class: String,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StepInput {
pub deal_id: String,
pub seq: i64,
pub operator: String,
pub developer: String,
pub at: i64,
pub parent: Option<Chain>,
pub settlement: Option<Value>,
pub decide: Option<Decide>,
pub local: String,
pub amount: String,
pub currency: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StepHeader {
pub record_type: String,
pub epistemic_type: String,
pub committed_at: String,
pub subject_ref: String,
pub cites: Vec<String>,
pub fields: BTreeMap<String, String>,
}
pub fn step_capsule(input: &StepInput) -> Result<(Capsule, StepHeader), Error> {
if input.deal_id.is_empty() || input.seq < 1 {
return Err(Error::Invalid(
"a step needs a deal id and a seq >= 1".into(),
));
}
if input.developer.is_empty() {
return Err(Error::Invalid(
"a step needs the producer's developer name".into(),
));
}
if let Some(p) = &input.parent {
if p.relation != RELATION_FOLLOWS && p.relation != RELATION_CONFIRMS {
return Err(Error::Invalid(format!(
"chain relation {} is not follows or confirms",
super::check::go_q(&p.relation)
)));
}
}
let at = rfc3339_seconds(input.at);
let mut c = Capsule {
action_id: format!("{}/{}", input.deal_id, input.seq),
action_type: ACTION_TYPE_FYI.into(),
operator: input.operator.clone(),
developer: input.developer.clone(),
timestamp: at.clone(),
disposition: None,
effect: None,
chain: input.parent.clone(),
extensions: Vec::new(),
};
if let Some(s) = &input.settlement {
c.extensions.push(Extension {
name: "settlement".into(),
value: s.clone(),
});
}
c.extensions.push(Extension {
name: DEAL_ID_MEMBER.into(),
value: Value::String(input.deal_id.clone()),
});
if let Some(d) = &input.decide {
c.action_type = ACTION_TYPE_DECIDE.into();
c.disposition = Some(d.disposition.clone());
c.effect = Some(Effect {
effect_type: d.effect_type.clone(),
status: EFFECT_DISPATCHED.into(),
irreversibility_class: d.irreversibility_class.clone(),
effect_attestation: ATTESTATION_RUNTIME_CLAIMED.into(),
});
}
let h = StepHeader {
record_type: STEP_RECORD_TYPE.into(),
epistemic_type: EPISTEMIC_PRODUCER_CLAIM.into(),
committed_at: at,
subject_ref: c.action_id.clone(),
cites: input
.parent
.iter()
.map(|p| p.parent_capsule_id.clone())
.collect(),
fields: BTreeMap::from([
(LOCAL_FIELD.to_string(), input.local.clone()),
(AMOUNT_FIELD.to_string(), input.amount.clone()),
(CURRENCY_FIELD.to_string(), input.currency.clone()),
]),
};
Ok((c, h))
}