Skip to content

Commit 2b51b8c

Browse files
fix: verify receipt and email flows, preserve cents and complete monthly reports
1 parent d838730 commit 2b51b8c

19 files changed

Lines changed: 205 additions & 97 deletions

‎.env.example‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ GEMINI_API_KEY=
1919
# Both receipt scanning and reports use this model. Verify access with your key.
2020
GEMINI_MODEL=gemini-3.5-flash-lite
2121
RESEND_API_KEY=
22+
# Optional verified sender; defaults to Resend's restricted testing sender.
23+
RESEND_FROM=
2224
# This spelling intentionally matches app/api/exchangeRates/route.js.
2325
OPEN_EXCANGE_API_KEY=
2426

‎README.de.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ Next.js 15 und React 19 bilden die Anwendung. Die Oberfläche nutzt Tailwind CSS
5555

5656
## Stand und Grenzen
5757

58-
Das Projekt ist eine Demo. Belegscan und Monatsberichte verwenden jetzt gemeinsam `GEMINI_MODEL`, standardmäßig `gemini-3.5-flash-lite`. Der Free-Tarif des Demo-Projekts ohne aktivierte Abrechnung wurde in AI Studio bestätigt. Ein echter API-Test mit erfundenem Belegtext lieferte die erwarteten JSON-Daten. Die tatsächlichen Kontingente sind projektabhängig. Der Belegscan benötigt eine Anmeldung und begrenzt Versuche auf fünf pro Nutzer mit Auffüllung nach 24 Stunden. Der Bildscan über die angemeldete Oberfläche und der Berichtversand müssen separat geprüft werden. Siehe [KI kostenlos einrichten](docs/AI.md).
58+
Das Projekt ist eine Demo. Belegscan und Monatsberichte verwenden gemeinsam `GEMINI_MODEL`, standardmäßig `gemini-3.5-flash-lite`. Der Free-Tarif des Demo-Projekts ohne aktivierte Abrechnung wurde in AI Studio bestätigt. Ein erfundener Bildbeleg wurde über die angemeldete Oberfläche gescannt und als Transaktion gespeichert. Zwei ausdrücklich freigegebene Test-Mails für Budgetwarnung und Monatsbericht wurden laut Resend zugestellt. Die automatische Zeitplanung ist noch nicht verbunden. Die tatsächlichen Kontingente sind projektabhängig; Belegscans sind auf fünf Versuche pro Nutzer mit Auffüllung nach 24 Stunden begrenzt. Siehe [Prüfergebnisse](docs/VERIFICATION.md) und [KI kostenlos einrichten](docs/AI.md).
5959

