Files
FiscusPublic/crates/fiscus-capture/src/shortcut.rs
T

121 lines
4.3 KiB
Rust

//! The iPhone Shortcut post (`POST /inbox`). We write the Shortcut, so the shape is ours:
//! `{"amount", "merchant", "card", "time"}` and an optional `"currency": "CZK"`, nothing else.
use crate::{amount, card_ok, merchant_ok, Capture};
use fiscus_ledger::{Date, Timestamp};
use serde::Deserialize;
use serde_json::value::RawValue;
/// The largest body the inbox reads.
pub const MAX_BODY: usize = 4096;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CaptureError {
#[error("the post is larger than 4 KiB")]
TooLarge,
#[error("the post is not a JSON object with exactly amount, merchant, card and time")]
Malformed,
#[error("the amount is not a positive amount in CZK")]
Amount,
#[error("the currency is not CZK")]
Currency,
#[error("the merchant must be 1-200 characters without control characters")]
Merchant,
#[error("the card name must be at most 60 characters without control characters")]
Card,
#[error("the time is not ISO 8601 with an offset (2026-11-03T14:05:00+01:00)")]
Time,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Post<'a> {
#[serde(borrow)]
amount: &'a RawValue,
merchant: String,
card: String,
time: String,
currency: Option<String>,
}
/// One post → one capture, or the first thing wrong with it.
pub fn parse(body: &[u8]) -> Result<Capture, CaptureError> {
if body.len() > MAX_BODY {
return Err(CaptureError::TooLarge);
}
let post: Post = serde_json::from_slice(body).map_err(|_| CaptureError::Malformed)?;
let raw = post.amount.get();
let text: String = if raw.starts_with('"') {
serde_json::from_str(raw).map_err(|_| CaptureError::Amount)?
} else if raw.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
raw.to_string()
} else {
return Err(CaptureError::Amount);
};
let amount = amount::parse_positive(&text).ok_or(CaptureError::Amount)?;
if post.currency.as_deref().is_some_and(|c| c != "CZK") {
return Err(CaptureError::Currency);
}
if !merchant_ok(&post.merchant) {
return Err(CaptureError::Merchant);
}
if !card_ok(&post.card) {
return Err(CaptureError::Card);
}
let (date, at) = parse_time(&post.time).ok_or(CaptureError::Time)?;
let card = post.card.trim();
Ok(Capture {
amount: amount.checked_neg().map_err(|_| CaptureError::Amount)?,
date,
at,
merchant: post.merchant.trim().to_string(),
card: (!card.is_empty()).then(|| card.to_string()),
})
}
fn num(s: &str) -> Option<u32> {
(!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())).then(|| s.parse().ok()).flatten()
}
/// `YYYY-MM-DDTHH:MM[:SS[.fff]](Z|±HH:MM)` → the local date written in it, and the instant.
pub fn parse_time(s: &str) -> Option<(Date, Timestamp)> {
let (date, rest) = s.split_once('T')?;
if date.len() != 10 || &date[4..5] != "-" || &date[7..8] != "-" {
return None;
}
let day = Date::from_ymd(num(&date[..4])? as i32, num(&date[5..7])?, num(&date[8..])?)?;
let (clock, offset_min) = if let Some(c) = rest.strip_suffix('Z') {
(c, 0i64)
} else {
let i = rest.rfind(['+', '-'])?;
let (c, off) = rest.split_at(i);
let sign = if off.starts_with('-') { -1 } else { 1 };
let off = &off[1..];
if off.len() != 5 || &off[2..3] != ":" {
return None;
}
let (h, m) = (num(&off[..2])?, num(&off[3..])?);
if h > 14 || m > 59 {
return None;
}
(c, sign * (h as i64 * 60 + m as i64))
};
let (hms, millis) = match clock.split_once('.') {
Some((hms, frac)) if (1..=3).contains(&frac.len()) => (hms, num(frac)? as i64 * 10i64.pow(3 - frac.len() as u32)),
Some(_) => return None,
None => (clock, 0),
};
let parts: Vec<&str> = hms.split(':').collect();
if !(2..=3).contains(&parts.len()) || parts.iter().any(|p| p.len() != 2) {
return None;
}
let (h, m) = (num(parts[0])?, num(parts[1])?);
let sec = if parts.len() == 3 { num(parts[2])? } else { 0 };
if h > 23 || m > 59 || sec > 59 {
return None;
}
let local_s = day.days() as i64 * 86_400 + h as i64 * 3600 + m as i64 * 60 + sec as i64;
let utc_ms = (local_s - offset_min * 60) * 1000 + millis;
Some((day, Timestamp(utc_ms)))
}