1use simpleplatform_sdk::prelude::*;
16
17const APP_ID: &str = "dev.simple.expenses";
19
20#[derive(Deserialize, Schema)]
30struct Input {
31 #[simple(length(min = 1))]
33 employee_id: String,
34
35 #[simple(length(min = 1), format = "uri")]
37 receipt_url: String,
38}
39
40#[derive(Deserialize)]
42struct Policy {
43 approval_limit: f64,
44 currency: String,
45}
46
47#[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#[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
95fn 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 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 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 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}