6060
Der alte Seed-Endpunkt ist deaktiviert und antwortet mit HTTP 410. Das bisherige Skript mit festen IDs wird darüber nicht mehr ausgeführt. Next.js und seine Prüfkonfiguration wurden auf die abgesicherte Version 15.5.28 aktualisiert; geschützte Routen und die Anmeldeweiterleitung sind korrigiert.
6161

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ A full-stack personal finance demo that brings accounts, transactions and spendi
1010
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-Prisma-111827?logo=postgresql)](prisma/schema.prisma)
1111
[![Project status](https://img.shields.io/badge/status-demo-f5d563)](#project-status)
1212

13-
[Request a demo](docs/DEMO.md#request-a-demo) · [Set up the full app](docs/SETUP.md) · [Architecture](docs/ARCHITECTURE.md) · [Deutsch](README.de.md)
13+
[Request a demo](docs/DEMO.md#request-a-demo) · [Set up the full app](docs/SETUP.md) · [Verification](docs/VERIFICATION.md) · [Architecture](docs/ARCHITECTURE.md) · [Deutsch](README.de.md)
1414

1515
![Actual Prudentis AI analytics components rendered in a browser with fictional transactions](docs/images/analytics-preview.png)
1616

‎actions/budget.js‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import {auth} from "@clerk/nextjs/server";
44
import {db} from "@/lib/prisma";
55
import {revalidatePath} from "next/cache";
6+
import {monthWindow} from "@/lib/reporting.mjs";
67

78
export async function getCurrentBudget(accountId) {
89
try{
@@ -24,16 +25,7 @@ export async function getCurrentBudget(accountId) {
2425
});
2526

2627
const currentDate = new Date();
27-
const startOfMonth = new Date(
28-
currentDate.getFullYear(),
29-
currentDate.getMonth(),
30-
1
31-
);
32-
const endOfMonth = new Date(
33-
currentDate.getFullYear(),
34-
currentDate.getMonth() + 1,
35-
0
36-
);
28+
const {start: startOfMonth, end: endOfMonth} = monthWindow(currentDate);
3729

3830
const expenses = await db.transaction.aggregate({
3931
where: {
@@ -42,7 +34,7 @@ export async function getCurrentBudget(accountId) {
4234
type: "EXPENSE",
4335
date: {
4436
gte: startOfMonth,
45-
lte: endOfMonth,
37+
lt: endOfMonth,
4638
},
4739
},
4840
_sum:{
@@ -92,4 +84,4 @@ export async function updateBudget(amount) {
9284
console.log("Error updating budget:", error);
9385
return {success: false, error: error.message};
9486
}
95-
}
87+
}

‎actions/send-email.js‎

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1 @@
1-
import {Resend} from "resend";
2-
3-
export async function sendEmail({to, subject, react}) {
4-
const resend = new Resend(process.env.RESEND_API_KEY || "");
5-
6-
try{
7-
const data = await resend.emails.send({
8-
from: "Prudentis AI <onboarding@resend.dev>",
9-
to,
10-
subject,
11-
react,
12-
});
13-
14-
return {success: true, data};
15-
} catch (error) {
16-
console.error("Error sending email:", error);
17-
return {success: false, error: error.message};
18-
}
19-
}
1+
export {sendEmail} from "../lib/email.mjs";

‎actions/transaction.js‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import aj from "@/lib/arcjet";
88
import { request } from "@arcjet/next";
99
import aiRateLimit from "@/lib/arcjet-ai";
1010
import { validateReceiptFile } from "@/lib/receipt.mjs";
11+
import { parseReceiptResponse } from "@/lib/receipt-response.mjs";
1112

1213
const serializeAmount = (obj) => ({
1314
...obj,
@@ -151,14 +152,7 @@ export async function scanReceipt(file) {
151152
const cleanedText = text.replace(/```(?:json)?\n?/g, "").trim();
152153

153154
try {
154-
const data = JSON.parse(cleanedText);
155-
return {
156-
amount: parseFloat(data.amount),
157-
date: new Date(data.date),
158-
description: data.description,
159-
category: data.category,
160-
merchantName: data.merchantName,
161-
};
155+
return parseReceiptResponse(JSON.parse(cleanedText));
162156
} catch (parseError) {
163157
console.error("Error parsing JSON response:", parseError);
164158
throw new Error("Invalid response format from Gemini");

‎app/(main)/transaction/_components/transaction-form.jsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ const AddTransactionForm = ({accounts, categories, editMode = false, initialData
172172
<SelectContent>
173173
{accounts.map((account) => (
174174
<SelectItem key={account.id} value={account.id}>
175-
{account.name} (${parseInt(account.balance).toFixed(2)})
175+
{account.name} (${Number(account.balance).toFixed(2)})
176176
</SelectItem>
177177
))}
178178
<CreateAccountDrawer>

‎docs/AI.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ The per-user scan bucket is not a global project cost cap. Monthly reports also
3636

3737
## Verification and data handling
3838

39-
Unit tests cover missing keys, shared model selection, retired-model rejection and receipt upload boundaries. They do not contact Google. On October 25, 2026, AI Studio showed the demo project's Free tier with billing not enabled. A live SDK request using fictional receipt text and `gemini-3.5-flash-lite` returned valid JSON with the expected amount and date. The initially selected `gemini-3.8-flash` returned 503 overload errors twice, so the demo now selects Flash-Lite explicitly. This is not an automatic fallback. Image upload through the authenticated UI and scheduled report delivery still need separate integration checks.
39+
Unit tests cover missing keys, shared model selection, retired-model rejection, upload boundaries and malformed receipt responses. They do not contact Google. On October 25, 2026, AI Studio showed the demo project's Free tier with billing not enabled. Live text and image receipt tests with `gemini-3.5-flash-lite` returned the expected fields; the image was scanned and saved through the authenticated UI. A controlled monthly-report run generated insights and sent an authorized test message, which Resend reported as delivered. The initially selected `gemini-3.8-flash` returned 503 overload errors twice, so the demo now selects Flash-Lite explicitly. This is not an automatic fallback. Automatic cloud schedules remain disabled. See the [verification record](VERIFICATION.md).
4040

4141
Use fictional receipt data initially. Receipt images and monthly aggregate statistics leave the application when those features call Google. Review the provider terms applicable to your location and tier before using personal financial data; the [pricing page](https://ai.google.dev/gemini-api/docs/pricing) links to the relevant data-use terms.
4242

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ These areas remain follow-up work rather than capabilities established by the do
6262
1. **Full route protection.** Middleware now matches the bare dashboard and the actual `/transaction` prefix and uses Clerk's `auth.protect()` redirect. Verify these flows with the deployment's Clerk instance. Server Actions also enforce identity.
6363
2. **Legacy seeding.** `/api/seed` is disabled and returns HTTP 410. The historical generator is not imported by that endpoint and must not be reconnected to a public route.
6464
3. **Recurrence semantics.** The current due-check treats a missing `lastProcessed` as immediately due. Verify first-run dates, month-end behavior, retries and duplicate-event idempotency with a test database.
65-
4. **Date boundaries.** Some monthly queries use the final day at midnight as an inclusive end. Review end-of-day coverage, timezone handling and first-of-month reports across short months.
65+
4. **Date boundaries.** Budget queries and monthly reports now share complete UTC month windows with an exclusive next-month boundary. Tests cover leap day, the 31st and year transitions. User-selectable reporting timezones are not implemented.
6666
5. **Concurrent balances.** The creation action reads a balance before writing a calculated new value. Review concurrent writes and default-account changes with realistic integration tests.
67-
6. **AI contract.** The provider model is configurable and bounded, but extraction accuracy, response shape and SDK compatibility still need a live test. MIME/size checks do not inspect the actual binary image signature. Review model output validation before relying on extracted financial values.
68-
7. **Email errors.** Confirm both API return values and job outcomes. Resend may return an error payload rather than throwing; retry and `lastAlertSent` behavior need a configured delivery test.
67+
6. **AI contract.** A fictional receipt image was scanned and saved through the live UI. Receipt fields and report-insight arrays are validated; extraction accuracy across real-world receipts still requires evaluation. MIME/size checks do not inspect the binary image signature.
68+
7. **Email delivery.** Provider error payloads now fail delivery, and alert markers are updated only after acceptance. Controlled budget/monthly handler tests were delivered by Resend. Automatic scheduling still needs an explicitly configured Inngest Cloud connection; see [verification](VERIFICATION.md).
6969
8. **Dependency maintenance.** Next.js and eslint-config-next are updated to 15.5.28 following the October 2026 security advisory. Other dependencies still need routine maintenance; this targeted update is not an application-wide vulnerability assessment.
7070

7171
The full application's root layout is dynamic, so authenticated pages are rendered per request instead of during a build. Both the preview and the full application now build without service credentials; runtime functionality still needs configured services. Database migrations enable row-level security and revoke access from Supabase's public REST roles, as the application accesses these tables through Prisma on the server.

‎docs/SETUP.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ Copy-Item .env.example .env
5050
| `GEMINI_API_KEY` | Receipt extraction and monthly AI insights. | Enabling AI features. |
5151
| `GEMINI_MODEL` | Shared model selection; defaults to `gemini-3.5-flash-lite`. | Optional override; verify availability in your project. |
5252
| `RESEND_API_KEY` | Budget-alert and monthly-report delivery. | Sending email. |
53+
| `RESEND_FROM` | Optional verified sender address. | Sending beyond Resend's restricted testing sender. |
5354
| `OPEN_EXCANGE_API_KEY` | `/api/exchangeRates`. The spelling matches the existing code. | Using exchange-rate data. |
5455
| `INNGEST_EVENT_KEY` | Send events to Inngest Cloud. | Deploying background jobs to Inngest Cloud. |
5556
| `INNGEST_SIGNING_KEY` | Verify Inngest Cloud requests. | Deploying background jobs to Inngest Cloud. |
@@ -100,7 +101,7 @@ Receipt images are sent to Google when this feature is used. Monthly insight gen
100101

101102
### Email delivery
102103

103-
Set `RESEND_API_KEY`. [`actions/send-email.js`](../actions/send-email.js) currently uses `Prudentis AI <onboarding@resend.dev>`. Follow Resend's account restrictions for testing and configure a verified sender domain in the code before broader delivery. The preview's `/reports` route renders the email locally without sending anything.
104+
Set `RESEND_API_KEY`. The shared [`mail helper`](../lib/email.mjs) defaults to `Prudentis AI <onboarding@resend.dev>`. Follow Resend's account restrictions for testing; use `RESEND_FROM` with a verified sender domain before broader delivery. Provider error responses fail delivery, and job retries use stable idempotency headers. The preview's `/reports` route renders the email locally without sending anything. See the [verification record](VERIFICATION.md) for the authorized delivery tests and scheduling status.
104105

105106
### Scheduled jobs
106107

0 commit comments

Comments
 (0)