Skip to main content

GL Engine API Reference

Service-layer API for the General Ledger Engine. All functions require a QueryContext for tenant-scoped execution.

QueryContext

interface QueryContext {
tenantId: string; // UUID - tenant isolation via RLS
userId?: string; // UUID - audit trail attribution
moduleSource?: string; // Source module identifier
}

Account Service (account.service.ts)

createAccount(ctx, input): Promise

Creates a new account in the Chart of Accounts.

FieldTypeRequiredDescription
accountNumberstringYesHierarchical number (e.g., "1.1.01")
accountNamestringYesDisplay name
accountTypeAccountTypeYesASSET, LIABILITY, EQUITY, REVENUE, EXPENSE
parentIdstringNoParent account UUID
isHeaderbooleanNoHeader (synthetic) account flag
spedNaturaSPEDNaturaNoSPED natura code (auto-derived if omitted)
currencystringNoAccount currency (default: BRL)

updateAccount(ctx, id, input): Promise

Updates mutable fields (name, description, SPED mappings, metadata).

deactivateAccount(ctx, id): Promise

Deactivates account. Fails if account has non-zero balance.

getAccountTree(ctx, filters?): Promise <AccountNode[] >

Returns hierarchical account tree. Filters: accountType, status, search.

getAccountByNumber(ctx, accountNumber): Promise

Lookup by account number. Throws ACCOUNT_NOT_FOUND if missing.


Journal Service (journal.service.ts)

createJournalEntry(ctx, input): Promise

Creates a DRAFT journal entry with lines.

FieldTypeRequiredDescription
referenceNumberstringYesUnique reference (idempotency key)
entryDatestringYesEntry date (YYYY-MM-DD)
descriptionstringYesMax 500 chars
moduleSourceModuleSourceYesMANUAL, BUDGET, FORECAST, etc.
linesCreateJournalLineInput[]YesMin 2 lines, debits must equal credits

Line fields: accountNumber, debitAmount, creditAmount, originalCurrency, exchangeRate, costCenterId, projectId, dimensions, description.

postJournalEntry(ctx, id): Promise

Transitions DRAFT -> POSTED. Triggers:

  • Period state validation (must be OPEN)
  • Balance update (materializes to gl_account_balances)
  • Audit log entry

reverseJournalEntry(ctx, id, input): Promise

Creates a reversing entry (swapped debits/credits) and marks original as REVERSED.

FieldTypeRequiredDescription
referenceNumberstringYesReference for reversal entry
entryDatestringYesReversal date
descriptionstringNoOverride description

getJournalEntry(ctx, id): Promise

Returns entry with all lines.

searchJournalEntries(ctx, query): Promise <PaginatedResult >

Paginated search with filters: status, moduleSource, periodId, dateFrom, dateTo, search.


Period Service (period.service.ts)

createFiscalYear(ctx, year, startMonth?): Promise <FiscalPeriod[] >

Creates 12 monthly periods + 2 adjustment periods (13, 14). All start in FUTURE state.

openPeriod(ctx, periodId): Promise

Transitions FUTURE -> OPEN. Only OPEN periods accept posted entries.

closePeriod(ctx, periodId): Promise

Transitions OPEN -> CLOSED. Performs balance verification first. Carries forward balances to next period.

lockPeriod(ctx, periodId): Promise

Transitions CLOSED -> LOCKED. Permanently seals the period.

getPeriod / getPeriodsByYear / getPeriodForDate

Query functions for period lookup.


Balance Service (balance.service.ts)

verifyBalances(ctx, periodId): Promise

Compares stored balances against recomputed values from journal lines. Returns discrepancies.

getAccountBalance(ctx, accountId, periodId): Promise <AccountBalance | null >

Single account balance lookup for a period.

getAccountLedger(ctx, accountId, dateRange): Promise <LedgerEntry[] >

Chronological entries for an account with running balance.


Report Service (report.service.ts)

getTrialBalance(ctx, periodId, filters?): Promise

Trial balance with totals. Filters: accountType, includeZeroBalances.

getBalanceSheet(ctx, periodId): Promise

Balance sheet grouped by ASSET, LIABILITY, EQUITY. Includes isBalanced check.

getIncomeStatement(ctx, periodId): Promise

P&L grouped by REVENUE, EXPENSE. Computes netIncome.


Currency Service (currency.service.ts)

setExchangeRate(ctx, input): Promise

Upserts exchange rate (from/to/type/date is the unique key).

FieldTypeRequiredDescription
fromCurrencystringYesSource currency (e.g., "USD")
toCurrencystringYesTarget currency (e.g., "BRL")
rateTypeRateTypeYesSPOT, AVERAGE, CLOSING
ratenumberYesExchange rate value
effectiveDatestringYesDate rate is effective

getExchangeRate(ctx, from, to, rateType, date): Promise <ExchangeRate | null >

Returns most recent rate on or before the given date. Returns null if none found.

revalueAccounts(ctx, periodId, rateType): Promise

Revalues all foreign-currency account balances using the specified rate type at period end.


SPED Service (sped.service.ts)

exportSPED_ECD(ctx, fiscalYear, config): Promise

Full ECD export pipeline:

  1. Create export record (GENERATING)
  2. Pre-validate (CNPJ, balances, mappings, BS equation)
  3. Generate registros (0000, I010, I030, I050, I051, I155, I200, I250, 9999)
  4. Encode to ISO-8859-1
  5. SHA-256 hash
  6. Store result (COMPLETED / FAILED)

Returns SPEDExportResult with fileContent (Buffer), fileHash, recordCount.


Audit Service (audit.service.ts)

getAuditTrail(ctx, filters): Promise <PaginatedResult >

Paginated audit log query. Filters: tableName, recordId, action, userId, dateFrom, dateTo.

getEntityHistory(ctx, tableName, recordId): Promise <AuditEntry[] >

Complete history for a specific record, ordered chronologically.


AI Service (ai.service.ts)

queryNaturalLanguage(ctx, question): Promise

Translates natural language to SQL with guardrails (read-only, tenant-filtered). Returns results only if confidence >= 0.7.

detectAnomalies(ctx, periodId): Promise

Scans for: unusual amounts (3-sigma), off-hours posting, round numbers, high reversal rates, period-end stuffing.

suggestAccountMapping(ctx, description): Promise <AccountSuggestion[] >

Returns up to 5 account suggestions based on description keyword matching.

classifyTransaction(ctx, input): Promise

Wraps suggestAccountMapping with primary/alternative account format.


Error Codes

CodeNameDescription
GL_001UNBALANCED_ENTRYDebits != Credits
GL_002INSUFFICIENT_LINESLess than 2 lines
GL_010ACCOUNT_NOT_FOUNDAccount lookup failed
GL_011ACCOUNT_HAS_BALANCECannot deactivate with balance
GL_020PERIOD_NOT_OPENPeriod is not in OPEN state
GL_021PERIOD_LOCKEDPeriod is permanently locked
GL_030ENTRY_ALREADY_POSTEDCannot re-post
GL_031ENTRY_ALREADY_REVERSEDCannot reverse twice
GL_040BALANCE_VERIFICATION_FAILEDDiscrepancies found
GL_050SPED_VALIDATION_FAILEDPre-export validation failed
GL_060IMMUTABLE_RECORDAudit log modification blocked