Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The web app in `src/` (TanStack Start routes, components, hooks and server funct
- Category learning comes only from a person's decision; in the UI, route category choices and recurrence confirmations to the API's decision endpoints, never to heuristics or model output.
- Scope UI types to the read model they need. Invalidation of financial reads includes configuration, planning, categories and paginated transactions; optimistic category edits must also cover cached transaction pages.
- Sign-in is Google through Better Auth in `src/features/auth`, limited to `SPENDLE_ALLOWED_EMAILS`. Better Auth keeps people, sessions and OAuth clients in its own database (a SQLite file in `data/auth/` on Node, the D1 `spendle-auth` on Cloudflare; never financial data) and creates its tables on first use. `src/start.ts` requires an allowed session for every server function; route `beforeLoad` only guards pages. A new server route that touches data must call `readViewer()` itself. QA runs keep real auth: `vp run qa:start` registers a sign-in link for `qa@spendle.local` (`SPENDLE_QA_SIGN_IN_TOKEN`), which nothing else sets.
- The MCP server (`/api/mcp`, `src/features/mcp`) is Better Auth's OAuth provider plus resource: a client signs in through `/entrar`, the person approves it on `/autorizar`, and each call re-checks the allowlist before calling the API as that member. Tools read, refresh and sync Open Finance. Only a token with the `spendle:write` scope, which the person grants on `/autorizar`, also gets the write tools; they record the person's decisions (categories, notes, one-off marks, transfers, category rules, caps, pausing recurrences) through the same API endpoints as the app, and the tools tell the client to call them only when the person asks.
- The MCP server (`/api/mcp`, `src/features/mcp`) is Better Auth's OAuth provider plus resource: a client signs in through `/entrar`, the person approves it on `/autorizar`, and each call re-checks the allowlist before calling the API as that member. Tools read, refresh and sync Open Finance. Only a token with the `spendle:write` scope, which the person grants on `/autorizar`, also gets the write tools; they record the person's decisions (categories, notes and one-off marks on one or many entries, transfers, income versus movement, category rules, payee names, caps, plan envelopes, pausing and editing recurrences) through the same API endpoints as the app, and the tools tell the client to call them only when the person asks.
- AI features (assistant, model classifier) are on by default when the server has their keys; there is no separate consent step. Model output never unlocks an import or teaches categories.

## Production on Cloudflare
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ claude mcp add --transport http spendle http://localhost:3000/api/mcp

O cliente abre o login sozinho. Você entra com Google e aprova o aplicativo em `/autorizar`. A partir daí ele lê contas, transações, planejamento, gastos contra os tetos, previsão de caixa, cartões e parcelas, investimentos e conexões de Open Finance, e pode atualizar e sincronizar essas conexões.

Se o cliente pedir, `/autorizar` também oferece **Permitir alterações**, desligado por padrão. Com essa opção ligada, o cliente pode mudar a categoria, a nota e a marca de pontual de uma transação, marcar transferências, pagamentos de fatura e aportes, criar regras de categoria, definir tetos e pausar recorrências. Cada alteração passa pelas mesmas regras do app. Contas não mudam por aí. Um cliente aprovado antes só lê até você conectá-lo de novo.
Se o cliente pedir, `/autorizar` também oferece **Permitir alterações**, desligado por padrão. Com essa opção ligada, o cliente pode mudar a categoria, a nota e a marca de pontual de uma ou várias transações de uma vez, marcar transferências, pagamentos de fatura e aportes, dizer se uma entrada é renda ou só dinheiro mudando de conta, criar regras de categoria (que só recategorizam o histórico quando você pede), dar nome a um favorecido, definir tetos e a divisão do plano, e pausar ou ajustar recorrências. Cada alteração passa pelas mesmas regras do app. Contas não mudam e nenhuma transação é apagada por aí. Um cliente aprovado antes só lê até você conectá-lo de novo.

Tirar um e-mail de `SPENDLE_ALLOWED_EMAILS` também corta o acesso que esse e-mail já tinha dado.

Expand Down
2 changes: 2 additions & 0 deletions packages/server/src/api/Failures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ const manual: Record<ManualEntryError['reason'], Status> = {
const notes: Record<NotesError['reason'], Status> = {
entry_not_found: NotFound,
note_too_long: InvalidRequest,
payee_too_long: InvalidRequest,
no_merchant: Rejected,
}

const investments: Record<InvestmentsError['reason'], Status> = {
Expand Down
32 changes: 25 additions & 7 deletions packages/server/src/api/ReadModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as Schema from 'effect/Schema'
import * as SqlClient from 'effect/sql/SqlClient'
import * as SqlSchema from 'effect/sql/SqlSchema'

import { merchantSignature } from '../categories/Patterns.ts'
import type { Account } from '../ledger/Accounts.ts'
import { entryNotes, entryOneOffs } from '../ledger/Notes.ts'
import { inChunks } from '../persistence/Chunks.ts'
Expand Down Expand Up @@ -56,7 +57,11 @@ const EntryRow = Schema.Struct({
manualId: Schema.NullOr(Schema.String),
})

const toEntry = (row: typeof EntryRow.Type, rates: RateTable): Entry => ({
const toEntry = (
row: typeof EntryRow.Type,
rates: RateTable,
payees: ReadonlyMap<string, string>,
): Entry => ({
id: row.id,
accountId: row.accountId,
bookedOn: row.bookedOn,
Expand All @@ -76,6 +81,7 @@ const toEntry = (row: typeof EntryRow.Type, rates: RateTable): Entry => ({
excludedFromSpending: row.excludedFromSpending ?? false,
},
note: row.note,
payee: payees.get(merchantSignature(row.description)) ?? null,
oneOff: row.oneOff,
manualId: row.manualId,
converted:
Expand Down Expand Up @@ -121,14 +127,26 @@ const make = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient
const exchangeRates = yield* ExchangeRates

/** Entries with their amount in reais when they are in another currency. */
const findPayees = SqlSchema.findAll({
Request: Schema.Void,
Result: Schema.Struct({ signature: Schema.String, name: Schema.String }),
execute: () => sql`SELECT signature, name FROM payee_names`,
})

/**
* Entries with the person's name for their merchant, and their amount in
* reais when they are in another currency.
*/
const toEntries = (rows: ReadonlyArray<typeof EntryRow.Type>) =>
Effect.map(
exchangeRates.table(
Effect.gen(function* () {
const rates = yield* exchangeRates.table(
rows.map((row) => ({ currency: row.currency, from: row.bookedOn })),
),
(rates) => rows.map((row) => toEntry(row, rates)),
)
)
const payees = new Map(
(yield* findPayees(undefined)).map((row) => [row.signature, row.name]),
)
return rows.map((row) => toEntry(row, rates, payees))
})

// Per account and kind, the latest report still standing: each source's
// latest report of a day, unless a later read withdrew it.
Expand Down
18 changes: 18 additions & 0 deletions packages/server/src/api/definition/Categories.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as Schema from 'effect/Schema'
import * as HttpApiEndpoint from 'effect/http-api/HttpApiEndpoint'
import * as HttpApiGroup from 'effect/http-api/HttpApiGroup'
import * as HttpApiSchema from 'effect/http-api/HttpApiSchema'

import {
CategoryExplanation,
Expand Down Expand Up @@ -235,6 +236,23 @@ export class CategoryDecisionsApi extends HttpApiGroup.make('categoryDecisions')
success: CategoryExplanation,
error: EndpointErrors,
}),
HttpApiEndpoint.post('decideMany', '/category-decisions', {
/**
* The person's category for several entries at once, as `decide`
* sets it for one. All of them are decided or, when an entry or the
* category is unknown, none.
*/
payload: Schema.Struct({
entryIds: Schema.Array(Schema.String).check(
Schema.isMinLength(1),
Schema.isMaxLength(500),
),
categoryId: Schema.String,
learn: Schema.optional(Schema.Boolean),
}),
success: HttpApiSchema.NoContent,
error: EndpointErrors,
}),
HttpApiEndpoint.post('confirm', '/entries/:entryId/category/confirm', {
params: entryParams,
success: CategoryExplanation,
Expand Down
2 changes: 2 additions & 0 deletions packages/server/src/api/definition/Entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export const Entry = Schema.Struct({
category: Schema.NullOr(EntryCategory),
/** The person's note on the movement. */
note: Schema.NullOr(Schema.String),
/** The person's readable name for the merchant; show it instead of the description. */
payee: Schema.NullOr(Schema.String),
/** Marked by the person as one-off: counted in its month, left out of averages. */
oneOff: Schema.Boolean,
/** Set when the person typed the movement in: the id to edit or delete it with. */
Expand Down
19 changes: 18 additions & 1 deletion packages/server/src/api/definition/Manual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,17 @@ export const EntryOneOff = Schema.Struct({
oneOff: Schema.Boolean,
})

export const EntryPayee = Schema.Struct({
entryId: Schema.String,
payee: Schema.NullOr(Schema.String),
})

const externalParams = { externalId: Schema.String }

/**
* What the person types in: transactions (facts from the `manual` source,
* edited as new versions), balances they inform (checkpoints of the
* balance proof), notes on entries and one-off marks.
* balance proof), notes on entries, one-off marks and payee names.
*/
export class ManualApi extends HttpApiGroup.make('manual')
.add(
Expand Down Expand Up @@ -115,5 +120,17 @@ export class ManualApi extends HttpApiGroup.make('manual')
success: EntryOneOff,
error: EndpointErrors,
}),
HttpApiEndpoint.put('setPayee', '/entries/:entryId/payee', {
params: { entryId: Schema.String },
/**
* A readable name for the entry's merchant, shown for every movement
* of that merchant; null or blank clears it.
*/
payload: Schema.Struct({
name: Schema.NullOr(Schema.String.check(Schema.isMaxLength(80))),
}),
success: EntryPayee,
error: EndpointErrors,
}),
)
.prefix('/api') {}
41 changes: 41 additions & 0 deletions packages/server/src/api/handlers/Categories.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,47 @@ describe('categories API', () => {
}).pipe(Effect.provide(apiTest())),
)

it.effect('decides several entries at once, or none of them', () =>
Effect.gen(function* () {
const { client, later, earlier } = yield* bakery
const decideMany = (entryIds: Array<string>, categoryId: string) =>
client.categoryDecisions.decideMany({
payload: { entryIds, categoryId, learn: false },
})
const categoryOf = (entryId: string) =>
client.categoryDecisions
.explain({ params: { entryId } })
.pipe(Effect.map((explained) => explained.categoryId))
const unknownEntry = yield* decideMany(
[later.id, 'missing'],
'groceries',
).pipe(Effect.flip)
const untouched = yield* categoryOf(later.id)
const unknownCategory = yield* decideMany([later.id], 'nope').pipe(
Effect.flip,
)
yield* decideMany([later.id, earlier.id], 'groceries')
const patterns = yield* client.categoryStore.patterns()

assert.deepStrictEqual(
{
unknownEntry: reasonOf(unknownEntry),
untouched,
unknownCategory: reasonOf(unknownCategory),
decided: [yield* categoryOf(later.id), yield* categoryOf(earlier.id)],
learned: patterns.length,
},
{
unknownEntry: ['NotFound', 'entry_not_found'],
untouched: null,
unknownCategory: ['NotFound', 'category_not_found'],
decided: ['groceries', 'groceries'],
learned: 0,
},
)
}).pipe(Effect.provide(apiTest())),
)

it.effect('previews a store edit before applying it to history', () =>
Effect.gen(function* () {
const { client, later, earlier } = yield* bakery
Expand Down
7 changes: 7 additions & 0 deletions packages/server/src/api/handlers/Categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,13 @@ export const CategoryDecisionsHandlers = HttpApiBuilder.group(
...(payload.learn === undefined ? {} : { learn: payload.learn }),
})
.pipe(then(params.entryId), respond('categoryDecisions.decide')),
decideMany: ({ payload }) =>
settle(
categorizer.decideMany(payload.entryIds, payload.categoryId, {
origin: 'transaction_list',
...(payload.learn === undefined ? {} : { learn: payload.learn }),
}),
).pipe(Effect.asVoid, respond('categoryDecisions.decideMany')),
confirm: ({ params }) =>
categorizer
.confirm(params.entryId)
Expand Down
71 changes: 71 additions & 0 deletions packages/server/src/api/handlers/Manual.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,77 @@ describe('manual entries API', () => {
}).pipe(Effect.provide(apiTest())),
)

it.effect(
'names every movement of a merchant with the person’s payee name',
() =>
Effect.gen(function* () {
const { client, account } = yield* checking
const typed = (bookedOn: string, description: string) =>
client.manual.createTransaction({
payload: {
accountId: account.id,
bookedOn,
amountCents: -12_000,
description,
},
})
const first = yield* typed(
'2026-09-03',
'PIX ENVIADO 03/09 JOAO P SILVA',
)
yield* typed('2026-10-03', 'PIX ENVIADO 03/10 JOAO P SILVA')
yield* typed('2026-10-04', 'Padaria Real')
const short = yield* typed('2026-10-05', 'COMPRA C6')
const payees = () =>
client.entries
.list({ query: { accountId: account.id } })
.pipe(
Effect.map(({ entries }) =>
entries.map((entry) => [entry.description, entry.payee]),
),
)
const named = yield* client.manual.setPayee({
params: { entryId: first.entryId! },
payload: { name: ' Diarista João ' },
})
const shortName = yield* client.manual.setPayee({
params: { entryId: short.entryId! },
payload: { name: 'Banco C6' },
})
const shown = yield* payees()
yield* client.manual.setPayee({
params: { entryId: first.entryId! },
payload: { name: null },
})
const cleared = yield* payees()
const missing = yield* client.manual
.setPayee({ params: { entryId: 'nope' }, payload: { name: 'x' } })
.pipe(Effect.flip)
assert.deepStrictEqual(
{
named: [named.payee, shortName.payee],
shown,
cleared: cleared.map(([, payee]) => payee),
missing: [
missing._tag,
'reason' in missing ? missing.reason : null,
],
},
{
named: ['Diarista João', 'Banco C6'],
shown: [
['COMPRA C6', 'Banco C6'],
['Padaria Real', null],
['PIX ENVIADO 03/10 JOAO P SILVA', 'Diarista João'],
['PIX ENVIADO 03/09 JOAO P SILVA', 'Diarista João'],
],
cleared: ['Banco C6', null, null, null],
missing: ['NotFound', 'entry_not_found'],
},
)
}).pipe(Effect.provide(apiTest())),
)

it.effect(
'checks an informed balance in the proof, and stops when the person withdraws it',
() =>
Expand Down
6 changes: 5 additions & 1 deletion packages/server/src/api/handlers/Manual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const ManualHandlers = HttpApiBuilder.group(
const notes = yield* Notes
// A typed-in change resolves its entry in the request; its category and
// pairs are rebuilt in reactors, so it answers once those show it too.
// Notes and one-off marks are stored as they are.
// Notes, one-off marks and payee names are stored as they are.
const settle = settled(yield* Reactors)
return handlers.handleAll({
createTransaction: ({ payload }) => {
Expand Down Expand Up @@ -46,6 +46,10 @@ export const ManualHandlers = HttpApiBuilder.group(
notes
.setOneOff(params.entryId, payload.oneOff)
.pipe(respond('manual.setOneOff')),
setPayee: ({ params, payload }) =>
notes
.setPayee(params.entryId, payload.name)
.pipe(respond('manual.setPayee')),
})
}),
)
Loading
Loading