@somewhere-cloud/cli 0.38.153 → 0.38.155
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/docs/adopt.md +39 -0
- package/dist/docs/analytics.md +161 -0
- package/dist/docs/api-reference.md +339 -0
- package/dist/docs/api-surface.md +2067 -0
- package/dist/docs/app-mcp.md +162 -0
- package/dist/docs/architecture-patterns.md +334 -0
- package/dist/docs/auth-client.md +531 -0
- package/dist/docs/billing.md +76 -0
- package/dist/docs/browser.md +639 -0
- package/dist/docs/calendar.md +298 -0
- package/dist/docs/changes.md +323 -0
- package/dist/docs/cli.md +407 -0
- package/dist/docs/common-mistakes.md +199 -0
- package/dist/docs/connect-agent.md +72 -0
- package/dist/docs/cors.md +114 -0
- package/dist/docs/cron.md +167 -0
- package/dist/docs/database-engine.md +167 -0
- package/dist/docs/declared-data.md +1656 -0
- package/dist/docs/declared-files.md +475 -0
- package/dist/docs/deploy-intelligence.md +188 -0
- package/dist/docs/deploy.md +733 -0
- package/dist/docs/design-system.md +273 -0
- package/dist/docs/dev-environments.md +496 -0
- package/dist/docs/domain-ownership.md +31 -0
- package/dist/docs/domains.md +370 -0
- package/dist/docs/feedback.md +88 -0
- package/dist/docs/file-tools.md +116 -0
- package/dist/docs/functions.md +489 -0
- package/dist/docs/getting-started.md +238 -0
- package/dist/docs/github.md +95 -0
- package/dist/docs/google-calendar.md +212 -0
- package/dist/docs/groups.md +836 -0
- package/dist/docs/guarantees.md +58 -0
- package/dist/docs/handled-for-you.md +224 -0
- package/dist/docs/inspect.md +171 -0
- package/dist/docs/limits.md +68 -0
- package/dist/docs/live-data.md +197 -0
- package/dist/docs/live.md +92 -0
- package/dist/docs/local-dev.md +30 -0
- package/dist/docs/migration-supabase.md +58 -0
- package/dist/docs/payments.md +1102 -0
- package/dist/docs/portability.md +194 -0
- package/dist/docs/postgres.md +301 -0
- package/dist/docs/pricing-comparison.md +42 -0
- package/dist/docs/pricing.md +39 -0
- package/dist/docs/project-groups.md +107 -0
- package/dist/docs/projects.md +380 -0
- package/dist/docs/recipe-ai-agent.md +112 -0
- package/dist/docs/recipe-ai-features.md +227 -0
- package/dist/docs/recipe-ai-receipts.md +783 -0
- package/dist/docs/recipe-background-jobs.md +369 -0
- package/dist/docs/recipe-booking.md +348 -0
- package/dist/docs/recipe-csv-import.md +390 -0
- package/dist/docs/recipe-ecommerce.md +127 -0
- package/dist/docs/recipe-email.md +282 -0
- package/dist/docs/recipe-escalation.md +133 -0
- package/dist/docs/recipe-file-uploads.md +159 -0
- package/dist/docs/recipe-import-app.md +110 -0
- package/dist/docs/recipe-login.md +457 -0
- package/dist/docs/recipe-multi-chat.md +198 -0
- package/dist/docs/recipe-paid-api.md +161 -0
- package/dist/docs/recipe-pdfs.md +205 -0
- package/dist/docs/recipe-push-notifications.md +107 -0
- package/dist/docs/recipe-seo.md +200 -0
- package/dist/docs/recipe-signed-in-app.md +330 -0
- package/dist/docs/render.md +99 -0
- package/dist/docs/rooms.md +554 -0
- package/dist/docs/sdk.md +287 -0
- package/dist/docs/sdks.md +24 -0
- package/dist/docs/search.md +199 -0
- package/dist/docs/security-model.md +168 -0
- package/dist/docs/setup.md +212 -0
- package/dist/docs/smoke.md +102 -0
- package/dist/docs/speed.md +298 -0
- package/dist/docs/sql-compatibility.md +96 -0
- package/dist/docs/sw.agent.md +248 -0
- package/dist/docs/sw.ai.md +1291 -0
- package/dist/docs/sw.auth.md +1811 -0
- package/dist/docs/sw.billing.md +171 -0
- package/dist/docs/sw.db.md +2128 -0
- package/dist/docs/sw.email.md +661 -0
- package/dist/docs/sw.endpoint.md +187 -0
- package/dist/docs/sw.env.md +303 -0
- package/dist/docs/sw.fetch.md +115 -0
- package/dist/docs/sw.fs.md +424 -0
- package/dist/docs/sw.groups.md +836 -0
- package/dist/docs/sw.image.md +69 -0
- package/dist/docs/sw.jobs.md +520 -0
- package/dist/docs/sw.logs.md +61 -0
- package/dist/docs/sw.mail.md +106 -0
- package/dist/docs/sw.notifications.md +78 -0
- package/dist/docs/sw.push.md +161 -0
- package/dist/docs/sw.rateLimit.md +67 -0
- package/dist/docs/sw.web.md +128 -0
- package/dist/docs/tasks.md +269 -0
- package/dist/docs/test.md +220 -0
- package/dist/docs/tool-reference-account.md +7 -0
- package/dist/docs/tool-reference-ai.md +121 -0
- package/dist/docs/tool-reference-analytics.md +37 -0
- package/dist/docs/tool-reference-api.md +19 -0
- package/dist/docs/tool-reference-artifacts.md +35 -0
- package/dist/docs/tool-reference-auth.md +163 -0
- package/dist/docs/tool-reference-browser.md +114 -0
- package/dist/docs/tool-reference-code.md +26 -0
- package/dist/docs/tool-reference-connect.md +21 -0
- package/dist/docs/tool-reference-cron.md +48 -0
- package/dist/docs/tool-reference-db.md +282 -0
- package/dist/docs/tool-reference-domains.md +107 -0
- package/dist/docs/tool-reference-email.md +55 -0
- package/dist/docs/tool-reference-env.md +19 -0
- package/dist/docs/tool-reference-feedback.md +56 -0
- package/dist/docs/tool-reference-fs.md +265 -0
- package/dist/docs/tool-reference-github.md +57 -0
- package/dist/docs/tool-reference-groups.md +85 -0
- package/dist/docs/tool-reference-help.md +29 -0
- package/dist/docs/tool-reference-jobs.md +39 -0
- package/dist/docs/tool-reference-live.md +48 -0
- package/dist/docs/tool-reference-logs.md +16 -0
- package/dist/docs/tool-reference-payments.md +44 -0
- package/dist/docs/tool-reference-project.md +706 -0
- package/dist/docs/tool-reference-push.md +78 -0
- package/dist/docs/tool-reference-rate-limit.md +18 -0
- package/dist/docs/tool-reference-search.md +68 -0
- package/dist/docs/tool-reference-security.md +42 -0
- package/dist/docs/tool-reference-smoke.md +17 -0
- package/dist/docs/tool-reference-stock-photos.md +20 -0
- package/dist/docs/tool-reference-tasks.md +73 -0
- package/dist/docs/tool-reference-telegram.md +32 -0
- package/dist/docs/tool-reference-usage.md +9 -0
- package/dist/docs/tool-reference-web.md +71 -0
- package/dist/docs/tool-reference-webhooks.md +9 -0
- package/dist/docs/troubleshooting.md +411 -0
- package/dist/docs/typed-functions.md +94 -0
- package/dist/docs/verify-before-deploy.md +67 -0
- package/dist/docs/vs-supabase.md +75 -0
- package/dist/docs/vs-vercel.md +103 -0
- package/dist/lib/bundle.js +303 -221
- package/dist/lib/bundle.js.map +3 -3
- package/dist/types/lib/test-session.d.ts +8 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +3 -2
- package/runtime/DECLARED-DATA-VENDOR.json +5 -5
- package/runtime/PLATFORM-SOURCE.json +1 -1
- package/runtime/SOURCE-LINT-VENDOR.json +2 -2
- package/runtime/declared-data.cjs +37 -19
- package/runtime/source-lint.cjs +1 -1
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
# Recipe — Read receipts with AI
|
|
2
|
+
|
|
3
|
+
Upload a private receipt photo or PDF, extract its details, then let the user
|
|
4
|
+
correct them before saving. The model does the reading; the user decides what
|
|
5
|
+
becomes a record. Editing and saving do not call the model.
|
|
6
|
+
|
|
7
|
+
## Start from a signed-in app
|
|
8
|
+
|
|
9
|
+
Ask before destructive or paid actions unless the user already authorized them.
|
|
10
|
+
|
|
11
|
+
Create an app with `somewhere init`, or ask your connected agent to create a
|
|
12
|
+
project with the sign-in starter. Keep the starter's auth and layout files.
|
|
13
|
+
Add the files below, replacing its `src/pages/HomePage.tsx`. Deploy raw source
|
|
14
|
+
with `somewhere deploy` or `project_deploy`; there is no frontend build step.
|
|
15
|
+
|
|
16
|
+
This recipe uses `provider: 'anthropic'` with an image-capable model from
|
|
17
|
+
`ai_catalog` and structured output. The example selects `claude-haiku-5-5`.
|
|
18
|
+
Other providers currently refuse image and PDF inputs. Check the account's AI
|
|
19
|
+
balance and the project's spend cap before inviting people to use it.
|
|
20
|
+
|
|
21
|
+
## What the app handles
|
|
22
|
+
|
|
23
|
+
1. **Private upload.** An `owner()` file collection accepts JPEG, PNG, GIF,
|
|
24
|
+
WebP and PDF files up to the example's 5 MiB limit. The browser sends no
|
|
25
|
+
owner id; the signed-in session determines who can reach each file.
|
|
26
|
+
2. **Read once.** The function requires the user, checks a per-user reading
|
|
27
|
+
limit, then reads that user's upload and sends its bytes in one
|
|
28
|
+
`sw.ai.chat` request. It omits `conversation_id`. One request can include
|
|
29
|
+
a separately billed structured-output repair.
|
|
30
|
+
3. **Review.** The result is an unsaved form. The user can change the merchant,
|
|
31
|
+
date, currency, total and line items. Invalid fields keep Save disabled.
|
|
32
|
+
4. **Save explicitly.** Save creates an owner-scoped row from the reviewed
|
|
33
|
+
values. A unique owner-and-file key prevents a second receipt for that
|
|
34
|
+
upload. A second click while an action is running is ignored.
|
|
35
|
+
5. **Recover an uncertain save.** A lost response shows **Check saved
|
|
36
|
+
receipt**, which only reads. If the row is still absent, the user can
|
|
37
|
+
choose **Save again**; the unique key prevents a duplicate. The app never
|
|
38
|
+
repeats a model request or save automatically.
|
|
39
|
+
|
|
40
|
+
The example sets a per-user counter to 20 readings an hour before file or
|
|
41
|
+
model access. Warm instances can admit a few extra readings. The project's AI
|
|
42
|
+
spend cap is a separate control. A refused or failed reading leaves manual
|
|
43
|
+
entry available.
|
|
44
|
+
|
|
45
|
+
## Files
|
|
46
|
+
|
|
47
|
+
The schema, function, services and page below form one example. Keep their
|
|
48
|
+
paths so the relative imports resolve. `api/_lib` contains shared server code;
|
|
49
|
+
`api/receipts/extract.ts` is the request handler.
|
|
50
|
+
|
|
51
|
+
### Schema: private uploads and saved receipts
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
// db/schema.ts
|
|
55
|
+
import { files, id, json, number, owner, schema, table, text } from 'somewhere/db';
|
|
56
|
+
|
|
57
|
+
// receipts: each signed-in user sees and writes only their own saved receipts
|
|
58
|
+
// through the generated somewhere:data client. The browser creates a row only
|
|
59
|
+
// after the user reviews the extracted values and presses Save. One receipt
|
|
60
|
+
// per uploaded file per user: user_id is the owner column owner() manages, so
|
|
61
|
+
// a second save of the same file is refused (DATA_CONFLICT) instead of
|
|
62
|
+
// creating a duplicate, and one user's file ids reveal nothing to another.
|
|
63
|
+
//
|
|
64
|
+
// receipt_files: private uploads, readable only by the uploader. The types are
|
|
65
|
+
// exactly the image and PDF formats the model accepts; 5MB (5 MiB) keeps the
|
|
66
|
+
// base64-encoded request well inside the platform's attachment request limit.
|
|
67
|
+
export default schema({
|
|
68
|
+
receipts: table(
|
|
69
|
+
{
|
|
70
|
+
id: id(),
|
|
71
|
+
file_id: text(),
|
|
72
|
+
merchant: text(),
|
|
73
|
+
purchased_on: text({ default: '' }),
|
|
74
|
+
currency: text({ default: '' }),
|
|
75
|
+
total: number({ nullable: true }),
|
|
76
|
+
lines: json(),
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
scope: owner(),
|
|
80
|
+
unique: [['user_id', 'file_id']],
|
|
81
|
+
client: {
|
|
82
|
+
read: ['id', 'file_id', 'merchant', 'purchased_on', 'currency', 'total', 'lines'],
|
|
83
|
+
create: ['file_id', 'merchant', 'purchased_on', 'currency', 'total', 'lines'],
|
|
84
|
+
delete: true,
|
|
85
|
+
identity: 'authenticated',
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
),
|
|
89
|
+
}, {
|
|
90
|
+
files: {
|
|
91
|
+
receipt_files: files({
|
|
92
|
+
path: '/receipts',
|
|
93
|
+
scope: owner(),
|
|
94
|
+
client: { read: true, upload: true, delete: true },
|
|
95
|
+
limits: { maxSize: '5MB', types: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'] },
|
|
96
|
+
}),
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Shared types
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// types/receipts.ts
|
|
105
|
+
// Type aliases, not interfaces: a line list is stored in a json() column, and
|
|
106
|
+
// only a type alias is assignable to the generated client's JSON value type.
|
|
107
|
+
export type ReceiptLine = { description: string; amount: number };
|
|
108
|
+
|
|
109
|
+
/** What extraction proposes and the user edits. Nothing is saved until Save. */
|
|
110
|
+
export type ReceiptDraft = {
|
|
111
|
+
file_id: string;
|
|
112
|
+
merchant: string;
|
|
113
|
+
/** YYYY-MM-DD, or '' when the receipt shows no date. */
|
|
114
|
+
purchased_on: string;
|
|
115
|
+
/** ISO 4217 code such as 'USD', or '' when the receipt shows none. */
|
|
116
|
+
currency: string;
|
|
117
|
+
lines: ReceiptLine[];
|
|
118
|
+
total: number | null;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export type ReceiptDraftErrors = Partial<Record<'merchant' | 'purchased_on' | 'currency' | 'lines' | 'total', string>>;
|
|
122
|
+
|
|
123
|
+
/** The extraction function's answer. `retry` tells the page whether trying the
|
|
124
|
+
* same file again is reasonable; the page never retries on its own. */
|
|
125
|
+
export type ExtractAnswer =
|
|
126
|
+
| { ok: true; draft: ReceiptDraft }
|
|
127
|
+
| { ok: false; error: { code: string; message: string; retry: boolean } };
|
|
128
|
+
|
|
129
|
+
/** A save either committed, was refused (nothing written), or its outcome is
|
|
130
|
+
* unknown because the response was lost. Unknown is never reported as unsaved. */
|
|
131
|
+
export type SaveOutcome =
|
|
132
|
+
| { kind: 'saved'; message: string }
|
|
133
|
+
| { kind: 'refused'; message: string }
|
|
134
|
+
| { kind: 'unknown'; message: string };
|
|
135
|
+
|
|
136
|
+
/** A read-only look for this file's saved receipt. */
|
|
137
|
+
export type SavedCheck = { kind: 'found'; message: string } | { kind: 'not-found' } | { kind: 'unknown'; message: string };
|
|
138
|
+
|
|
139
|
+
export type ReceiptFlowStep =
|
|
140
|
+
| { kind: 'choose' }
|
|
141
|
+
| { kind: 'uploading' }
|
|
142
|
+
| { kind: 'extracting'; fileId: string }
|
|
143
|
+
| { kind: 'review'; draft: ReceiptDraft }
|
|
144
|
+
| { kind: 'saving'; draft: ReceiptDraft }
|
|
145
|
+
/** The save's outcome is unknown. `checked`: a look found nothing yet. */
|
|
146
|
+
| { kind: 'unconfirmed'; draft: ReceiptDraft; checked: boolean }
|
|
147
|
+
| { kind: 'saved'; message: string };
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Server helpers: model, response schema and answer checks
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
// api/_lib/receipt-extraction.ts
|
|
154
|
+
import type { ExtractAnswer, ReceiptDraft, ReceiptLine } from '../../types/receipts';
|
|
155
|
+
|
|
156
|
+
// This Anthropic model accepts images, PDFs and response_schema.
|
|
157
|
+
export const RECEIPT_MODEL = 'claude-haiku-5-5';
|
|
158
|
+
/** This example's own per-user limit on metered readings (not a platform quota). */
|
|
159
|
+
export const RECEIPT_READS_PER_HOUR = 20;
|
|
160
|
+
/** db/schema.ts receipt_files maxSize: '5MB' is 5 MiB. */
|
|
161
|
+
export const RECEIPT_MAX_BYTES = 5 * 1024 * 1024;
|
|
162
|
+
const MAX_LINES = 100;
|
|
163
|
+
const MAX_TEXT = 200;
|
|
164
|
+
|
|
165
|
+
/** The structured answer the model must return; validated again below. */
|
|
166
|
+
export const RECEIPT_SCHEMA = {
|
|
167
|
+
type: 'object',
|
|
168
|
+
additionalProperties: false,
|
|
169
|
+
required: ['merchant', 'purchased_on', 'currency', 'lines', 'total'],
|
|
170
|
+
properties: {
|
|
171
|
+
merchant: { type: 'string', description: 'Store or business name as printed.' },
|
|
172
|
+
purchased_on: { type: 'string', description: 'Purchase date as YYYY-MM-DD, or an empty string if none is shown.' },
|
|
173
|
+
currency: { type: 'string', description: 'ISO 4217 code such as USD, or an empty string if unclear.' },
|
|
174
|
+
lines: {
|
|
175
|
+
type: 'array',
|
|
176
|
+
items: {
|
|
177
|
+
type: 'object',
|
|
178
|
+
additionalProperties: false,
|
|
179
|
+
required: ['description', 'amount'],
|
|
180
|
+
properties: { description: { type: 'string' }, amount: { type: 'number' } },
|
|
181
|
+
},
|
|
182
|
+
},
|
|
183
|
+
total: { type: ['number', 'null'], description: 'Total paid, or null if not shown.' },
|
|
184
|
+
},
|
|
185
|
+
} as const;
|
|
186
|
+
|
|
187
|
+
export const RECEIPT_PROMPT = 'Read this receipt. Return each purchased item with its price, the merchant, '
|
|
188
|
+
+ 'the purchase date and the total. Copy values as printed; do not invent missing ones.';
|
|
189
|
+
|
|
190
|
+
/** A collection file id is one path segment; anything else is refused. */
|
|
191
|
+
export function isFileId(value: unknown): value is string {
|
|
192
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 128
|
|
193
|
+
&& !value.includes('/') && value !== '.' && value !== '..';
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] as const;
|
|
197
|
+
type ImageType = (typeof IMAGE_TYPES)[number];
|
|
198
|
+
|
|
199
|
+
/** The native input block for an uploaded file, or null for any other type. */
|
|
200
|
+
export function inputBlock(contentType: string | null, bytes: Uint8Array): SomewhereAiImageInputBlock | SomewhereAiDocumentInputBlock | null {
|
|
201
|
+
const data = toBase64(bytes);
|
|
202
|
+
if (contentType === 'application/pdf') {
|
|
203
|
+
return { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data } };
|
|
204
|
+
}
|
|
205
|
+
if (IMAGE_TYPES.includes(contentType as ImageType)) {
|
|
206
|
+
return { type: 'image', source: { type: 'base64', media_type: contentType as ImageType, data } };
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Plain base64 (no data: prefix), encoded in chunks to stay within argument limits. */
|
|
212
|
+
export function toBase64(bytes: Uint8Array): string {
|
|
213
|
+
let binary = '';
|
|
214
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
215
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
216
|
+
}
|
|
217
|
+
return btoa(binary);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function text(value: unknown, max = MAX_TEXT): string | null {
|
|
221
|
+
return typeof value === 'string' ? value.trim().slice(0, max) : null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function money(value: unknown): number | null {
|
|
225
|
+
return typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 100) / 100 : null;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** The model's structured answer as a draft, or null when it is not one. */
|
|
229
|
+
export function draftFromModel(parsed: unknown, fileId: string): ReceiptDraft | null {
|
|
230
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
231
|
+
const answer = parsed as Record<string, unknown>;
|
|
232
|
+
const merchant = text(answer.merchant);
|
|
233
|
+
const purchasedOn = text(answer.purchased_on, 10);
|
|
234
|
+
const currency = text(answer.currency, 3);
|
|
235
|
+
if (merchant === null || purchasedOn === null || currency === null || !Array.isArray(answer.lines)) return null;
|
|
236
|
+
const lines: ReceiptLine[] = [];
|
|
237
|
+
for (const raw of answer.lines.slice(0, MAX_LINES)) {
|
|
238
|
+
const line = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};
|
|
239
|
+
const description = text(line.description);
|
|
240
|
+
const amount = money(line.amount);
|
|
241
|
+
if (description === null || amount === null) return null;
|
|
242
|
+
lines.push({ description, amount });
|
|
243
|
+
}
|
|
244
|
+
const total = answer.total === null ? null : money(answer.total);
|
|
245
|
+
if (total === null && answer.total !== null) return null;
|
|
246
|
+
return {
|
|
247
|
+
file_id: fileId,
|
|
248
|
+
merchant,
|
|
249
|
+
purchased_on: /^\d{4}-\d{2}-\d{2}$/.test(purchasedOn) ? purchasedOn : '',
|
|
250
|
+
currency: /^[A-Za-z]{3}$/.test(currency) ? currency.toUpperCase() : '',
|
|
251
|
+
lines,
|
|
252
|
+
total,
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export function refusal(status: number, code: string, message: string, retry: boolean): Response {
|
|
257
|
+
const body: ExtractAnswer = { ok: false, error: { code, message, retry } };
|
|
258
|
+
return Response.json(body, { status });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* A failed model call, in words the page can show. Messages say what the
|
|
263
|
+
* user can do next and make no claim about charges; only a rate limit is
|
|
264
|
+
* offered as worth trying again later.
|
|
265
|
+
*/
|
|
266
|
+
export function modelFailure(reason: unknown): Response {
|
|
267
|
+
const code = reason && typeof reason === 'object' && typeof (reason as { code?: unknown }).code === 'string'
|
|
268
|
+
? (reason as { code: string }).code : '';
|
|
269
|
+
switch (code) {
|
|
270
|
+
case 'INSUFFICIENT_BALANCE':
|
|
271
|
+
case 'PAID_API_NOT_ACTIVATED':
|
|
272
|
+
case 'PAID_AI_DISABLED':
|
|
273
|
+
return refusal(402, code, 'Receipt reading is unavailable right now. Enter the values yourself.', false);
|
|
274
|
+
case 'AI_SPEND_CAP_REACHED':
|
|
275
|
+
return refusal(429, code, 'Receipt reading is paused for now. Enter the values yourself.', false);
|
|
276
|
+
case 'AI_INPUT_UNSUPPORTED':
|
|
277
|
+
case 'AI_INPUT_TOO_LARGE':
|
|
278
|
+
return refusal(400, code, 'This file could not be read. Upload a JPEG, PNG, GIF, WebP or PDF under 5 MB.', false);
|
|
279
|
+
case 'MODEL_CAPABILITY_UNSUPPORTED':
|
|
280
|
+
case 'MODEL_RETIRED':
|
|
281
|
+
return refusal(503, code, 'Receipt reading is unavailable with the configured model. Enter the values yourself.', false);
|
|
282
|
+
case 'RATE_LIMITED':
|
|
283
|
+
return refusal(429, code, 'Too many receipts at once. Try again in a minute.', true);
|
|
284
|
+
default:
|
|
285
|
+
return refusal(502, 'EXTRACTION_FAILED',
|
|
286
|
+
'Reading the receipt did not finish. It was not retried automatically, because it may already have been charged. '
|
|
287
|
+
+ 'Enter the values yourself, or try again once.', false);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
### The extraction function
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
// api/receipts/extract.ts
|
|
296
|
+
// POST /api/receipts/extract { file_id } → { ok: true, draft } | { ok: false, error }
|
|
297
|
+
//
|
|
298
|
+
// Reads one of the signed-in user's own receipt uploads, makes one sw.ai.chat
|
|
299
|
+
// request for structured rows (the platform may add one separately billed
|
|
300
|
+
// structured-output repair inside it), and returns them as an unsaved draft.
|
|
301
|
+
// Saving happens later, in the browser, only after the user reviews the values.
|
|
302
|
+
import type { ExtractAnswer } from '../../types/receipts';
|
|
303
|
+
import {
|
|
304
|
+
draftFromModel, inputBlock, isFileId, modelFailure, RECEIPT_MAX_BYTES, RECEIPT_MODEL,
|
|
305
|
+
RECEIPT_PROMPT, RECEIPT_READS_PER_HOUR, RECEIPT_SCHEMA, refusal,
|
|
306
|
+
} from '../_lib/receipt-extraction';
|
|
307
|
+
|
|
308
|
+
export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
|
|
309
|
+
if (req.method !== 'POST') return new Response('Method not allowed', { status: 405, headers: { Allow: 'POST' } });
|
|
310
|
+
// Required first: sw.fs below acts as this verified user. Without a signed-in
|
|
311
|
+
// user it would act with project authority over every file.
|
|
312
|
+
const user = await sw.auth.requireUser(req);
|
|
313
|
+
|
|
314
|
+
const body: unknown = await req.json().catch(() => null);
|
|
315
|
+
const fileId = body && typeof body === 'object' ? (body as { file_id?: unknown }).file_id : undefined;
|
|
316
|
+
if (!isFileId(fileId)) return refusal(400, 'VALIDATION_ERROR', 'Choose a receipt to read.', false);
|
|
317
|
+
|
|
318
|
+
// Each reading is metered, so this example allows each user 20 per hour,
|
|
319
|
+
// counted before any file read or model request.
|
|
320
|
+
const limit = await sw.rateLimit.check(`receipt-extract:${user.id}`, RECEIPT_READS_PER_HOUR, 3600);
|
|
321
|
+
if (!limit.allowed) {
|
|
322
|
+
return refusal(429, 'RECEIPT_RATE_LIMITED', `You can read ${RECEIPT_READS_PER_HOUR} receipts an hour. Try again later, or enter the values yourself.`, false);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const file = await findOwnedReceipt(sw, fileId);
|
|
326
|
+
if (!file) return refusal(404, 'RECEIPT_NOT_FOUND', 'That receipt was not found. Upload it again.', false);
|
|
327
|
+
if (file.size_bytes > RECEIPT_MAX_BYTES) return refusal(413, 'RECEIPT_TOO_LARGE', 'Receipts must be under 5 MB.', false);
|
|
328
|
+
|
|
329
|
+
const bytes = new Uint8Array(await (await sw.fs.read(file.path)).arrayBuffer());
|
|
330
|
+
const block = inputBlock(file.content_type, bytes);
|
|
331
|
+
if (!block) return refusal(415, 'RECEIPT_TYPE_UNSUPPORTED', 'Upload a JPEG, PNG, GIF, WebP or PDF.', false);
|
|
332
|
+
|
|
333
|
+
let result: SomewhereAiChatResult;
|
|
334
|
+
try {
|
|
335
|
+
// No conversation_id: this is a one-shot extraction. A failed call is
|
|
336
|
+
// never repeated here.
|
|
337
|
+
result = await sw.ai.chat({
|
|
338
|
+
provider: 'anthropic',
|
|
339
|
+
model: RECEIPT_MODEL,
|
|
340
|
+
max_tokens: 2048,
|
|
341
|
+
response_schema: RECEIPT_SCHEMA,
|
|
342
|
+
messages: [{ role: 'user', content: [block, { type: 'text', text: RECEIPT_PROMPT }] }],
|
|
343
|
+
stream: false,
|
|
344
|
+
});
|
|
345
|
+
} catch (reason: unknown) {
|
|
346
|
+
return modelFailure(reason);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const draft = draftFromModel(result.parsed, fileId);
|
|
350
|
+
if (!draft) {
|
|
351
|
+
return refusal(422, 'RECEIPT_UNREADABLE', 'No rows could be read from this receipt. Enter them yourself, or upload a clearer image.', false);
|
|
352
|
+
}
|
|
353
|
+
const answer: ExtractAnswer = { ok: true, draft };
|
|
354
|
+
return Response.json(answer);
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
/** The one file stored under this upload's id, if the signed-in user owns it.
|
|
358
|
+
* Listing as that user shows only their own files, so another user's id
|
|
359
|
+
* answers exactly like a missing one. */
|
|
360
|
+
async function findOwnedReceipt(sw: SomewhereRuntimeContext, fileId: string): Promise<SomewhereFsListEntry | null> {
|
|
361
|
+
let listing: SomewhereFsListResult;
|
|
362
|
+
try {
|
|
363
|
+
listing = await sw.fs.list(`/receipts/${fileId}/`);
|
|
364
|
+
} catch (reason: unknown) {
|
|
365
|
+
const status = reason && typeof reason === 'object' ? (reason as { status?: unknown }).status : undefined;
|
|
366
|
+
if (status === 403 || status === 404) return null;
|
|
367
|
+
throw reason;
|
|
368
|
+
}
|
|
369
|
+
const found = listing.entries.filter((entry) => entry.type === 'file');
|
|
370
|
+
return found.length === 1 ? found[0] : null;
|
|
371
|
+
}
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
### Browser services: upload, read, save and check
|
|
375
|
+
|
|
376
|
+
```ts
|
|
377
|
+
// src/services/receipts.ts
|
|
378
|
+
import { data, DataError } from 'somewhere:data';
|
|
379
|
+
import { files } from 'somewhere:files';
|
|
380
|
+
import type { ExtractAnswer, ReceiptDraft, ReceiptDraftErrors, SavedCheck, SaveOutcome } from '../../types/receipts';
|
|
381
|
+
|
|
382
|
+
// Mirrors db/schema.ts receipt_files; the platform enforces the same limits.
|
|
383
|
+
export const RECEIPT_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'] as const;
|
|
384
|
+
export const RECEIPT_MAX_BYTES = 5 * 1024 * 1024;
|
|
385
|
+
|
|
386
|
+
export type Outcome<T> = { ok: true; value: T } | { ok: false; message: string; retry: boolean };
|
|
387
|
+
|
|
388
|
+
/** Checked here for a fast answer; the collection's limits are the authority. */
|
|
389
|
+
export function checkReceiptFile(file: File): string | null {
|
|
390
|
+
if (!RECEIPT_TYPES.includes(file.type as (typeof RECEIPT_TYPES)[number])) return 'Choose a JPEG, PNG, GIF, WebP or PDF.';
|
|
391
|
+
if (file.size > RECEIPT_MAX_BYTES) return 'Receipts must be under 5 MB.';
|
|
392
|
+
return null;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Private upload into the signed-in user's receipt_files collection. */
|
|
396
|
+
export async function uploadReceipt(file: File): Promise<Outcome<string>> {
|
|
397
|
+
const problem = checkReceiptFile(file);
|
|
398
|
+
if (problem) return { ok: false, message: problem, retry: false };
|
|
399
|
+
const result = await files.receipt_files.upload(file);
|
|
400
|
+
if (result.error) {
|
|
401
|
+
if (result.error.code === 'PAYLOAD_TOO_LARGE') return { ok: false, message: 'Receipts must be under 5 MB.', retry: false };
|
|
402
|
+
if (result.error.code === 'FILE_TYPE_NOT_ALLOWED') return { ok: false, message: 'Choose a JPEG, PNG, GIF, WebP or PDF.', retry: false };
|
|
403
|
+
if (result.error.code === 'AUTH_REQUIRED') return { ok: false, message: 'Your session ended. Sign in again.', retry: false };
|
|
404
|
+
return { ok: false, message: result.error.message || 'The upload failed. Try again.', retry: true };
|
|
405
|
+
}
|
|
406
|
+
return { ok: true, value: result.data.id };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** One extraction request. The caller decides whether to ask again. */
|
|
410
|
+
export async function extractReceipt(fileId: string): Promise<Outcome<ReceiptDraft>> {
|
|
411
|
+
let response: Response;
|
|
412
|
+
try {
|
|
413
|
+
response = await fetch('/api/receipts/extract', {
|
|
414
|
+
method: 'POST',
|
|
415
|
+
headers: { 'Content-Type': 'application/json' },
|
|
416
|
+
body: JSON.stringify({ file_id: fileId }),
|
|
417
|
+
});
|
|
418
|
+
} catch {
|
|
419
|
+
// The request may or may not have reached the server, so this is not
|
|
420
|
+
// presented as safe to repeat.
|
|
421
|
+
return { ok: false, message: 'Could not confirm the receipt was read. Check your connection, then enter the values or try once more.', retry: false };
|
|
422
|
+
}
|
|
423
|
+
if (response.status === 401) return { ok: false, message: 'Your session ended. Sign in again.', retry: false };
|
|
424
|
+
const answer = await response.json().catch(() => null) as ExtractAnswer | null;
|
|
425
|
+
if (!answer) return { ok: false, message: 'The receipt could not be read. Enter the values yourself.', retry: false };
|
|
426
|
+
if (!answer.ok) return { ok: false, message: answer.error.message, retry: answer.error.retry };
|
|
427
|
+
return { ok: true, value: answer.draft };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function validateDraft(draft: ReceiptDraft): ReceiptDraftErrors {
|
|
431
|
+
const errors: ReceiptDraftErrors = {};
|
|
432
|
+
if (!draft.merchant.trim()) errors.merchant = 'Add the merchant.';
|
|
433
|
+
if (draft.purchased_on && !/^\d{4}-\d{2}-\d{2}$/.test(draft.purchased_on)) errors.purchased_on = 'Use YYYY-MM-DD, or leave it empty.';
|
|
434
|
+
if (draft.currency && !/^[A-Z]{3}$/.test(draft.currency)) errors.currency = 'Use a three-letter code such as USD, or leave it empty.';
|
|
435
|
+
if (draft.lines.some((line) => !line.description.trim() || !Number.isFinite(line.amount))) errors.lines = 'Every line needs a description and an amount.';
|
|
436
|
+
if (draft.total !== null && !Number.isFinite(draft.total)) errors.total = 'Enter the total as a number, or leave it empty.';
|
|
437
|
+
return errors;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** Refusals the platform answers before writing anything. */
|
|
441
|
+
const NOT_WRITTEN = new Set([
|
|
442
|
+
'AUTH_REQUIRED', 'DATA_ACCESS_DENIED', 'DATA_CONTRACT_MISMATCH', 'DATA_IDENTITY_MISMATCH',
|
|
443
|
+
'DATA_INPUT_INVALID', 'DATA_INPUT_TOO_LARGE', 'DATA_OPERATION_INVALID', 'DATA_VALUE_INVALID',
|
|
444
|
+
]);
|
|
445
|
+
|
|
446
|
+
function refusedMessage(code: string): string {
|
|
447
|
+
if (code === 'AUTH_REQUIRED') return 'Your session ended. Sign in again, then save.';
|
|
448
|
+
if (code === 'DATA_CONTRACT_MISMATCH') return 'This app was just updated. Reload the page, then save.';
|
|
449
|
+
return 'The receipt was not saved. Check the values and save again.';
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Saves the reviewed values once and never repeats the write. A lost
|
|
453
|
+
* response is reported as unknown, not as unsaved. Never calls the model. */
|
|
454
|
+
export async function saveReceipt(draft: ReceiptDraft): Promise<SaveOutcome> {
|
|
455
|
+
try {
|
|
456
|
+
const result = await data.receipts.create({
|
|
457
|
+
file_id: draft.file_id,
|
|
458
|
+
merchant: draft.merchant.trim(),
|
|
459
|
+
purchased_on: draft.purchased_on,
|
|
460
|
+
currency: draft.currency,
|
|
461
|
+
total: draft.total,
|
|
462
|
+
lines: draft.lines.map((line) => ({ description: line.description.trim(), amount: line.amount })),
|
|
463
|
+
});
|
|
464
|
+
return { kind: 'saved', message: result.data ? `Saved the receipt from ${result.data.merchant}.` : 'Saved the receipt.' };
|
|
465
|
+
} catch (reason: unknown) {
|
|
466
|
+
const code = reason instanceof DataError ? reason.code : null;
|
|
467
|
+
// One receipt per file (db/schema.ts unique): this file's receipt exists.
|
|
468
|
+
if (code === 'DATA_CONFLICT') return { kind: 'saved', message: 'This receipt is already saved.' };
|
|
469
|
+
if (code && NOT_WRITTEN.has(code)) return { kind: 'refused', message: refusedMessage(code) };
|
|
470
|
+
}
|
|
471
|
+
return { kind: 'unknown', message: 'We could not confirm the save. Check for the saved receipt before saving again.' };
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** Read-only: is this file's receipt among the user's saved receipts? */
|
|
475
|
+
export async function findSavedReceipt(fileId: string): Promise<SavedCheck> {
|
|
476
|
+
try {
|
|
477
|
+
const page = await data.receipts.list({ where: { file_id: fileId }, limit: 1 });
|
|
478
|
+
const saved = page.data[0];
|
|
479
|
+
return saved ? { kind: 'found', message: `Saved the receipt from ${saved.merchant}.` } : { kind: 'not-found' };
|
|
480
|
+
} catch {
|
|
481
|
+
return { kind: 'unknown', message: 'Could not check right now. Try again in a moment.' };
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
### The page flow
|
|
487
|
+
|
|
488
|
+
```ts
|
|
489
|
+
// src/data/useReceiptFlow.ts
|
|
490
|
+
import { useEffect, useRef, useState } from 'react';
|
|
491
|
+
import type { ReceiptDraft, ReceiptDraftErrors, ReceiptFlowStep } from '../../types/receipts';
|
|
492
|
+
import { extractReceipt, findSavedReceipt, saveReceipt, uploadReceipt, validateDraft } from '../services/receipts';
|
|
493
|
+
|
|
494
|
+
export interface ReceiptFlow {
|
|
495
|
+
step: ReceiptFlowStep;
|
|
496
|
+
/** The last failure, with whether trying the same action again is reasonable. */
|
|
497
|
+
problem: { message: string; retry: boolean } | null;
|
|
498
|
+
errors: ReceiptDraftErrors;
|
|
499
|
+
/** The uploaded file whose reading can be requested again by the user. */
|
|
500
|
+
retryFileId: string | null;
|
|
501
|
+
choose(file: File): Promise<void>;
|
|
502
|
+
extract(fileId: string): Promise<void>;
|
|
503
|
+
enterManually(): void;
|
|
504
|
+
edit(draft: ReceiptDraft): void;
|
|
505
|
+
save(): Promise<void>;
|
|
506
|
+
/** After an unconfirmed save: look for this file's saved receipt (read-only). */
|
|
507
|
+
checkSaved(): Promise<void>;
|
|
508
|
+
startOver(): void;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const BLANK = (fileId: string): ReceiptDraft => ({ file_id: fileId, merchant: '', purchased_on: '', currency: '', lines: [], total: null });
|
|
512
|
+
|
|
513
|
+
// Upload → one extraction → review → explicit save. Editing and saving never
|
|
514
|
+
// call the model; a failed reading is only repeated if the user asks.
|
|
515
|
+
export function useReceiptFlow(): ReceiptFlow {
|
|
516
|
+
const mounted = useRef(false);
|
|
517
|
+
// Set synchronously, so a second click before React re-renders cannot start
|
|
518
|
+
// a second upload, model call or save.
|
|
519
|
+
const busy = useRef(false);
|
|
520
|
+
const [step, setStep] = useState<ReceiptFlowStep>({ kind: 'choose' });
|
|
521
|
+
const [problem, setProblem] = useState<ReceiptFlow['problem']>(null);
|
|
522
|
+
const [retryFileId, setRetryFileId] = useState<string | null>(null);
|
|
523
|
+
|
|
524
|
+
useEffect(() => {
|
|
525
|
+
mounted.current = true;
|
|
526
|
+
return () => { mounted.current = false; };
|
|
527
|
+
}, []);
|
|
528
|
+
|
|
529
|
+
async function once(action: () => Promise<void>): Promise<void> {
|
|
530
|
+
if (busy.current) return;
|
|
531
|
+
busy.current = true;
|
|
532
|
+
try {
|
|
533
|
+
await action();
|
|
534
|
+
} finally {
|
|
535
|
+
busy.current = false;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
async function runExtraction(fileId: string) {
|
|
540
|
+
setProblem(null);
|
|
541
|
+
setStep({ kind: 'extracting', fileId });
|
|
542
|
+
const read = await extractReceipt(fileId);
|
|
543
|
+
if (!mounted.current) return;
|
|
544
|
+
if (read.ok) {
|
|
545
|
+
setRetryFileId(null);
|
|
546
|
+
setStep({ kind: 'review', draft: read.value });
|
|
547
|
+
} else {
|
|
548
|
+
setProblem({ message: read.message, retry: read.retry });
|
|
549
|
+
setRetryFileId(fileId);
|
|
550
|
+
setStep({ kind: 'choose' });
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const draft = step.kind === 'review' || step.kind === 'saving' || step.kind === 'unconfirmed' ? step.draft : null;
|
|
555
|
+
const errors = draft ? validateDraft(draft) : {};
|
|
556
|
+
|
|
557
|
+
return {
|
|
558
|
+
step,
|
|
559
|
+
problem,
|
|
560
|
+
errors,
|
|
561
|
+
retryFileId,
|
|
562
|
+
choose: (file) => once(async () => {
|
|
563
|
+
setProblem(null);
|
|
564
|
+
setRetryFileId(null);
|
|
565
|
+
setStep({ kind: 'uploading' });
|
|
566
|
+
const uploaded = await uploadReceipt(file);
|
|
567
|
+
if (!mounted.current) return;
|
|
568
|
+
if (!uploaded.ok) {
|
|
569
|
+
setProblem({ message: uploaded.message, retry: uploaded.retry });
|
|
570
|
+
setStep({ kind: 'choose' });
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
await runExtraction(uploaded.value);
|
|
574
|
+
}),
|
|
575
|
+
extract: (fileId) => once(() => runExtraction(fileId)),
|
|
576
|
+
enterManually() {
|
|
577
|
+
if (!retryFileId || busy.current) return;
|
|
578
|
+
setProblem(null);
|
|
579
|
+
setStep({ kind: 'review', draft: BLANK(retryFileId) });
|
|
580
|
+
setRetryFileId(null);
|
|
581
|
+
},
|
|
582
|
+
edit(next) {
|
|
583
|
+
if (step.kind === 'review') setStep({ kind: 'review', draft: next });
|
|
584
|
+
},
|
|
585
|
+
// From review, or again from an unconfirmed save after a look found
|
|
586
|
+
// nothing: a second write of the same file is refused, never duplicated.
|
|
587
|
+
save: () => once(async () => {
|
|
588
|
+
const ready = step.kind === 'review' || (step.kind === 'unconfirmed' && step.checked);
|
|
589
|
+
if (!ready || Object.keys(errors).length > 0) return;
|
|
590
|
+
const reviewed = step.draft;
|
|
591
|
+
setProblem(null);
|
|
592
|
+
setStep({ kind: 'saving', draft: reviewed });
|
|
593
|
+
const saved = await saveReceipt(reviewed);
|
|
594
|
+
if (!mounted.current) return;
|
|
595
|
+
if (saved.kind === 'saved') setStep({ kind: 'saved', message: saved.message });
|
|
596
|
+
else if (saved.kind === 'refused') {
|
|
597
|
+
setProblem({ message: saved.message, retry: true });
|
|
598
|
+
setStep({ kind: 'review', draft: reviewed });
|
|
599
|
+
} else {
|
|
600
|
+
setProblem({ message: saved.message, retry: false });
|
|
601
|
+
setStep({ kind: 'unconfirmed', draft: reviewed, checked: false });
|
|
602
|
+
}
|
|
603
|
+
}),
|
|
604
|
+
checkSaved: () => once(async () => {
|
|
605
|
+
if (step.kind !== 'unconfirmed') return;
|
|
606
|
+
const pending = step.draft;
|
|
607
|
+
const found = await findSavedReceipt(pending.file_id);
|
|
608
|
+
if (!mounted.current) return;
|
|
609
|
+
if (found.kind === 'found') {
|
|
610
|
+
setProblem(null);
|
|
611
|
+
setStep({ kind: 'saved', message: found.message });
|
|
612
|
+
} else if (found.kind === 'not-found') {
|
|
613
|
+
// Absence is not proof the save failed; say what is known.
|
|
614
|
+
setProblem({ message: 'No saved receipt for this file yet. If you just saved, check again in a moment. Saving again is safe: a duplicate is refused.', retry: true });
|
|
615
|
+
setStep({ kind: 'unconfirmed', draft: pending, checked: true });
|
|
616
|
+
} else {
|
|
617
|
+
setProblem({ message: found.message, retry: true });
|
|
618
|
+
}
|
|
619
|
+
}),
|
|
620
|
+
startOver() {
|
|
621
|
+
if (busy.current) return;
|
|
622
|
+
setProblem(null);
|
|
623
|
+
setRetryFileId(null);
|
|
624
|
+
setStep({ kind: 'choose' });
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
```
|
|
629
|
+
|
|
630
|
+
### The review form
|
|
631
|
+
|
|
632
|
+
```tsx
|
|
633
|
+
// src/ui/ReceiptReview.tsx
|
|
634
|
+
import type { ChangeEvent, FormEvent } from 'react';
|
|
635
|
+
import type { ReceiptDraft, ReceiptLine } from '../../types/receipts';
|
|
636
|
+
import type { ReceiptFlow } from '../data/useReceiptFlow';
|
|
637
|
+
import { RECEIPT_TYPES } from '../services/receipts';
|
|
638
|
+
|
|
639
|
+
/** An empty field is NaN, which validation reports, never a silent 0. */
|
|
640
|
+
const amountOf = (value: string): number => (value.trim() === '' ? Number.NaN : Number(value));
|
|
641
|
+
|
|
642
|
+
export function ReceiptReview({ flow }: { flow: ReceiptFlow }) {
|
|
643
|
+
const { step, problem } = flow;
|
|
644
|
+
return (
|
|
645
|
+
<div className="panel">
|
|
646
|
+
<h1 className="panel__title">Receipts</h1>
|
|
647
|
+
{step.kind === 'choose' ? <ChooseFile flow={flow} /> : null}
|
|
648
|
+
{step.kind === 'uploading' ? <p role="status">Uploading…</p> : null}
|
|
649
|
+
{step.kind === 'extracting' ? <p role="status">Reading the receipt…</p> : null}
|
|
650
|
+
{step.kind === 'review' || step.kind === 'saving' ? <ReviewForm flow={flow} draft={step.draft} saving={step.kind === 'saving'} /> : null}
|
|
651
|
+
{step.kind === 'unconfirmed' ? (
|
|
652
|
+
<div className="actions">
|
|
653
|
+
<p role="status">Saving {step.draft.merchant || 'this receipt'} was not confirmed.</p>
|
|
654
|
+
<button type="button" className="button" onClick={() => void flow.checkSaved()}>Check saved receipt</button>
|
|
655
|
+
{step.checked ? <button type="button" className="button button--quiet" onClick={() => void flow.save()}>Save again</button> : null}
|
|
656
|
+
</div>
|
|
657
|
+
) : null}
|
|
658
|
+
{step.kind === 'saved' ? (
|
|
659
|
+
<div className="actions">
|
|
660
|
+
<p role="status">{step.message}</p>
|
|
661
|
+
<button type="button" className="button" onClick={flow.startOver}>Add another receipt</button>
|
|
662
|
+
</div>
|
|
663
|
+
) : null}
|
|
664
|
+
{problem ? <p className="notice error" role="alert">{problem.message}</p> : null}
|
|
665
|
+
</div>
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
function ChooseFile({ flow }: { flow: ReceiptFlow }) {
|
|
670
|
+
function onChange(event: ChangeEvent<HTMLInputElement>) {
|
|
671
|
+
const file = event.target.files?.[0];
|
|
672
|
+
event.target.value = '';
|
|
673
|
+
if (file) void flow.choose(file);
|
|
674
|
+
}
|
|
675
|
+
const fileId = flow.retryFileId;
|
|
676
|
+
return (
|
|
677
|
+
<>
|
|
678
|
+
<div className="field">
|
|
679
|
+
<label htmlFor="receipt-file">Receipt photo or PDF <span className="hint">up to 5 MB</span></label>
|
|
680
|
+
<input id="receipt-file" type="file" accept={RECEIPT_TYPES.join(',')} onChange={onChange} />
|
|
681
|
+
</div>
|
|
682
|
+
{fileId ? (
|
|
683
|
+
<div className="actions">
|
|
684
|
+
<button type="button" className="button button--quiet" onClick={flow.enterManually}>Enter the values myself</button>
|
|
685
|
+
{flow.problem?.retry ? <button type="button" className="button" onClick={() => void flow.extract(fileId)}>Read it again</button> : null}
|
|
686
|
+
</div>
|
|
687
|
+
) : null}
|
|
688
|
+
</>
|
|
689
|
+
);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function ReviewForm({ flow, draft, saving }: { flow: ReceiptFlow; draft: ReceiptDraft; saving: boolean }) {
|
|
693
|
+
const { errors } = flow;
|
|
694
|
+
const set = (patch: Partial<ReceiptDraft>) => flow.edit({ ...draft, ...patch });
|
|
695
|
+
const setLine = (index: number, patch: Partial<ReceiptLine>) =>
|
|
696
|
+
set({ lines: draft.lines.map((line, i) => (i === index ? { ...line, ...patch } : line)) });
|
|
697
|
+
|
|
698
|
+
function onSubmit(event: FormEvent<HTMLFormElement>) {
|
|
699
|
+
event.preventDefault();
|
|
700
|
+
void flow.save();
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
return (
|
|
704
|
+
<form onSubmit={onSubmit} noValidate>
|
|
705
|
+
<p className="muted">Check every value. Nothing is saved until you press Save.</p>
|
|
706
|
+
<div className="field">
|
|
707
|
+
<label htmlFor="receipt-merchant">Merchant</label>
|
|
708
|
+
<input id="receipt-merchant" value={draft.merchant} disabled={saving} onChange={(e) => set({ merchant: e.target.value })} />
|
|
709
|
+
{errors.merchant ? <p className="error">{errors.merchant}</p> : null}
|
|
710
|
+
</div>
|
|
711
|
+
<div className="field">
|
|
712
|
+
<label htmlFor="receipt-date">Date <span className="hint">YYYY-MM-DD</span></label>
|
|
713
|
+
<input id="receipt-date" value={draft.purchased_on} disabled={saving} onChange={(e) => set({ purchased_on: e.target.value.trim() })} />
|
|
714
|
+
{errors.purchased_on ? <p className="error">{errors.purchased_on}</p> : null}
|
|
715
|
+
</div>
|
|
716
|
+
<div className="field">
|
|
717
|
+
<label htmlFor="receipt-currency">Currency</label>
|
|
718
|
+
<input id="receipt-currency" value={draft.currency} disabled={saving} onChange={(e) => set({ currency: e.target.value.trim().toUpperCase() })} />
|
|
719
|
+
{errors.currency ? <p className="error">{errors.currency}</p> : null}
|
|
720
|
+
</div>
|
|
721
|
+
<fieldset className="field" disabled={saving}>
|
|
722
|
+
<legend>Items</legend>
|
|
723
|
+
{draft.lines.map((line, index) => (
|
|
724
|
+
<div className="actions" key={index}>
|
|
725
|
+
<input aria-label={`Item ${index + 1}`} value={line.description} onChange={(e) => setLine(index, { description: e.target.value })} />
|
|
726
|
+
<input aria-label={`Amount ${index + 1}`} type="number" step="0.01" value={Number.isNaN(line.amount) ? '' : line.amount}
|
|
727
|
+
onChange={(e) => setLine(index, { amount: amountOf(e.target.value) })} />
|
|
728
|
+
<button type="button" className="link-button link-button--danger" onClick={() => set({ lines: draft.lines.filter((_, i) => i !== index) })}>Remove</button>
|
|
729
|
+
</div>
|
|
730
|
+
))}
|
|
731
|
+
<button type="button" className="link-button" onClick={() => set({ lines: [...draft.lines, { description: '', amount: Number.NaN }] })}>Add item</button>
|
|
732
|
+
{errors.lines ? <p className="error">{errors.lines}</p> : null}
|
|
733
|
+
</fieldset>
|
|
734
|
+
<div className="field">
|
|
735
|
+
<label htmlFor="receipt-total">Total</label>
|
|
736
|
+
<input id="receipt-total" type="number" step="0.01" disabled={saving} value={draft.total === null || Number.isNaN(draft.total) ? '' : draft.total}
|
|
737
|
+
onChange={(e) => set({ total: e.target.value.trim() === '' ? null : amountOf(e.target.value) })} />
|
|
738
|
+
{errors.total ? <p className="error">{errors.total}</p> : null}
|
|
739
|
+
</div>
|
|
740
|
+
<div className="actions">
|
|
741
|
+
<button type="submit" className="button" disabled={saving || Object.keys(errors).length > 0} aria-busy={saving}>{saving ? 'Saving…' : 'Save'}</button>
|
|
742
|
+
<button type="button" className="button button--quiet" disabled={saving} onClick={flow.startOver}>Discard</button>
|
|
743
|
+
</div>
|
|
744
|
+
</form>
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
### The home page
|
|
750
|
+
|
|
751
|
+
```tsx
|
|
752
|
+
// src/pages/HomePage.tsx
|
|
753
|
+
import type { User } from '../../types/auth';
|
|
754
|
+
import { useReceiptFlow } from '../data/useReceiptFlow';
|
|
755
|
+
import { ReceiptReview } from '../ui/ReceiptReview';
|
|
756
|
+
import { SignedInLayout } from './SignedInLayout';
|
|
757
|
+
|
|
758
|
+
// Replaces the starter's home page. App.tsx already renders this only for a
|
|
759
|
+
// signed-in user, keyed by user id, so another account starts a fresh flow.
|
|
760
|
+
export function HomePage({ user }: { user: User }) {
|
|
761
|
+
const flow = useReceiptFlow();
|
|
762
|
+
return (
|
|
763
|
+
<SignedInLayout user={user}>
|
|
764
|
+
<ReceiptReview flow={flow} />
|
|
765
|
+
</SignedInLayout>
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
```
|
|
769
|
+
|
|
770
|
+
## Try it
|
|
771
|
+
|
|
772
|
+
Sign in and choose a receipt you can share with the model. The app uploads it
|
|
773
|
+
and shows **Reading the receipt…** while extraction runs. Check and edit every
|
|
774
|
+
extracted value, then save. Ask your agent to inspect the saved row through the
|
|
775
|
+
generated data client; this example does not include a saved-receipts list. Sign in as a second user: the
|
|
776
|
+
first user's upload and receipt should be unavailable.
|
|
777
|
+
|
|
778
|
+
The reading can fail or be inaccurate. Keep the original file and ask the
|
|
779
|
+
user to check totals and currency before relying on a saved record. Use a
|
|
780
|
+
smaller image if an upload exceeds the example's limit.
|
|
781
|
+
|
|
782
|
+
Related: `declared-files` for upload rules, `declared-data` for owner tables,
|
|
783
|
+
`sw.ai` for models and costs, and `recipe-background-jobs` for longer work.
|