clayway-extractreceiptendpoint.web.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { callGoogleSheetsAPI } from "https://esm.town/v/clayway/callGoogleSheetsAPI";
import { extractReceiptInfo } from "https://esm.town/v/clayway/extractReceiptInfo";
import process from "node:process";
type RequestBody = {
text: string;
time_zone: string;
};
export async function extractReceiptEndpoint(request: Request): Promise<Response> {
if (request.method !== "POST") {
return Response.json({
error: "Method not allowed",
}, { status: 405 });
}
if (
request.headers.get("Authorization")
!== process.env.ENDPOINT_TOKEN
) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const { text, time_zone: timeZone } = await request.json() as RequestBody;
const result = JSON.parse(await extractReceiptInfo(text));
// Formats dates into YYYY-MM-DD taking time zone into account
const dateFormatter = new Intl.DateTimeFormat("fr-CA", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone,
});
const {
date = dateFormatter.format(new Date()),
name,
amount,
category,
} = result;
try {
await callGoogleSheetsAPI({
sheetId: process.env.BUDGET_SHEET_ID,
serviceAccount: process.env.GOOGLE_SERVICE_ACCOUNT,
action: "values/Transactions!A1:G1:append?insertDataOption=INSERT_ROWS&valueInputOption=USER_ENTERED",
data: {
values: [[date, name, amount, category, "", "", ""]] as string[][],
},
});
return Response.json({ result });
}
catch (error) {
return Response.json({ error }, { status: 500 });
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 24, 2023