Todos os caminhos abaixo usam /index.php/apps/librefinance/api. Identidade é fornecida pela autenticação Nextcloud. IDs de espaço pertencem aos dados da aplicação; não são grupos Nextcloud nem IDs da empresa fiscal.
POST /spaces: {"name":"Tesouraria","kind":"collective","currency":"BRL"}
Resposta 201: {"id":1,"name":"Tesouraria","kind":"collective","currency":"BRL","role":"owner"}
Tipos: personal, collective, organization. A criação continua restrita a BRL com duas casas decimais; não há ativação de novas moedas.
As listas GET /spaces, GET /spaces/archived,
GET /saas/v1/environments/{environmentId}/workspaces e
GET /spaces/{spaceId}/accounts incluem, em cada registro autorizado,
currency (código armazenado), currencyPrecision (escala inteira ou
null) e currencyMetadataVersion (versão do registro de moedas).
Por exemplo, BRL retorna precisão 2, JPY retorna 0 e KWD retorna 3 no
registro versão 1. A precisão é metadado de leitura do registro atual,
não uma autorização de escrituração em moeda estrangeira nem um snapshot
histórico. Códigos históricos não reconhecidos permanecem inalterados e
retornam precisão null; consumidores não devem presumir duas casas.
Os valores monetários, as regras de acesso e os contratos de escrita
permanecem inalterados.
POST /spaces/1/members: {"uid":"user2","role":"operator"}
POST /spaces/1/groups: {"gid":"cooperados","role":"viewer"}
Resposta: {"ok":true}.
DELETE /spaces/1/members/{uid} e DELETE /spaces/1/groups/{gid} revogam imediatamente a concessão correspondente. Não é permitido revogar a propriedade do espaço.
Papéis: viewer (consulta), auditor (consulta), operator (lançamentos), manager (lançamentos, contas, acessos), owner (total). Acesso a outro espaço resulta em 404; violação de papel em espaço acessível resulta em 403. Owner não é transferível nesta versão.
POST /spaces/1/accounts: {"code":"1010","name":"Checking account","class":"asset","isBank":true}
Resposta 201: conta criada com saldo inicial zero; moeda herdada do espaço.
Classes: asset, liability, equity, revenue, expense. Código é único por espaço.
POST /spaces/1/journals:
{
"debitId": 1, "creditId": 3, "amountMinor": 2599,
"date": "2026-11-20", "memo": "Receita de teste",
"externalKey": "api:synthetic-example-001"
}Resposta 201: {"id":1,"replayed":false}. A segunda submissão com a mesma chave e o mesmo conteúdo retorna o mesmo ID com replayed:true. Mesma chave com dados diferentes retorna 409. O valor sempre usa unidades menores inteiras, sem ponto flutuante.
O débito registra +amountMinor, o crédito registra -amountMinor; a soma é zero. A API é deliberadamente restrita a um par de contas neste marco. Lançamentos multi-linha exigirão contrato versionado.
GET /spaces/1/journals?beforeId=100 devolve até 50 registros, com nextBeforeId para paginação autorizada.
POST /spaces/1/journals/10/reverse cria um lançamento oposto vinculado ao original
no mesmo espaço e preserva o histórico. A primeira chamada retorna HTTP 200 com
o ID do estorno e replayed: false. Uma nova chamada autorizada retorna o mesmo
ID com replayed: true quando já existe um estorno vinculado. Uma chave de
idempotência igual à chave histórica de estorno pode pertencer a um lançamento
comum. Nesse caso, o estorno e a repetição do lançamento comum retornam seus
respectivos IDs. As restrições de acesso e de vínculos com módulos também se
aplicam às repetições do estorno. Se a disputa pela gravação persistir, a API
pode retornar HTTP 409 com {"error":"concurrent_change"}. O cliente pode
repetir a mesma chamada de estorno.
GET /spaces/1/contacts?afterId=0 lista até 50 por página e retorna nextAfterId para continuação. Leitura exige vínculo ao espaço; criação/edição exige manager ou owner.
POST /spaces/1/contacts: {"name":"Cliente sintético","kind":"customer","email":"user@example.invalid","taxId":"00.000.000/0000-00"}
Resposta 201: objeto de contato com id, nome, tipo, email, tax_id e ativo.
PUT /spaces/1/contacts/{contactId}: exige nome, kind e admite email, taxId e active.
Omitir active mantém o estado atual; false arquiva e true restaura explicitamente.
Kind é customer, vendor ou both. Tax ID é um identificador cadastral, não uma verificação fiscal de CPF/CNPJ. IDs de outro espaço retornam 404.
GET /spaces/1/items?afterId=0 lista de forma paginada.
POST /spaces/1/items:
{"sku":"SERV-001","name":"Serviço sintético","kind":"service","unitPriceMinor":25000,"description":"Descrição"}
Resposta 201: objeto de item com id, sku, name, kind, unit_price_minor, currency, active, unit_code, unit_label, sale_price_minor, purchase_price_minor e pricing_mapping (somente leitura, catalog-item-pricing.v1).
PUT /spaces/1/items/{itemId}: atualização com sku, name, kind, unitPriceMinor, description e active.
Unidade e preços separados (mapeamento catalog-item-pricing.v1), todos opcionais em POST e PUT:
unitCode (até 16 caracteres A-Z 0-9 . _ -, normalizado para maiúsculas), unitLabel (texto aparado de até 40 pontos de código Unicode, sem caracteres de controle),
salePriceMinor e purchasePriceMinor (inteiros em centavos, 0 a 9000000000000, na moeda do espaço).
unitPriceMinor continua sendo o preço legado e obrigatório; não é copiado para os preços de venda/compra.
Semântica: null na resposta significa ausente (itens anteriores à migração permanecem com null); 0 é gratuito explícito.
No PUT, para os quatro campos, chave omitida preserva o valor armazenado e null explícito limpa o valor.
unitCode e unitLabel são definidos por strings (texto em branco limpa a unidade para null); um valor que não seja string
(número, booleano, lista) ou fora das regras acima retorna 422 invalid_unit_code ou invalid_unit_label.
salePriceMinor e purchasePriceMinor são definidos por inteiros; strings, decimais, negativos e valores acima do limite
retornam 422 invalid_sale_price ou invalid_purchase_price.
Editar o catálogo não altera linhas de documentos já emitidos, que guardam seus próprios valores. Leitura exige items.read;
escrita exige items.manage (403 sem permissão). SKU duplicado retorna 409 sku_conflict.
Preços são inteiros em centavos (BRL) no domínio atual, inclusive zero. Estoque, tabelas de preços e descontos ainda não estão presentes. Os módulos opcionais de fatura comercial e regras genéricas de imposto estão disponíveis, mas não equivalem a controle fiscal certificado ou emissão de nota.
GET /spaces/{spaceId}/transactions?bankAccountId=1&status=pending&from=2026-11-01&through=2026-11-30 consulta movimentações importadas no espaço autorizado. As datas de lançamento do extrato (booking_date) são inclusivas e independentes: omita from ou through para deixar o respectivo limite aberto. Use datas ISO gregorianas (YYYY-MM-DD); datas inválidas ou intervalo invertido retornam 422.
Os filtros de conta, situação e data são aplicados antes da paginação por ID. A resposta mantém transactions (até 50 registros) e nextAfterId; use os mesmos filtros nas páginas seguintes. Movimentações pendentes são evidências, não lançamentos no razão. Esta consulta não calcula totais de extrato.
POST /spaces/{spaceId}/imports/preview recebe o mesmo arquivo e conta de
destino do contrato de importação existente:
{"bankAccountId":1,"format":"csv","csv":"id,date,amount,description\nmov-001,2026-11-20,-25.90,Pagamento sintético\n"}Para OFX, informe format: "ofx" e ofx com o conteúdo, sem csv.
O limite continua sendo 256 KiB e 500 movimentações; a prévia aplica o
mesmo parser estrito e a mesma autorização de importação, incluindo a
conta bancária ativa e as políticas vigentes. A moeda do OFX, quando
informada, deve corresponder à da conta. O contrato de importação
continua usando duas casas decimais.
O retorno 200 (contractVersion: 1) informa a conta, formato, moeda,
currencyPrecision, counts de new, replayed e conflicting,
e rows com a posição lógica, identificador externo normalizado, data,
valor inteiro em unidades mínimas, descrição e classificação. Uma linha
repetida tem o mesmo identificador na mesma conta, data, valor e descrição.
Conflitos não são sobrescritos. Se o parser rejeitar o arquivo inteiro,
counts será nulo, sem linhas parciais, e fileError terá
classification (malformed/unsupported), code e row quando
identificável (posição lógica dos registros, não linha física do arquivo).
Não há gravação de extrato, auditoria, arquivo ou lançamento nesta etapa;
postingCreated é sempre falso.
Quando ready for verdadeiro, a resposta inclui previewHash.
Confirme com POST /spaces/{spaceId}/imports reenviando o mesmo
payload e esse hash. Ele é vinculado à identidade autenticada, gestão,
conta, formato, conteúdo recebido, dados normalizados, moeda, políticas
efetivas e evidência existente pertinente. Não é uma credencial ou
reserva permanente. A confirmação reserva a conta na transação, revalida
a autorização e o parser, consulta o estado corrente e rejeita uma
prévia alterada com 409 (bank_import_preview_changed); revogação de
acesso ou conta indisponível mantém 403/404. Em caso de erro ou resposta
incerta, faça nova prévia. Nunca confirme automaticamente. A criação
registra somente evidência pendente e sua auditoria, não dinheiro
contabilizado. A resposta 201 mantém imported, skipped e currency.
O endpoint de importação continua compatível com clientes antigos que
não enviam previewHash; nesses casos aplica as validações e
idempotência existentes sem exigir etapa anterior. A interface nativa
exige confirmação após a prévia. Alterar arquivo, conta, formato ou
gestão invalida a prévia visível.
GET /spaces/{spaceId}/general-ledger?accountId=1&from=2026-01-01&through=2026-12-31
consulta lançamentos efetivados da conta autorizada, inclusive inativa, por
data efetiva inclusiva e ID do registro contábil. A base
posted_debit_positive representa a escrituração atual: débito positivo,
crédito negativo. Não converte regime de caixa para competência e não
inclui compromissos, projeções ou extratos pendentes. O contrato atual é BRL
com duas casas decimais; moedas divergentes são recusadas, sem conversão
implícita. As políticas e a capacidade reports.read são verificadas pelo servidor.
O objeto retorna conta, moeda, precisão, período, openingMinor,
closingMinor, pageOpeningMinor, rowCount, snapshot, rows e
nextCursor. Valores monetários são strings decimais inteiras em
unidades mínimas, sem arredondamento; débitos/créditos são magnitudes não
negativas, amountMinor tem sinal e runningMinor é o saldo acumulado.
Saldo inicial soma registros anteriores a from; saldo final inclui
todos até through. A página contém até 50 registros, ordenados por
data efetiva e ID de registro; o saldo não depende do tamanho da página.
Para continuar, reenvie os mesmos filtros, snapshot e afterDate/
afterId de nextCursor. Um estado alterado retorna 409
(ledger_report_changed); reaplique o relatório. Não é um snapshot
histórico retido no servidor. Valores fora da faixa inteira de 64 bits
são recusados em vez de aproximados.
GET /spaces/{spaceId}/general-ledger/journals/{journalId} revalida
as permissões de leitura e retorna o lançamento efetivado e seus lados
contábeis na gestão. Estornos permanecem separados do original, com
reversedJournalId; nenhum lançamento é removido ou duplicado.
GET /spaces/{spaceId}/general-ledger/export usa os mesmos parâmetros,
com snapshot obrigatório e capacidade reports.export em cada
página. Cada página de exportação contém até 250 registros para reduzir
as leituras repetidas; a paginação interativa continua limitada a 50.
O cliente nativo começa sem cursor, segue todos os cursores, confere
contagem, ordenação e saldos, e só então disponibiliza o CSV.
Não limita a exportação às linhas visíveis. A exportação reúne os
fragmentos CSV na memória do navegador; não é streaming para disco.
O CSV inclui linhas explícitas de abertura/fechamento e referências a
lançamentos, inclusive estornos. Importe colunas de valores como texto
em planilhas que arredondam inteiros extensos; descrições são escapadas
e neutralizadas contra fórmulas. Para grandes volumes, use paginação
da API e um consumidor incremental. Falha ou alteração durante a leitura
não gera arquivo parcial. Leitura e exportação compartilham um orçamento
por gestão: duas consultas simultâneas, até 120 reservas de início por
minuto (60 por slot), e quatro consultas simultâneas na instalação inteira.
A reserva é contabilizada antes da consulta, inclusive se o processo for
interrompido. No PostgreSQL, a confirmação da reserva é seguida de uma nova
aquisição dos bloqueios transacionais; se houver concorrência nesse intervalo,
a reserva permanece contabilizada, mas nenhuma consulta é iniciada.
O servidor retorna 429 com ledger_report_busy e
Retry-After: 5 quando o orçamento está ocupado. Reenvie o mesmo
snapshot e cursor; o cliente nativo repete a página de exportação com
espera limitada e nunca baixa um arquivo incompleto. Os bloqueios não
expiram enquanto a consulta está em execução; o encerramento da conexão
(PostgreSQL/MariaDB) ou do processo (SQLite em host único) libera o slot,
sem depender do relógio de cada nó. Os arquivos de bloqueio SQLite ficam
no diretório de dados privado; não devem ser removidos enquanto houver
processos ativos. A saturação global pode causar 429 em outras gestões:
o limite não garante capacidade reservada por gestão nem um prazo máximo
de consulta. O orçamento não limita o número total de linhas.
As rotas existentes GET/POST /spaces/{spaceId}/contacts e PUT /spaces/{spaceId}/contacts/{contactId} mantêm os campos anteriores e passam a retornar profile e a aceitar esse objeto opcional nas escritas, com os campos contactPerson (160 caracteres), phone (60), website (255, HTTP/HTTPS), billingAddress e shippingAddress. Cada endereço tem line1 e line2 (255 cada), city e region (120 cada), postalCode (32) e country (código ISO 3166-1 alpha-2 em maiúsculas da lista já usada pelo sistema). O endereço de cobrança não é copiado para o endereço de entrega. A resposta sempre contém o objeto profile, com os objetos billingAddress e shippingAddress. Seus campos escalares são string ou null; em contatos antigos, os campos escalares ainda não preenchidos são null. Na atualização, omitir profile ou um campo preserva o valor anterior; null ou string vazia limpa um campo, null no endereço limpa somente aquele endereço. Campos desconhecidos, tipo incorreto, caracteres de controle e país não reconhecido retornam invalid_contact_profile (422). Nenhuma jurisdição, identificação fiscal ou relação de identidade é inferida dos endereços. Mesmo nome pode identificar registros distintos. A referência estável continua sendo contactId; o arquivamento mantém dados e vínculos. Faturas emitidas e lançamentos não são modificados.
GET /spaces/{spaceId}/transactions/{transactionId}/reconciliation-candidates?windowDays=3&afterId=0 é uma consulta de revisão, sem criação de registros, lançamentos ou vínculos. Requer as capacidades de conciliação, leitura e postagem do razão e uso da conta bancária ativa. A conta, a moeda, o valor com sinal e a data são obtidos exclusivamente do extrato pendente autorizado. A janela é inclusiva, de zero a trinta dias para cada lado da data do extrato (padrão três). A referência externa é devolvida como evidência, mas o identificador idempotente do lançamento não equivale a uma referência de origem bancária: sourceReferenceComparison é unavailable, sem associação inferida.
Os candidatos usam o mesmo espaço, conta, moeda e valor exato, com lançamento efetivado dentro da janela. São excluídos estornos, originais estornados, registros já conciliados e journals reivindicados pelo módulo bancário. Vínculos independentes de outros módulos não são tratados como conciliação. O resultado distingue unique, ambiguous, no_candidate e incomplete_lookup. candidateStatus descreve a classificação do conjunto filtrado, mesmo se uma página final contiver apenas um candidato; nextAfterId permite continuar, com os mesmos parâmetros, em ordem de ID e até 50 registros por página. Uma leitura não constitui reserva de candidato: as condições podem mudar, e a confirmação continua exigindo POST /transactions/{transactionId}/match, que revalida conta, valor, estado, autorização e reivindicação em transação. A revisão manual permanece disponível e a ausência de sugestões não autoriza criar um novo lançamento.
GET /spaces/{spaceId}/activity aceita from e through como limites inclusivos opcionais em datas ISO gregorianas. A data filtrada é a data efetiva do lançamento, o vencimento do compromisso ou a data do extrato, conforme a origem de cada movimentação. Os limites são combinados com os filtros existentes antes da paginação; mantenha os mesmos filtros ao utilizar nextCursor. O filtro não altera os valores nem transforma compromissos ou evidências em lançamentos realizados.
GET /spaces/{spaceId}/obligations/{obligationId}/recurrence-preview?count=2&stepMonths=1&endOfMonth=clamp prevê os próximos vencimentos de uma obrigação autônoma aberta e não paga. Os parâmetros são obrigatórios: count de 1 a 24, stepMonths de 1 a 12 e endOfMonth igual a clamp (ajustar para o último dia do mês) ou reject (rejeitar o dia indisponível). A previsão usa as datas originais de emissão e vencimento como âncoras, não cria títulos, não realiza lançamentos e não altera a obrigação consultada. Repetir a consulta com os mesmos dados retorna a mesma previsão. Entradas inválidas e modelos inelegíveis retornam 422; usuários sem acesso recebem 404.
GET /spaces/{spaceId}/invoices aceita issueFrom e issueThrough como limites inclusivos opcionais em datas ISO gregorianas (YYYY-MM-DD). O filtro restringe a data de emissão (issue_on) antes da paginação e é combinado com kind, status e cursor. Datas inválidas ou intervalo invertido retornam o erro invalid_invoice_period (422).
Both operations require the invoice.manage capability in the workspace, only apply to documents in draft status, and carry the revision the client displayed (expectedVersion, the version returned by GET /spaces/{spaceId}/invoices/{invoiceId}).
PUT /spaces/{spaceId}/invoices/{invoiceId}acceptsexpectedVersion,contactId,issueOn,dueOn,country, optionalregion,linesand optionalcustomFields, validated exactly as on creation (party, dates, currency, lines, tax snapshots). The totals are recomputed from the validated lines. The number, kind and ID never change. The response contains the newversion. A stale revision returnsinvoice_concurrent_change(409) and invalid data returns 422, both before any write. An audit entryinvoice.draft_updatedis recorded.DELETE /spaces/{spaceId}/invoices/{invoiceId}?expectedVersion=Nremoves the draft from the active worklist. Nothing is physically deleted: the row becomes an audited tombstone (statusremoved, auditinvoice.draft_removed) that keeps its ID, number (which stays reserved), lines and history, and is still readable by ID. Removed documents are excluded fromGET /spaces/{spaceId}/invoices(includingstatus=draftandstatus=attention) and can no longer be edited, issued or removed. Obligation, allocation, journal-claim or settlement evidence blocks removal withinvoice_has_dependents(409).- Issued, partially paid, paid or removed documents are refused with
invoice_not_draft(409); an unknown actor or workspace follows the usual authorization errors. POST /spaces/{spaceId}/invoices/{invoiceId}/issueaccepts an optionalexpectedVersion. When supplied, it must equal the draft's current revision (the one the approver reviewed); otherwiseinvoice_concurrent_change(409) is returned and nothing is written. A document that is not a draft when the request starts (removed or otherwise no longer a draft) returnsinvoice_not_draft(409); the status is checked before the revision, so a staleexpectedVersiondoes not change that. A removal or edit committed during the request, after the read and before the conditional update, returnsinvoice_concurrent_change(409) and nothing is written. Clients should reload oninvoice_concurrent_changeand retry only if the document is still a draft and the new revision has been reviewed, and stop oninvoice_not_draft. Issuing creates the obligation once and posts no journal entry. A database lock timeout or deadlock against a competing writer (including PostgreSQL SQLSTATE55P03) is reported after rollback asinvoice_concurrent_change. Omitting it keeps the previous behavior. The detail read (GET .../invoices/{invoiceId}) re-checks the header revision after reading lines and custom fields, so it never mixes revisions; if the document keeps changing it returnsinvoice_concurrent_change(409).- An issue and an edit or removal of the same draft are serialized by one compare-and-swap on status and version: exactly one can leave the observed revision, so no obligation is duplicated or orphaned and the ledger is not written before issuance.
GET /spaces/{spaceId}/invoice-duplicate-candidates accepts either the
existing document's positive invoiceId alone (plus the optional afterId
cursor), or explicit evidence: kind (invoice/bill), contactId (active,
workspace-scoped party), optional reference, issueOn (canonical
Gregorian date) and totalMinor (canonical positive decimal integer string
at the current workspace currency precision). Existing-document mode derives
all evidence from the authorized stored document and excludes that document
from the candidates. Evidence overrides in this mode are invalid.
The lookup always matches the same workspace, kind, contact and currency.
A candidate must have the same normalized reference OR the same exact total
and an issue date within three calendar days inclusive. The returned
matchReasons enumerate the matched evidence; each row is only a
possible_duplicate, not proof of identical origin, fraud or invalidity.
The three-day window is an explicit heuristic; amount alone or date alone
is insufficient. Unknown/invalid contact IDs and inaccessible documents
are not accepted. incomplete_evidence is distinct from no_candidate.
candidates pages are ordered by ascending ID, up to 50 per page, with
nextAfterId for the next page using the same evidence. The absence of a
candidate is not certification that a document is unique.
knownDocumentId identifies only the already stored native document in
detail mode. The native document ID is never an external origin identity.
Optional query parameters sourceNamespace, sourceCompany, resource and
sourceRecordId form the full origin key. They must be supplied all together
or not at all (otherwise 422 invalid_duplicate_evidence) and are rejected
with invoiceId. originIdentityStatus is:
verified_exact: create mode; the key matches a recorded identity in this workspace.originMatchholdsinvoiceId(native ID) andidentity(external key), kept separate. That document is reported only inoriginMatch, not among the possible duplicates, and the result is shown even when the party or reference evidence is incomplete.not_found: a complete key was supplied and no identity matches.not_supplied: no key was supplied.verified/unknown: detail mode;knownDocumentOriginlists the known document's identities, orunknownwhen none is recorded.
Every candidate has origin (status verified or unknown, plus
identities), so documents without a recorded identity are explicitly
unknown-origin. A document number or reference is never an origin identity and
a possible match never asserts a source-system identity; contractVersion
remains 1 and the new fields are additive.
No invoice, obligation, settlement, journal, or balance is written or
deleted. Existing invoice number uniqueness rules remain unchanged.
An origin identity is the complete key sourceNamespace, sourceCompany,
resource and sourceRecordId within one workspace, mapped to exactly one
native commercial document. sourceNamespace and resource are normalized to
lower case; company and record ID are exact source values (surrounding
whitespace trimmed). Limits: namespace 64, company 128, resource 32 and record
ID 128 characters from a restricted ASCII set; violations return 422
(invalid_origin_namespace, invalid_origin_company,
invalid_origin_resource, invalid_origin_record).
POST /spaces/{spaceId}/invoices/{invoiceId}/origin-identity (capability
invoice.manage) records one identity atomically. It returns 201 for a new
identity and 200 with replayed: true when the identical mapping already
exists, including concurrent replays. Mapping an existing identity to a
different document, or giving a document a second identity for the same
namespace and company, returns 409 origin_identity_conflict; nothing is
overwritten or merged. A document outside the workspace returns 404
invoice_not_found.
GET /spaces/{spaceId}/invoice-origin-identities?sourceNamespace=&sourceCompany=&resource=&sourceRecordId=
(capability invoice.read) returns {status: "verified", invoiceId, identity}
for an exact match in that workspace only. A miss, including an identity that
exists in another workspace, returns 404 origin_identity_not_found.
Document detail (invoice.origin) and list rows (origin) expose
{status: "verified"|"unknown", identities: [...]}. Documents without a
recorded identity, including every historical document, are unknown: no
provenance is guessed or backfilled, and recording an identity never changes
amounts, status, numbers or the append-only history of a document.
In the native create dialog, Check possible duplicates opens a read-only review using the selected party, document number, issue date and optional explicit source-document total (net of applicable withholdings and inclusive of applicable taxes). The evidence amount is not a draft line or a stored invoice total, and entering it is optional. In document details the review derives the stored evidence on the server and allows opening an authorized candidate through the usual detail action. Editing evidence invalidates previous results. Neither absence of matches nor dismissing the review changes the existing save/confirm/settlement behavior.
Scoped classifications (project, cost center, department, funding source, purpose) distinct from the chart of accounts and from categories. A definition or value grants no access to any record: every route reuses the workspace capabilities categories.read (lookup), categories.use (validation for new facts) and categories.manage (create, revise, archive), enforced on the server. Values are never deleted; archiving keeps them resolvable so facts that reference a stable ID stay valid. Identity is the string id; label is display text only and may change. Definition code values are unique (case-insensitive) within a workspace. Value code values are unique (case-insensitive) within their definition only, so the same value code may appear under different definitions: clients must key values by id or by the pair (definition, code), never by code alone.
Both list routes (definitions and values) return up to 50 records plus an integer nextAfterId. Start with afterId=0, pass the returned nextAfterId as afterId in the next request (keeping the other query parameters), and stop when nextAfterId is null.
parentId on value create and revise is a positive integer, a decimal string of 1 to 18 digits without leading zeros (so a value id returned by the API can be sent back unchanged), or null. On create, omitted and null both mean top level. On revise, omitting parentId keeps the current parent; only an explicit JSON null moves the value to the top level.
| Route | Purpose |
|---|---|
GET /spaces/{spaceId}/dimensions?afterId= |
Bounded (50) keyset list of definitions |
POST /spaces/{spaceId}/dimensions {code,label} |
Create definition (201); duplicate code 409 |
PUT /spaces/{spaceId}/dimensions/{definitionId}/archive {archived,expectedRevision} |
Archive or restore a definition (never deleted; values stay resolvable). While archived, values cannot be added or changed and forNewFact validation returns dimension_definition_archived (409). The definition revision also advances on every value-tree write; stale revision 409 |
GET /spaces/{spaceId}/dimensions/{definitionId}/values?afterId=&includeArchived= |
Bounded (50) keyset lookup; each value has id, code, label, parentId, status, revision, effectiveFrom, effectiveTo, selectable |
POST /spaces/{spaceId}/dimensions/{definitionId}/values {code,label,parentId?,effectiveFrom?,effectiveTo?} |
Create value (201); cycle, archived/foreign parent 422, duplicate code 409 |
PUT /spaces/{spaceId}/dimension-values/{valueId} {label,expectedRevision,parentId?|null} |
Relabel/reparent; omitting parentId preserves the current parent, an explicit parentId: null makes the value a root; stale revision 409 |
PUT /spaces/{spaceId}/dimension-values/{valueId}/archive {archived,expectedRevision} |
Archive or restore |
GET /spaces/{spaceId}/dimensions/{definitionId}/values/{valueId}?forNewFact=&onDate= |
Typed validation contract for postings, reports and migration |
Without forNewFact, any existing value in the workspace and definition resolves (historical meaning preserved). With forNewFact=1, an archived value, a value under an archived ancestor (dimension_value_archived) or, only when onDate is supplied, a value outside its effective range on that date (dimension_value_not_effective) is rejected. Without onDate effectiveness is not checked, so callers needing that guarantee must pass the fact date. A valid request to an inaccessible workspace returns HTTP 404 space_not_found. Malformed parameters (for example, an invalid cursor) can return 422 before the workspace check; validation of stored dimension data requires access to the workspace. Foreign definitions, values and parents are reported as dimension_value_not_found, dimension_definition_not_found (404) or dimension_foreign_parent (422). Dimension allocations are not persisted; they require the authoritative posting contract.
{"error":"permission_denied"} 403; {"error":"space_not_found"} 404; {"error":"idempotency_conflict"} 409; entrada inválida 422.
Falhas internas não devem revelar SQL, caminhos do host nem configurações.
GET /spaces/{spaceId}/cash-flow?from=2026-11-01&through=2026-11-30 mantém a agregação de todas as contas bancárias e de caixa. Informe bankAccountId para restringir os saldos e os movimentos mensais à conta bancária autorizada, inclusive inativa para consulta histórica. O resultado informa bankAccountId (0 para todas). Uma transferência interna é neutra na visão consolidada; na visão de uma conta, sua respectiva entrada ou saída compõe o saldo. Não são considerados compromissos futuros nem extratos pendentes.
Permissões granulares adicionais, estoque, contabilidade de múltiplas moedas, notas fiscais efetivamente emitidas, sincronização bancária online, migração integral do Akaunting, fechamento fiscal e demonstrações contábeis formais continuam fora desta versão. A importação pertence ao core; a NFS-e brasileira permanece um aplicativo opcional independente. A interface IA usa OCP\\TaskProcessing com prévia de dados e consentimento; o transporte MCP oferece quatro ferramentas de leitura, sem ferramentas de pagamento/contabilização. Ver OpenAPI, MCP/IA e testes.
The manager-only core API accepts normalized JSON to preview and confirm catalog, historical bank statement and paired-transfer imports. Source identity coverage is read-only, including account references and audit snapshots. Apply requires the exact returned preview hash and explicit confirmation. Existing mapped records remain idempotent, source conflicts are rejected, and bank movements are not posted to the ledger automatically.
Akaunting API client, remote connection setup, credentials, direct extraction and full migration are not part of this PR. Source mapping and historical reconciliation will be implemented separately.
GET /spaces/{spaceId}/exchange-rates?afterId=0 returns the supported currency metadata version, its deliberately bounded currency/precision map, up to 50 authorized rate snapshots in ID order and a nextAfterId cursor.
For dated selection, provide all three parameters together:
sourceCurrency=JPY&targetCurrency=KWD&asOf=2026-11-24.
Codes are trimmed and normalized to uppercase, then checked against the
bounded registry; the date is a canonical Gregorian date. Optionally add
sourceType=manual or sourceType=imported. Selection returns every
eligible snapshot for that exact directed pair with effectiveOn <= asOf,
without choosing the newest, inverting a rate or resolving ambiguity.
Filtering precedes ID-ordered pagination; use the same parameters with
each nextAfterId. The response includes the normalized selection (sourceType
is null for all sources); an authorized empty result is HTTP 200 with
rates=[], not an authorization failure. Partial/invalid selection is 422.
Omitting all selection parameters retains the existing historical list.
A caller without workspace capability receives the existing denial.
POST /spaces/{spaceId}/exchange-rates records a quote using sourceCurrency, targetCurrency, rate (a positive exact decimal string), effectiveOn (a real calendar date), sourceType (manual or imported) and sourceRef (a bounded non-secret provenance identifier). Rate means target major units per source major unit. The server resolves and stores both precisions. A successful recording returns HTTP 200 with rate and replayed; a canonical equivalent quote in the same book returns the original record. Corrections append new snapshots; there is no update/delete endpoint or automatic rate choice.
Read requires currency.rates.read; recording requires currency.rates.manage (manager or owner). Financial membership and SaaS restrictions remain authoritative. Unrelated books do not share rates. Source references are not credentials or URLs. No historical balance is converted, no journal is created, no bank/FX provider is contacted. Ledger activation and mixed currency posting remain separate deliverables.
These routes define fiscal years and periods of one workspace. Defining,
editing or preparing a period does not block, reject or change any posting;
no closing lock exists yet. Periods are separate from bank review periods,
due dates and agreement eligibility. Every route requires the workspace
capability workspace.configure (manager or owner) and is scoped by
spaceId; a viewer or operator receives 403 and a non-member 404. Identifiers
of another workspace return 404 (fiscal_year_not_found,
fiscal_period_not_found).
Dates are canonical calendar days (YYYY-MM-DD, years 1900-2100, 29 February
only in leap years) and both bounds are inclusive. A key matches
[a-z0-9][a-z0-9._-]{0,63} and is unique per workspace and table; labels have
up to 120 characters.
| Route | Purpose |
|---|---|
GET /spaces/{spaceId}/fiscal-years?afterId= |
Up to 50 years by ID cursor (nextAfterId), each with its periods, status, revision and contiguous |
POST /spaces/{spaceId}/fiscal-years |
key, label, startsOn, endsOn; creates a draft (201) |
PUT /spaces/{spaceId}/fiscal-years/{yearId} |
label, startsOn, endsOn, expectedRevision; draft only |
DELETE /spaces/{spaceId}/fiscal-years/{yearId}?expectedRevision= |
Draft only; removes its periods |
POST /spaces/{spaceId}/fiscal-years/{yearId}/periods |
key, label, startsOn, endsOn, expectedRevision (of the year) |
PUT /spaces/{spaceId}/fiscal-periods/{periodId} |
label, startsOn, endsOn, expectedRevision (of the period) |
DELETE /spaces/{spaceId}/fiscal-periods/{periodId}?expectedRevision= |
Draft year only |
POST /spaces/{spaceId}/fiscal-years/{yearId}/prepare |
expectedRevision; draft to ready_for_closure |
POST /spaces/{spaceId}/fiscal-years/{yearId}/reopen |
expectedRevision; back to draft |
GET /spaces/{spaceId}/fiscal-periods/lookup?date= |
Year and period covering the date (each null when absent) |
Lifecycle: draft -> ready_for_closure -> draft. Only a draft can be
edited or deleted. Preparing requires at least one period, the first starting
on the year start, every next period starting the day after the previous end,
and the last ending on the year end (fiscal_year_not_contiguous, 422);
preparing is a marker, not a lock. Changes to a year or its period set
increase the year revision; a stale expectedRevision returns 409
revision_conflict. Overlapping years or periods return 409
(fiscal_year_overlap, fiscal_period_overlap), a duplicate key 409
fiscal_key_conflict, a non-draft year 409 fiscal_year_not_draft; invalid
dates, ranges, keys or periods outside their year return 422. A year holds at
most 60 periods. Each mutation is serialized per workspace, runs in a
transaction and writes lf_audit rows (fiscal_year.*, fiscal_period.*).
FiscalPeriodService::resolve(spaceId, date) returns {year, period} for a
YYYY-MM-DD effective date using starts_on <= date <= ends_on (inclusive
at both ends), or nulls when the date is outside every definition. It checks
no capability: the posting path authorizes its own actor first. The HTTP
lookup requires workspace.configure and always reports
postingEnforcement: "none".
A future lock implementation must, in the same database transaction that inserts the journal: (1) resolve the period for the journal's effective date; (2) take a row lock on the matching period (and year) row, or the workspace row where the engine has no row locks; (3) re-read its status inside that transaction; and (4) reject or accept the posting before any insert, so a concurrent close cannot interleave. Status and revision must not be cached across the transaction. The current journal and payment paths do not call this contract.
Financial members can open Exchange rates under Manage / Finance and tax. Managers and owners can append rate evidence using the native Nextcloud dialog. The supported currency list is obtained from the scoped API; the form accepts a decimal string with a single decimal point or comma and sends a canonical decimal-point string, never a floating-point number. The read-only table displays the stored exact rate, quote ID, date, currency pair, both stored precisions, provenance and actor. To find dated evidence, select the source and target currencies, accounting date and optionally the source type, then choose Find rates. The list contains all matching immutable candidates, in pages of 50, without automatically choosing a rate. Select Preview conversion on a particular row and enter a signed amount in that snapshot's source currency (including zero, with a decimal point or comma and no grouping). The server verifies that the explicit ID still qualifies for the applied selection, calculates the exact target minor units using stored precision, and the interface displays the result at target precision. Changing the filters invalidates preview actions until they are reapplied; changing the amount invalidates its previous result. An empty selection is distinct from a failed or unauthorized request; permission loss clears visible evidence. No financial records are modified. A correction adds another immutable record. The screen does not change the ledger currency, choose a rate for a posting or convert balances. Workspace changes discard in-flight UI results.
GET /spaces/{spaceId}/exchange-rates/{rateId}/preview?sourceMinor=1000 is an authenticated read-only conversion using one explicitly selected, immutable snapshot within the current book. The amount is a canonical signed minor-unit integer (including zero); decimal/exponent forms and out-of-range input are rejected. Conversion uses the stored source and target precisions, never the current currency metadata or locale. The result contains the original snapshot, sourceMinor, targetMinor, rounding=half_away_from_zero and postingCreated=false. A missing or foreign snapshot returns 404, including when the caller may access both books. No rate is selected automatically and no accounting state changes. For an explicit dated selection, pass the same sourceCurrency, targetCurrency, asOf and optional sourceType query parameters to preview. The selected ID must satisfy the same predicate; a future, wrong-pair or wrong-source snapshot returns the same 404 as a missing/foreign ID. Without these parameters the backward-compatible historical preview is unchanged. The selection result is not a posting authorization.
The official Nextcloud extractor is exercised by composer openapi:pilot
in CI; see OPENAPI.md.
The strict pilot compares the generated operation inventory and checks key
request and response contracts. The installed
tests/integration/currency-rate-history.php suite independently verifies
real HTTP behavior. Recording returns 200 for new and replayed quotes;
the public legacy specification remains authoritative during the transition
and has known discrepancies described in OPENAPI.md. Native generation
does not change the API or replace the complete public specification yet.
The same strict native generation also covers the 20 operations of
AccountController, JournalController, ActivityController,
MovementController, TransferController and PaymentMethodController;
inventory, preserved semantics and remaining routes are in
OPENAPI.md.
URLs, verbs, parameter names, access rules and amounts are unchanged:
account creation, journal posting and payment-method creation answer 201,
every other success (including applying a movement or transfer import)
answers 200, and errors keep the {"error": code} envelope with 401, 403,
404, 409 and 422 where the existing error map returns them.
Compatibility note: GET /spaces/{spaceId}/journals returns created_at as
an integer and reversed_journal_id as an integer for a reversal journal and
null otherwise. The controller normalizes these two fields because the
service returns the raw database scalars; clients that already treated them
as numbers see no change.
The functional/original currency design records the future v2 ledger boundary. It does not change these implemented endpoints or activate foreign currencies. Existing BRL v1 monetary fields remain exact integer minor units with their current semantics. A future explicitly negotiated version must expose original and functional amount, currency and stored precision separately; quote identity, provenance, effective date, and adjustment/rounding policy are part of the immutable financial fact. A functional-only adjustment is distinguished from an original-unit movement. Never add unlike original units or present an unsupported mixed-currency journal as a two-leg BRL entry. Preserve authorization, idempotency and error semantics; unsupported v2 operations through v1 must fail explicitly. Versioned OpenAPI changes, migration and full writer/reader qualification are separate implementation work.