Skip to main content

file_expense_receipt/
file_expense_receipt.rs

1//! File an expense from a receipt that lives behind a URL.
2//!
3//! The two other examples are GraphQL actions. This one is the whole surface in
4//! one handler: `settings` for the policy the tenant configured, `storage` for
5//! the file, `ai` for what the file says, and `graphql` for the record — one `?`
6//! between each and one `Error` out of all of them.
7//!
8//! Two things to take from it. The order is deliberate: the store is addressed
9//! by content, so putting the file in first is the step that can be repeated
10//! without filing the expense twice, and every refusal after it says so. And a
11//! `DocumentHandle` travels: `storage` answers with one, `ai` reads it, the
12//! mutation writes it into the record's `:document` field, and the action hands
13//! the same handle back.
14
15use simpleplatform_sdk::prelude::*;
16
17/// The app the expense table and the policy both belong to.
18const APP_ID: &str = "dev.simple.expenses";
19
20/// The advertised input: who the expense is for, and where the receipt is.
21///
22/// Both constraints below are ones the handler enforces in its first few
23/// lines, which is what makes them worth writing: a blank member is refused
24/// there, so `length(min = 1)` says the same thing to a caller before it sends
25/// anything. `format` says what kind of string the address is, and the
26/// approval limit and the currency are deliberately absent — they are what the
27/// tenant configured, read from `settings` at run time, so they are not this
28/// payload's to declare.
29#[derive(Deserialize, Schema)]
30struct Input {
31    /// The employee the expense is filed against.
32    #[simple(length(min = 1))]
33    employee_id: String,
34
35    /// Where the receipt is read from.
36    #[simple(length(min = 1), format = "uri")]
37    receipt_url: String,
38}
39
40/// What this tenant configured, rather than what this action assumes.
41#[derive(Deserialize)]
42struct Policy {
43    approval_limit: f64,
44    currency: String,
45}
46
47/// What the receipt says, read out of the file against the schema below.
48#[derive(Deserialize)]
49struct Receipt {
50    merchant: String,
51    currency: String,
52    total: f64,
53}
54
55#[derive(Deserialize)]
56struct Filed {
57    expense: Expense,
58}
59
60#[derive(Deserialize)]
61struct Expense {
62    id: String,
63}
64
65// The output type needs `Serialize`, and that is all the SDK asks of it.
66// `Debug` is here for the tests below, where `Result::unwrap_err` wants the
67// `Ok` type to carry it.
68#[derive(Debug, Serialize)]
69struct Output {
70    expense_id: String,
71    merchant: String,
72    total: f64,
73    receipt: DocumentHandle,
74}
75
76const FILE_EXPENSE: &str = r#"
77    mutation FileExpense($employee: ID!, $merchant: String!, $total: numeric!, $receipt: jsonb!) {
78      expense: insert_expenses__expense_one(
79        object: {
80          employee_id: $employee
81          merchant: $merchant
82          total: $total
83          receipt: $receipt
84          status: "submitted"
85        }
86      ) {
87        id
88      }
89    }"#;
90
91fn main() {
92    simple::run(handler)
93}
94
95/// File an expense for an employee from a receipt held at an address.
96///
97/// The receipt is stored first and read afterwards, so the merchant, the
98/// currency and the total on the expense are the ones on the file rather than
99/// ones supplied alongside it. A receipt in a currency this app does not file
100/// in, or a total over the approval limit the tenant configured, is refused
101/// with the file already stored and the expense not filed.
102///
103/// @tool
104/// @shortdesc File an expense from a receipt, reading its merchant, currency and total out of the file.
105/// @usewhen An employee has a receipt that should become a filed expense.
106fn handler(request: Request<Input>) -> Result<Output, Error> {
107    let employee = request.data.employee_id.trim();
108    let receipt_url = request.data.receipt_url.trim();
109
110    if employee.is_empty() {
111        return Err(Error::invalid("An expense is filed against an employee.")
112            .hint("Pass the id of the employee the receipt belongs to."));
113    }
114
115    if receipt_url.is_empty() {
116        return Err(Error::invalid("An expense is filed from a receipt.")
117            .hint("Pass the address the receipt is read from."));
118    }
119
120    let policy: Policy = simple::settings::get(APP_ID, &["approval_limit", "currency"])?;
121
122    let receipt = simple::storage::upload_external(
123        Source::url(receipt_url),
124        Target::new(APP_ID, "expense", "receipt"),
125    )?;
126
127    let read: Execution<Receipt> = simple::ai::extract(
128        simple::serde_json::to_value(&receipt)?,
129        "Read the merchant, the currency and the total from this receipt.",
130        json!({
131            "type": "object",
132            "properties": {
133                "merchant": { "type": "string" },
134                "currency": { "type": "string" },
135                "total": { "type": "number" }
136            },
137            "required": ["merchant", "currency", "total"]
138        }),
139        Options::default(),
140    )?;
141
142    let claim = read.data;
143
144    if claim.currency != policy.currency {
145        return Err(Error::domain(
146            "RECEIPT_CURRENCY_MISMATCH",
147            format!(
148                "The receipt is in {} and this app files expenses in {}.",
149                claim.currency, policy.currency
150            ),
151        )
152        .details(json!({ "expected": policy.currency, "receipt": claim.currency }))
153        .hint("File it against an app configured for that currency. The file is stored; the expense is not."));
154    }
155
156    if claim.total > policy.approval_limit {
157        return Err(Error::domain(
158            "EXPENSE_OVER_LIMIT",
159            format!(
160                "{} {} is over the {} approval limit.",
161                claim.total, claim.currency, policy.approval_limit
162            ),
163        )
164        .details(json!({
165            "limit": policy.approval_limit,
166            "merchant": claim.merchant,
167            "total": claim.total,
168        }))
169        .hint("Send it for approval instead. The file is stored; the expense is not."));
170    }
171
172    let filed: Filed = simple::graphql::mutate(
173        FILE_EXPENSE,
174        json!({
175            "employee": employee,
176            "merchant": &claim.merchant,
177            "receipt": &receipt,
178            "total": claim.total,
179        }),
180    )?;
181
182    Ok(Output {
183        expense_id: filed.expense.id,
184        merchant: claim.merchant,
185        total: claim.total,
186        receipt,
187    })
188}
189
190#[cfg(test)]
191mod tests {
192    use simpleplatform_sdk::testing;
193
194    use super::*;
195
196    /// The action names of the four calls this action makes, in the order it
197    /// makes them.
198    const SETTINGS: &str = "action:settings/get";
199    const UPLOAD: &str = "action:storage/upload-external";
200    const ORCHESTRATOR: &str = "logic:dev.simple.system/ai-orchestrator";
201    const DATABASE: &str = "action:db/execute";
202
203    fn input(employee_id: &str, receipt_url: &str) -> Request<Input> {
204        Request::new(Input {
205            employee_id: employee_id.to_string(),
206            receipt_url: receipt_url.to_string(),
207        })
208    }
209
210    fn stored_receipt() -> Value {
211        json!({
212            "file_hash": "9f86d081884c7d65",
213            "filename": "receipt.pdf",
214            "mime_type": "application/pdf",
215            "size": 24_576,
216            "storage_path": "documents/9f/86/9f86d081884c7d65",
217        })
218    }
219
220    /// A host that answers each of the four calls, with the receipt the model
221    /// reads out of the file decided by the test.
222    fn host(currency: &'static str, total: f64) -> impl Fn(String, Value) -> Result<Value, Error> {
223        move |name, _params| match name.as_str() {
224            SETTINGS => Ok(json!({ "approval_limit": 250.0, "currency": "USD" })),
225            UPLOAD => Ok(stored_receipt()),
226            ORCHESTRATOR => Ok(json!({
227                "data": { "merchant": "Blue Bottle", "currency": currency, "total": total },
228                "metadata": { "input_tokens": 1_840, "output_tokens": 32 },
229            })),
230            _ => Ok(json!({ "expense": { "id": "EXP-1" } })),
231        }
232    }
233
234    #[test]
235    fn it_stores_the_receipt_reads_it_and_files_what_it_says() {
236        let session = testing::install(host("USD", 18.5));
237
238        let output = handler(input("EMP-42", "https://example.com/receipt.pdf")).unwrap();
239
240        assert_eq!(output.expense_id, "EXP-1");
241        assert_eq!(output.merchant, "Blue Bottle");
242        assert_eq!(output.total, 18.5);
243        assert_eq!(output.receipt.file_hash, "9f86d081884c7d65");
244
245        let calls = session.calls();
246
247        assert_eq!(
248            calls
249                .iter()
250                .map(|call| call.name.as_str())
251                .collect::<Vec<_>>(),
252            [SETTINGS, UPLOAD, ORCHESTRATOR, DATABASE],
253        );
254
255        // The handle the store answered with is the one the model was given and
256        // the one the record was written with.
257        assert_eq!(calls[2].params["input"], stored_receipt());
258        assert_eq!(calls[3].params["variables"]["receipt"], stored_receipt());
259    }
260
261    #[test]
262    fn an_expense_over_the_limit_is_not_filed() {
263        let session = testing::install(host("USD", 940.0));
264
265        let error = handler(input("EMP-42", "https://example.com/receipt.pdf")).unwrap_err();
266
267        assert_eq!(error.code().as_str(), "EXPENSE_OVER_LIMIT");
268        assert_eq!(
269            session.calls().len(),
270            3,
271            "the file is stored and the expense is not"
272        );
273    }
274
275    #[test]
276    fn a_receipt_in_another_currency_is_not_filed() {
277        let session = testing::install(host("EUR", 18.5));
278
279        let error = handler(input("EMP-42", "https://example.com/receipt.pdf")).unwrap_err();
280
281        assert_eq!(error.code().as_str(), "RECEIPT_CURRENCY_MISMATCH");
282        assert_eq!(session.calls().len(), 3);
283    }
284
285    #[test]
286    fn an_expense_with_nothing_to_read_is_refused_before_anything_is_sent() {
287        let session = testing::install(host("USD", 18.5));
288
289        let error = handler(input("EMP-42", "   ")).unwrap_err();
290
291        assert_eq!(error.code().as_str(), "INVALID_TOOL_INPUT");
292        assert!(session.calls().is_empty());
293    }
294}