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.
| Field | Type | Required | Description |
|---|---|---|---|
| accountNumber | string | Yes | Hierarchical number (e.g., "1.1.01") |
| accountName | string | Yes | Display name |
| accountType | AccountType | Yes | ASSET, LIABILITY, EQUITY, REVENUE, EXPENSE |
| parentId | string | No | Parent account UUID |
| isHeader | boolean | No | Header (synthetic) account flag |
| spedNatura | SPEDNatura | No | SPED natura code (auto-derived if omitted) |
| currency | string | No | Account 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.
| Field | Type | Required | Description |
|---|---|---|---|
| referenceNumber | string | Yes | Unique reference (idempotency key) |
| entryDate | string | Yes | Entry date (YYYY-MM-DD) |
| description | string | Yes | Max 500 chars |
| moduleSource | ModuleSource | Yes | MANUAL, BUDGET, FORECAST, etc. |
| lines | CreateJournalLineInput[] | Yes | Min 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.
| Field | Type | Required | Description |
|---|---|---|---|
| referenceNumber | string | Yes | Reference for reversal entry |
| entryDate | string | Yes | Reversal date |
| description | string | No | Override 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).
| Field | Type | Required | Description |
|---|---|---|---|
| fromCurrency | string | Yes | Source currency (e.g., "USD") |
| toCurrency | string | Yes | Target currency (e.g., "BRL") |
| rateType | RateType | Yes | SPOT, AVERAGE, CLOSING |
| rate | number | Yes | Exchange rate value |
| effectiveDate | string | Yes | Date 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:
- Create export record (GENERATING)
- Pre-validate (CNPJ, balances, mappings, BS equation)
- Generate registros (0000, I010, I030, I050, I051, I155, I200, I250, 9999)
- Encode to ISO-8859-1
- SHA-256 hash
- 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
| Code | Name | Description |
|---|---|---|
| GL_001 | UNBALANCED_ENTRY | Debits != Credits |
| GL_002 | INSUFFICIENT_LINES | Less than 2 lines |
| GL_010 | ACCOUNT_NOT_FOUND | Account lookup failed |
| GL_011 | ACCOUNT_HAS_BALANCE | Cannot deactivate with balance |
| GL_020 | PERIOD_NOT_OPEN | Period is not in OPEN state |
| GL_021 | PERIOD_LOCKED | Period is permanently locked |
| GL_030 | ENTRY_ALREADY_POSTED | Cannot re-post |
| GL_031 | ENTRY_ALREADY_REVERSED | Cannot reverse twice |
| GL_040 | BALANCE_VERIFICATION_FAILED | Discrepancies found |
| GL_050 | SPED_VALIDATION_FAILED | Pre-export validation failed |
| GL_060 | IMMUTABLE_RECORD | Audit log modification blocked |