use serde_json::Value;
pub const PERIODS: [&str; 6] = ["day", "week", "month", "quarter", "year", "once"];
const AMOUNTS: [&str; 3] = ["max", "budget", "approve-above"];
pub struct Problem {
pub code: &'static str,
pub message: String,
}
fn text(v: Option<&Value>) -> Option<String> {
let s = match v? {
Value::Null => return None,
Value::String(s) => s.clone(),
Value::Array(a) => a.iter().map(plain).collect::<Vec<_>>().join(","),
other => plain(other),
};
(!s.is_empty()).then_some(s)
}
fn plain(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
pub fn list(v: Option<&Value>) -> Vec<String> {
match v {
Some(Value::Array(a)) => a.iter().map(|x| plain(x).trim().to_string()).collect(),
Some(Value::String(s)) => s.split(',').map(|x| x.trim().to_string()).collect(),
None | Some(Value::Null) => Vec::new(),
Some(other) => vec![plain(other).trim().to_string()],
}
}
fn pending(v: &str) -> bool {
let b = v.as_bytes();
let mut i = 0;
while i + 2 < b.len() {
if b[i] == b'$' && b[i + 1] == b'{' {
let rest = &v[i + 2..];
if let Some(end) = rest.find('}') {
let name = &rest[..end];
let mut chars = name.chars();
if chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
{
return true;
}
}
}
i += 1;
}
false
}
fn decimal(v: &str) -> bool {
let (int, frac) = match v.split_once('.') {
Some((i, f)) => (i, Some(f)),
None => (v, None),
};
!int.is_empty()
&& int.bytes().all(|c| c.is_ascii_digit())
&& frac.is_none_or(|f| (1..=18).contains(&f.len()) && f.bytes().all(|c| c.is_ascii_digit()))
}
fn currency(v: &str) -> bool {
v.len() == 3 && v.bytes().all(|c| c.is_ascii_uppercase())
}
fn domain(v: &str) -> bool {
if v.is_empty() || v.len() > 253 {
return false;
}
let labels: Vec<&str> = v.split('.').collect();
if labels.len() < 2 {
return false;
}
let (last, rest) = labels.split_last().unwrap();
let label = |l: &str| {
let b = l.as_bytes();
!b.is_empty()
&& b.len() <= 63
&& b[0].is_ascii_alphanumeric()
&& b[b.len() - 1].is_ascii_alphanumeric()
&& b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
};
let lb = last.as_bytes();
rest.iter().all(|l| label(l))
&& !lb.is_empty()
&& lb.len() <= 63
&& lb[0].is_ascii_alphabetic()
&& lb.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
}
fn merchant(v: &str) -> bool {
let b = v.as_bytes();
!b.is_empty() && b.len() <= 128 && b[0].is_ascii_alphanumeric() && b.iter().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b':' | b'-'))
}
fn is_date(v: &str) -> bool {
let b = v.as_bytes();
b.len() == 10 && b[4] == b'-' && b[7] == b'-' && b.iter().enumerate().all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit())
}
fn days(y: i64, m: i64, d: i64) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = if y >= 0 { y } else { y - 399 } / 400;
let yoe = y - era * 400;
let mp = (m + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
fn num(s: &str) -> Option<i64> {
(!s.is_empty() && s.bytes().all(|c| c.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}
pub fn instant(v: &str, until: bool) -> Option<i64> {
if v.len() < 10 || !is_date(&v[..10]) {
return None;
}
let (y, mo, d) = (num(&v[0..4])?, num(&v[5..7])?, num(&v[8..10])?);
if !(1..=12).contains(&mo) || !(1..=31).contains(&d) {
return None;
}
let day_ms = days(y, mo, d) * 86_400_000;
if v.len() == 10 {
return Some(day_ms + if until { 86_400_000 } else { 0 });
}
let t = &v[10..];
let t = t.strip_prefix('T').or_else(|| t.strip_prefix('t'))?;
if t.len() < 5 || t.as_bytes()[2] != b':' {
return None;
}
let (h, mi) = (num(&t[0..2])?, num(&t[3..5])?);
let mut rest = &t[5..];
let mut s = 0;
let mut ms = 0;
if let Some(r) = rest.strip_prefix(':') {
if r.len() < 2 {
return None;
}
s = num(&r[0..2])?;
rest = &r[2..];
if let Some(r) = rest.strip_prefix('.') {
let n = r.bytes().take_while(u8::is_ascii_digit).count();
if n == 0 {
return None;
}
let frac = &r[..n];
ms = num(&format!("{:0<3}", &frac[..n.min(3)]))?;
rest = &r[n..];
}
}
let offset = match rest {
"" => 0,
"Z" | "z" => 0,
o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) && o.as_bytes()[3] == b':' => {
let m = num(&o[1..3])? * 60 + num(&o[4..6])?;
if o.starts_with('+') { -m } else { m }
}
_ => return None,
};
if h > 23 || mi > 59 || s > 60 {
return None;
}
Some(day_ms + ((h * 60 + mi + offset) * 60 + s) * 1000 + ms)
}
fn amount(v: &str) -> Option<f64> {
decimal(v).then(|| v.parse().ok()).flatten()
}
pub fn problems(a: &serde_json::Map<String, Value>) -> Vec<Problem> {
let mut out = Vec::new();
let mut add = |code: &'static str, message: String| out.push(Problem { code, message });
if text(a.get("budget")).is_none() {
add("allowance-unbounded", "an allowance needs budget=… (it would limit nothing)".into());
}
let mut vals = [None, None, None];
for (i, k) in AMOUNTS.iter().enumerate() {
let Some(v) = text(a.get(*k)) else { continue };
if pending(&v) {
continue;
}
if !decimal(&v) {
add("allowance-amount-invalid", format!("{k}={v} is not a decimal ≥ 0 with at most 18 fractional digits"));
continue;
}
vals[i] = amount(&v);
}
let [max, budget, above] = vals;
match text(a.get("currency")) {
None => add("allowance-currency-invalid", "currency=… (an ISO 4217 code) names what its amounts are in".into()),
Some(c) if !pending(&c) && !currency(&c) => add("allowance-currency-invalid", format!("currency={c} is not an uppercase ISO 4217 code")),
_ => {}
}
if let Some(per) = text(a.get("per"))
&& !pending(&per)
&& !PERIODS.contains(&per.as_str())
{
add("allowance-per-unknown", format!("per={per} is one of {}", PERIODS.join(", ")));
}
if let Some(times) = text(a.get("times"))
&& !pending(×)
&& !(times.bytes().all(|c| c.is_ascii_digit()) && !times.starts_with('0') && !times.is_empty())
{
add("allowance-amount-invalid", format!("times={times} is a whole number ≥ 1"));
}
if let (Some(m), Some(b)) = (max, budget)
&& m > b
{
add("allowance-max-over-budget", format!("max ({m}) is above budget ({b})"));
}
if let (Some(x), Some(m)) = (above, max.or(budget))
&& x > m
{
add("allowance-approve-above-over-max", format!("approve-above ({x}) is above {} ({m})", if max.is_some() { "max" } else { "budget" }));
}
let from = text(a.get("from"));
let until = text(a.get("until"));
for (k, v, edge) in [("from", &from, false), ("until", &until, true)] {
if let Some(v) = v
&& !pending(v)
&& instant(v, edge).is_none()
{
add("allowance-amount-invalid", format!("{k}={v} is a date or a date-time (RFC 3339)"));
}
}
if let (Some(f), Some(u)) = (&from, &until)
&& !pending(f)
&& !pending(u)
&& let (Some(fi), Some(ui)) = (instant(f, false), instant(u, true))
&& ui <= fi
{
add("allowance-window-inverted", format!("until ({u}) is before from ({f})"));
}
if a.contains_key("payees") {
let ps = list(a.get("payees"));
if ps.is_empty() || ps.iter().any(|p| if let Some(r) = p.strip_prefix('&') { r.is_empty() } else { !(domain(p) || merchant(p)) }) {
add("allowance-payees-invalid", format!("payees={}: each is a domain, a merchant id or an &service reference", ps.join(",")));
}
}
out
}
fn decimal_of(v: Option<&Value>) -> Option<f64> {
text(v).filter(|s| decimal(s)).and_then(|s| s.parse().ok())
}
fn set(v: Option<&Value>) -> Vec<String> {
list(v).into_iter().filter(|s| !s.is_empty()).collect()
}
fn subset(a: &[String], b: &[String]) -> bool {
a.iter().all(|x| b.contains(x))
}
pub fn widenings(before: &serde_json::Map<String, Value>, after: &serde_json::Map<String, Value>) -> Vec<&'static str> {
let mut out = Vec::new();
for k in ["max", "budget", "approve-above"] {
if let Some(b) = decimal_of(before.get(k))
&& decimal_of(after.get(k)).is_none_or(|x| x > b)
{
out.push(k);
}
}
if let Some(b) = decimal_of(before.get("times"))
&& decimal_of(after.get("times")).is_none_or(|x| x > b)
{
out.push("times");
}
let per = |m: &serde_json::Map<String, Value>| text(m.get("per")).unwrap_or_else(|| "once".into());
if per(before) != per(after) {
out.push("per");
}
if text(before.get("currency")) != text(after.get("currency")) {
out.push("currency");
}
if !subset(&set(after.get("wallet")), &set(before.get("wallet"))) {
out.push("wallet");
}
for k in ["payees", "categories"] {
if before.contains_key(k) && (!after.contains_key(k) || !subset(&set(after.get(k)), &set(before.get(k)))) {
out.push(k);
}
}
let at = |m: &serde_json::Map<String, Value>, k: &str, until: bool| text(m.get(k)).and_then(|v| instant(&v, until));
if text(before.get("from")).is_some() && at(after, "from", false).is_none_or(|a| at(before, "from", false).is_some_and(|b| a < b)) {
out.push("from");
}
if text(before.get("until")).is_some() && at(after, "until", true).is_none_or(|a| at(before, "until", true).is_some_and(|b| a > b)) {
out.push("until");
}
if let Some(b) = text(before.get("approver"))
&& text(after.get("approver")).as_deref() != Some(b.as_str())
{
out.push("approver");
}
out
}
pub fn sentence(a: &serde_json::Map<String, Value>, title: Option<&str>, id: Option<&str>) -> String {
let mut parts: Vec<String> = Vec::new();
let cur = text(a.get("currency")).unwrap_or_default();
let wallets = set(a.get("wallet"));
if !wallets.is_empty() {
parts.push(format!("pay from {}{}", wallets.join(", "), if cur.is_empty() { String::new() } else { format!(" in {cur}") }));
}
let per = text(a.get("per")).unwrap_or_else(|| "once".into());
let span = if per == "once" { "in total".to_string() } else { format!("per calendar {per} (UTC)") };
let mut limits = Vec::new();
if let Some(m) = text(a.get("max")) {
limits.push(format!("at most {m} per payment"));
}
if let Some(b) = text(a.get("budget")) {
limits.push(format!("{b} {span}"));
}
if !limits.is_empty() {
parts.push(limits.join(" and "));
}
if let Some(t) = text(a.get("times")) {
parts.push(format!("at most {t} payments {}", if per == "once" { "in total".to_string() } else { format!("per {per}") }));
}
if a.contains_key("payees") {
parts.push(format!("only to {}", list(a.get("payees")).join(", ")));
}
if a.contains_key("categories") {
parts.push(format!("only for {}", list(a.get("categories")).join(", ")));
}
if let Some(above) = text(a.get("approve-above")) {
let who = text(a.get("approver")).unwrap_or_else(|| "the host's approver".into());
parts.push(format!("ask {who} before any payment above {above}"));
}
let from = text(a.get("from"));
let until = text(a.get("until"));
if from.is_some() || until.is_some() {
let mut w = Vec::new();
if let Some(f) = from {
w.push(format!("from {f}"));
}
if let Some(u) = until {
w.push(format!("{} {u}", if is_date(&u) { "through" } else { "until" }));
}
parts.push(format!("{} (UTC)", w.join(" ")));
}
format!(
"Allowance {}{}: {}.",
title.map(|t| format!("\"{t}\" ")).unwrap_or_default(),
id.map(|i| format!("(#{i})")).unwrap_or_default(),
parts.join("; ")
)
}
pub fn protocol_ok(v: &str) -> bool {
let short = |s: &str| {
let b = s.as_bytes();
!b.is_empty() && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')
};
let part = |s: &str| !s.is_empty() && s.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-');
let versions = |s: &str| !s.is_empty() && s.split(',').all(|x| !x.is_empty() && x.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-'));
let mut segs = v.split('/');
let first = segs.next().unwrap_or("");
if first.contains('.') {
let labels: Vec<&str> = first.split('.').collect();
if labels.len() < 2 || !labels.iter().all(|l| part(l)) {
return false;
}
let Some(name) = segs.next() else { return false };
if !part(name) {
return false;
}
match (segs.next(), segs.next()) {
(None, _) => true,
(Some(vs), None) => versions(vs),
_ => false,
}
} else {
if !short(first) {
return false;
}
match (segs.next(), segs.next()) {
(None, _) => true,
(Some(vs), None) => versions(vs),
_ => false,
}
}
}
pub const PARAMETER_KEYS: [&str; 8] = ["max", "budget", "approve-above", "times", "from", "until", "currency", "per"];
pub fn unresolved(a: &serde_json::Map<String, Value>) -> Vec<Problem> {
PARAMETER_KEYS
.iter()
.filter_map(|k| match a.get(*k) {
Some(Value::String(v)) if pending(v) => Some(Problem {
code: "allowance-amount-invalid",
message: format!("{k}={v} has no value: its parameter is not given and has no default"),
}),
_ => None,
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Allowance {
pub id: Option<String>,
pub title: Option<String>,
pub wallets: Vec<String>,
pub currency: Option<String>,
pub max: Option<String>,
pub budget: Option<String>,
pub per: String,
pub times: Option<u64>,
pub payees: Option<Vec<String>>,
pub categories: Option<Vec<String>>,
pub from: Option<String>,
pub until: Option<String>,
pub approve_above: Option<String>,
pub approver: Option<String>,
}
pub fn typed(a: &serde_json::Map<String, Value>) -> Allowance {
let t = |k: &str| text(a.get(k));
let opt_list = |k: &str| a.contains_key(k).then(|| list(a.get(k)).into_iter().filter(|x| !x.is_empty()).collect());
Allowance {
id: t("id"),
title: t("title"),
wallets: list(a.get("wallet")).into_iter().filter(|x| !x.is_empty()).collect(),
currency: t("currency"),
max: t("max"),
budget: t("budget"),
per: t("per").unwrap_or_else(|| "once".into()),
times: t("times").filter(|v| !v.starts_with('0') && v.bytes().all(|c| c.is_ascii_digit())).and_then(|v| v.parse().ok()),
payees: opt_list("payees"),
categories: opt_list("categories"),
from: t("from"),
until: t("until"),
approve_above: t("approve-above"),
approver: t("approver"),
}
}