NEXEVES Mega Menu

How to Create Financial Reports in ERPNext

 · 14 min read

How to Create Financial Reports in ERPNext – Complete Technical & Functional Guide ERPNext Illustration

1. Understanding Financial Data Architecture in ERPNext

Financial reporting in ERPNext is entirely driven by its General Ledger (GL Entry) architecture, which acts as the foundational data source for all financial statements generated within the system. Every accounting transaction—whether originating from a Sales Invoice, Purchase Invoice, Journal Entry, Payment Entry, Asset Depreciation, Stock Reconciliation, or any other financial-impacting document—ultimately posts balanced debit and credit entries into the GL Entry table. ERPNext strictly follows double-entry bookkeeping principles, ensuring that total debits always equal total credits at a database level. This ensures financial integrity and consistency across all reports. Financial statements such as Trial Balance, Profit & Loss Statement, Balance Sheet, and Cash Flow Statement are dynamically computed using aggregated GL Entry data filtered by company, fiscal year, posting date range, cost center, project, and finance book. Hierarchical grouping of accounts is managed using the nested set model fields (lft and rgt) in the Account DocType, enabling efficient subtotal and roll-up calculations. Understanding this architecture is critical for consultants and developers because all customization, performance tuning, and validation processes revolve around the GL Entry structure and its relational dependencies.

Core Financial Tables

Table NamePurpose
GL EntryStores every accounting transaction (debit & credit)
AccountChart of Accounts hierarchy and classification
CompanyDefines base currency, fiscal year, and financial defaults
Fiscal YearDefines accounting period boundaries
Cost CenterTracks department-level accounting allocation

Basic GL Aggregation Query

SELECT 
    account,
    SUM(debit) AS total_debit,
    SUM(credit) AS total_credit
FROM `tabGL Entry`
WHERE posting_date BETWEEN '2025-01-01' AND '2025-12-31'
AND company = 'ABC Pvt Ltd'
GROUP BY account;

Financial Reporting Workflow

  1. Business transaction is created (Invoice, Payment, Journal Entry).
  2. ERPNext generates balanced GL Entries.
  3. Report engine fetches GL data based on filters.
  4. Accounts grouped hierarchically.
  5. Totals, subtotals, and balances computed.
  6. Financial statement rendered dynamically.

2. Configuring Chart of Accounts for Accurate Financial Reporting

The Chart of Accounts (CoA) is the structural backbone of financial reporting in ERPNext. It defines how transactions are categorized and how balances roll up into financial statements. ERPNext organizes accounts into a tree hierarchy using a nested set model where parent accounts aggregate balances from child ledger accounts. Each account is assigned a root type: Asset, Liability, Equity, Income, or Expense. These root types determine how balances are calculated and presented in financial reports. For example, Asset and Expense accounts typically increase with debits, whereas Liability, Equity, and Income accounts increase with credits. Incorrect classification of accounts can distort Profit & Loss or Balance Sheet outputs. Multi-company environments require separate CoA configurations unless a shared template is implemented. Developers must ensure that each ledger account is correctly mapped to a parent group and assigned the proper account type to ensure accurate financial computation.

Sample Account Structure

Account NameParent AccountRoot Type
Sales RevenueIncomeIncome
Direct ExpenseExpenseExpense
CashCurrent AssetsAsset

Creating an Account via Python

import frappe

account = frappe.get_doc({
    "doctype": "Account",
    "account_name": "Consulting Revenue",
    "parent_account": "Income - ABC",
    "company": "ABC Pvt Ltd",
    "root_type": "Income",
    "account_type": "Income Account"
})
account.insert()

Configuration Workflow

  1. Navigate to Accounting → Chart of Accounts.
  2. Create parent group accounts.
  3. Add ledger accounts under appropriate parents.
  4. Assign correct root type and account type.
  5. Validate hierarchy structure.

3. Generating Standard Financial Reports Using Built-In Engine

ERPNext provides built-in financial reports such as Trial Balance, Profit & Loss Statement, Balance Sheet, and Cash Flow Statement. These reports dynamically aggregate GL Entries using server-side Python logic combined with optimized SQL queries. Users can filter reports by Company, Fiscal Year, From Date, To Date, Cost Center, Project, Periodicity (Monthly/Quarterly/Yearly), and Finance Book. The system computes opening balances as cumulative GL totals prior to the report start date and calculates period activity within the selected range. Comparison columns allow previous year or budget comparison. Since these reports rely on dynamic computation rather than stored totals, real-time accuracy is maintained across large datasets.

Balance Calculation Query Concept

SELECT 
    account,
    SUM(debit - credit) AS balance
FROM `tabGL Entry`
WHERE company = 'ABC Pvt Ltd'
AND posting_date <= '2025-12-31'
GROUP BY account;

Report Execution Workflow

  1. User selects financial report.
  2. Applies filters (company, date range, etc.).
  3. Backend fetches GL Entries.
  4. Aggregates balances by account.
  5. Calculates opening, period, and closing balances.
  6. Displays structured financial statement.

4. Creating Custom Trial Balance Using Query Report

When standard financial reports do not satisfy specific business requirements, ERPNext allows developers to create Query Reports using custom SQL logic. Query Reports directly interact with the database but still respect user permission rules. Developers define filters in the report configuration and reference them in SQL using placeholders. Proper indexing and optimized grouping logic are essential when querying large GL datasets. Custom Trial Balance reports typically compute debit, credit, and closing balances grouped by account while preserving hierarchical ordering using lft values.

Custom Trial Balance SQL Example

SELECT 
    gle.account,
    acc.account_name,
    SUM(gle.debit) AS total_debit,
    SUM(gle.credit) AS total_credit,
    SUM(gle.debit - gle.credit) AS closing_balance
FROM `tabGL Entry` gle
JOIN `tabAccount` acc ON gle.account = acc.name
WHERE gle.company = %(company)s
AND gle.posting_date BETWEEN %(from_date)s AND %(to_date)s
GROUP BY gle.account
ORDER BY acc.lft;

Report Configuration Steps

  1. Navigate to Developer → Report.
  2. Create new report and select “Query Report”.
  3. Define filters (Company, From Date, To Date).
  4. Paste optimized SQL query.
  5. Save and test report output.

5. Building Advanced Financial Statements Using Script Reports

While Query Reports provide flexibility through SQL-based aggregation, enterprise-level financial reporting often requires dynamic column generation, conditional grouping logic, multi-period comparisons, currency normalization, and advanced computational logic that cannot be efficiently implemented in pure SQL. In such cases, Script Reports in ERPNext provide backend-level customization using Python within the Frappe Framework. Script Reports execute server-side logic, allowing developers to fetch GL Entries, restructure datasets, calculate derived metrics such as EBITDA, Gross Margin Percentage, departmental profitability, or rolling 12-month revenue analysis. Unlike static reports, Script Reports allow dynamic column building based on user filters, enabling monthly breakdowns, quarter-wise comparisons, and fiscal year overlays. This approach ensures maximum flexibility while maintaining permission validation and system security.

Script Report Structure Example

import frappe
from frappe.utils import flt

def execute(filters=None):
    columns = get_columns()
    data = get_data(filters)
    return columns, data

def get_columns():
    return [
        {"label": "Account", "fieldname": "account", "fieldtype": "Data", "width": 220},
        {"label": "Debit", "fieldname": "debit", "fieldtype": "Currency", "width": 150},
        {"label": "Credit", "fieldname": "credit", "fieldtype": "Currency", "width": 150},
        {"label": "Net Balance", "fieldname": "balance", "fieldtype": "Currency", "width": 150}
    ]

def get_data(filters):
    entries = frappe.db.sql("""
        SELECT account,
               SUM(debit) AS debit,
               SUM(credit) AS credit
        FROM `tabGL Entry`
        WHERE company = %(company)s
        AND posting_date BETWEEN %(from_date)s AND %(to_date)s
        GROUP BY account
    """, filters, as_dict=1)

    for row in entries:
        row["balance"] = flt(row["debit"]) - flt(row["credit"])
    return entries

When to Use Script Reports

RequirementUse Script Report?
Dynamic month-wise columnsYes
Consolidated multi-company reportingYes
Simple grouped GL summaryNo
Static SQL-based aggregationNo

Implementation Workflow

  1. Create new Report under Developer module.
  2. Select “Script Report” as report type.
  3. Attach to Accounting module.
  4. Create Python backend file.
  5. Define filters and columns.
  6. Test execution with large datasets.

6. Implementing Multi-Currency Financial Reporting

Organizations operating internationally require accurate multi-currency financial reporting. ERPNext handles multi-currency accounting by storing transaction values both in company base currency and account currency. The GL Entry table contains fields such as debit, credit (base currency) and debit_in_account_currency, credit_in_account_currency (foreign currency). Exchange rates are maintained in the Currency Exchange DocType and are applied automatically during transaction posting. When generating reports, ERPNext aggregates base currency by default but allows presentation currency conversion dynamically. Developers must ensure that exchange rate fluctuations are properly captured using Exchange Gain/Loss entries generated during payment reconciliation.

Relevant GL Fields

FieldDescription
debitDebit in company base currency
creditCredit in company base currency
debit_in_account_currencyDebit in foreign currency
account_currencyCurrency assigned to account

Multi-Currency Query Example

SELECT 
    account,
    SUM(debit_in_account_currency) AS foreign_debit,
    SUM(debit) AS base_debit
FROM `tabGL Entry`
WHERE company = %(company)s
AND posting_date BETWEEN %(from_date)s AND %(to_date)s
GROUP BY account;

Configuration Workflow

  1. Enable multi-currency in Accounts Settings.
  2. Create foreign currency accounts.
  3. Maintain exchange rates.
  4. Post foreign currency invoices.
  5. Verify exchange gain/loss entries.

Validation Checklist

CheckExpected Result
Total recognized foreign amountMatches invoice value
Exchange difference entryGenerated automatically
Report currency conversionAccurate

7. Creating Consolidated Multi-Company Financial Reports

In enterprise environments with multiple legal entities, consolidated reporting is essential for group-level financial visibility. ERPNext supports multi-company setups where each company maintains isolated GL Entries. Consolidation requires aggregating financial data across companies while eliminating inter-company transactions. Script Reports are typically used to fetch GL data from multiple companies, normalize currency values, and combine balances into a consolidated financial statement. Proper mapping of inter-company accounts ensures elimination entries prevent revenue duplication.

Multi-Company Data Aggregation Example

companies = filters.get("companies")

consolidated_data = []

for company in companies:
    entries = frappe.db.sql("""
        SELECT account,
               SUM(debit - credit) AS balance
        FROM `tabGL Entry`
        WHERE company = %s
        AND posting_date BETWEEN %s AND %s
        GROUP BY account
    """, (company, filters.from_date, filters.to_date), as_dict=1)
    
    consolidated_data.extend(entries)

Consolidation Workflow

  1. Ensure uniform Chart of Accounts structure.
  2. Map inter-company accounts.
  3. Fetch GL data from each company.
  4. Normalize currency values.
  5. Eliminate internal balances.
  6. Aggregate consolidated totals.

Risk Areas

RiskImpact
Currency mismatchIncorrect totals
Inter-company duplicationInflated revenue
Inconsistent CoA structureMisaligned balances

8. Budget vs Actual Financial Analysis Implementation

Budget control enables organizations to compare planned financial allocations against actual GL activity. ERPNext allows budget creation at account and cost center levels. Budget amounts can be distributed monthly or annually. During reporting, actual GL balances are compared against allocated budgets to calculate variance and percentage deviation. Script Reports can enhance budget analysis by calculating rolling forecasts or dynamic department-wise comparisons.

Budget Variance SQL Example

SELECT 
    gle.account,
    SUM(gle.debit - gle.credit) AS actual_amount,
    bud.budget_amount,
    (SUM(gle.debit - gle.credit) - bud.budget_amount) AS variance
FROM `tabGL Entry` gle
LEFT JOIN `tabBudget Account` bud 
ON gle.account = bud.account
WHERE gle.company = %(company)s
AND gle.posting_date BETWEEN %(from_date)s AND %(to_date)s
GROUP BY gle.account;

Budget Configuration Steps

  1. Create Budget document.
  2. Select fiscal year.
  3. Assign accounts and cost centers.
  4. Distribute budget monthly.
  5. Enable budget control.

Variance Analysis Table

AccountBudgetActualVariance
Marketing Expense100,000120,00020,000 Over
Sales Revenue500,000480,00020,000 Under

9. Cash Flow Statement Technical Logic & Implementation

The Cash Flow Statement differs fundamentally from Profit & Loss and Balance Sheet because it focuses exclusively on liquidity movement rather than accrual-based accounting performance. ERPNext constructs the Cash Flow Statement by isolating GL Entries associated with accounts categorized as “Cash” or “Bank” under Account Type configuration. These liquidity accounts capture real inflows and outflows of funds. The report classifies transactions into Operating Activities (day-to-day business operations), Investing Activities (asset purchases or sales), and Financing Activities (loans, equity capital). In indirect method reporting, ERPNext begins with Net Profit and adjusts non-cash expenses such as depreciation and changes in working capital (receivables, payables, inventory). Developers customizing the cash flow report must ensure that non-cash accounts are excluded from liquidity computation and that opening balance reconciliation aligns with bank ledger records.

Liquidity Aggregation Query

SELECT 
    account,
    SUM(debit) AS total_inflow,
    SUM(credit) AS total_outflow,
    SUM(debit - credit) AS net_cash_movement
FROM `tabGL Entry`
WHERE company = %(company)s
AND posting_date BETWEEN %(from_date)s AND %(to_date)s
AND account IN (
    SELECT name FROM `tabAccount`
    WHERE account_type IN ('Cash', 'Bank')
)
GROUP BY account;

Activity Classification Table

Activity TypeExamples
OperatingCustomer payments, supplier payments
InvestingPurchase of machinery, sale of assets
FinancingBank loans, equity investment

Cash Flow Workflow

  1. Identify liquidity accounts (Cash & Bank).
  2. Calculate opening balance before reporting period.
  3. Aggregate period inflows and outflows.
  4. Classify transactions by activity type.
  5. Compute net increase/decrease in cash.
  6. Validate closing balance against bank ledger.

Validation Rule

Opening Balance + Net Movement = Closing Balance

10. Financial Year Closing & Opening Balance Mechanics

Financial year closing in ERPNext ensures that all Income and Expense accounts are reset while transferring the net profit or loss into a Retained Earnings (Equity) account. This process is executed through the Period Closing Voucher, which generates offsetting GL Entries without altering historical transactions. ERPNext dynamically computes opening balances for the next fiscal year as cumulative totals of GL Entries up to the fiscal year start date. Therefore, no manual opening balance entry is required when prior year data exists. Developers must ensure all transactions are posted and verified before closing, as backdated entries after closure can distort financial accuracy.

Net Profit Computation Query

SELECT 
    SUM(debit - credit) AS net_result
FROM `tabGL Entry`
WHERE company = %(company)s
AND posting_date BETWEEN '2025-01-01' AND '2025-12-31'
AND account IN (
    SELECT name FROM `tabAccount`
    WHERE root_type IN ('Income','Expense')
);

Year-End Closing Workflow

  1. Ensure all transactions are submitted.
  2. Run Trial Balance to verify totals.
  3. Confirm total debit equals total credit.
  4. Create Period Closing Voucher.
  5. Select Retained Earnings account.
  6. Submit voucher and lock fiscal year.

Risk Management Table

RiskImpact
Backdated journal entriesIncorrect opening balances
Unposted invoicesUnderstated revenue/expense
Wrong equity mappingDistorted retained earnings

11. Deferred Revenue & Accrual Accounting Configuration

ERPNext supports accrual-based accounting by enabling Deferred Revenue and Deferred Expense functionality. When deferred revenue is enabled for an item, ERPNext distributes income recognition over the service period rather than recognizing the entire amount immediately. The system schedules periodic GL Entries via background jobs to transfer amounts from Deferred Income account to actual Income account. This ensures compliance with accounting standards such as IFRS and GAAP. The scheduler automatically processes recognition entries based on configured frequency.

Recognition Logic Example (Python Concept)

def recognize_deferred_income(total_amount, months):
    monthly_amount = total_amount / months
    for month in range(months):
        create_gl_entry(
            debit_account="Deferred Income",
            credit_account="Service Revenue",
            amount=monthly_amount
        )

Deferred Revenue Configuration Table

FieldPurpose
Enable Deferred RevenueActivates scheduling logic
Service Start DateRecognition period start
Service End DateRecognition period end
Deferred AccountTemporary holding account

Implementation Workflow

  1. Create Item with deferred revenue enabled.
  2. Generate Sales Invoice.
  3. Submit invoice.
  4. System schedules recognition entries.
  5. Verify periodic GL postings.
  6. Confirm total recognized equals invoice value.

12. Financial Report Performance Optimization & Index Strategy

In enterprise environments, the GL Entry table may contain millions of records. Poorly optimized queries can result in significant performance degradation during financial reporting. ERPNext relies heavily on indexed fields such as company, posting_date, and account. Custom financial reports must always include date filters and company filters to prevent full table scans. Composite indexing improves grouped aggregation speed. Developers should test queries using EXPLAIN statements and monitor database load during report execution.

Recommended Composite Index

CREATE INDEX idx_company_posting_account
ON `tabGL Entry` (company, posting_date, account);

Performance Testing Steps

  1. Run EXPLAIN on query.
  2. Verify index usage.
  3. Measure execution time.
  4. Optimize joins and conditions.
  5. Retest with large dataset.

Optimization Checklist

StrategyBenefit
Date FilteringReduces scanned rows
Company FilteringData isolation
Composite IndexingFaster grouped queries
Minimal JoinsReduced query overhead

13. Auto Email Reports & Scheduled Financial Automation

In enterprise environments, financial reporting is not limited to on-demand generation; it must be automated and distributed consistently to stakeholders such as CFOs, auditors, department heads, and board members. ERPNext provides an Auto Email Report feature that allows scheduled delivery of financial statements such as Profit & Loss, Balance Sheet, Trial Balance, Cash Flow, and even custom Script Reports. This functionality operates through the background scheduler of the Frappe Framework, which periodically triggers report execution based on defined frequency (Daily, Weekly, Monthly, Quarterly, or Custom Cron). Filters are stored in JSON format and applied dynamically at runtime. The system renders reports into PDF or Excel formats and sends them through configured SMTP email accounts. Proper permission validation ensures that recipients only receive data they are authorized to access. Automation eliminates manual effort, reduces reporting delays, and improves consistency in financial communication.

Sample Filter JSON Configuration

{
    "company": "ABC Pvt Ltd",
    "from_date": "2025-01-01",
    "to_date": "2025-12-31",
    "periodicity": "Monthly"
}

Automation Workflow

  1. Configure Email Account (SMTP settings).
  2. Navigate to Auto Email Report module.
  3. Select financial report to automate.
  4. Define frequency and filter parameters.
  5. Add recipient email addresses.
  6. Enable scheduled delivery.

Validation Checklist

ValidationExpected Result
Scheduled triggerRuns at configured time
Report accuracyMatches manual execution
Email deliveryDelivered successfully
Permission complianceNo unauthorized exposure

14. Financial Dashboard & KPI Visualization Architecture

Financial dashboards transform structured accounting data into real-time visual insights for executive decision-making. ERPNext enables creation of dashboards that integrate charts, number cards, and summary widgets linked to financial reports or custom Script Reports. Key Performance Indicators (KPIs) such as Revenue Growth, Net Profit Margin, Gross Margin Percentage, Expense Ratio, Cash Position, and Working Capital can be calculated dynamically using aggregated GL Entry data. Dashboards allow drill-down functionality, enabling users to navigate from summary metrics into detailed transaction-level reports. By leveraging report sources and server-side calculations, dashboards ensure accurate and real-time financial monitoring across departments and management levels.

KPI Calculation SQL Example

SELECT 
    (SUM(CASE WHEN acc.root_type = 'Income' THEN gle.credit ELSE 0 END) -
     SUM(CASE WHEN acc.root_type = 'Expense' THEN gle.debit ELSE 0 END)
    ) AS net_profit
FROM `tabGL Entry` gle
JOIN `tabAccount` acc ON gle.account = acc.name
WHERE gle.company = %(company)s
AND gle.posting_date BETWEEN %(from_date)s AND %(to_date)s;

Common Financial KPIs

KPIFormula
Net Profit MarginNet Profit / Revenue
Expense RatioTotal Expenses / Revenue
Revenue Growth(Current - Previous) / Previous
Cash RatioCash / Current Liabilities

Dashboard Setup Workflow

  1. Create new Dashboard document.
  2. Add chart or number card.
  3. Link to financial report source.
  4. Configure filters and display options.
  5. Publish dashboard to specific roles.

15. Audit Trail & Financial Data Integrity Controls

Financial accuracy depends not only on correct reporting logic but also on strict audit control mechanisms. ERPNext maintains detailed audit trails through Version records that capture modifications to financial documents such as Journal Entries, Sales Invoices, and Purchase Invoices. Once documents are submitted, corresponding GL Entries become immutable unless explicitly canceled with reversal entries. The system supports period freeze functionality, which restricts backdated transactions beyond a configured date. This prevents unauthorized adjustments to closed fiscal periods. Audit Trail features allow filtering by document type, user, or date to track changes and ensure regulatory compliance. Proper implementation of these controls enhances financial transparency and strengthens internal governance.

Version Log Query Example

SELECT 
    ref_doctype,
    docname,
    modified_by,
    modified
FROM `tabVersion`
WHERE ref_doctype IN ('Journal Entry', 'Sales Invoice')
ORDER BY modified DESC;

Audit Control Workflow

  1. Submit financial document.
  2. Modify document (if permitted).
  3. Check Version log for changes.
  4. Enable accounting period freeze.
  5. Test restriction on backdated entries.

Data Integrity Safeguards

ControlPurpose
Document Submission LockPrevents unauthorized edits
Period FreezeProtects closed fiscal periods
Version TrackingMaintains change history
Role RestrictionLimits financial authority

16. Role-Based Access & Financial Security Architecture

Financial data security is critical in ERP systems. ERPNext enforces role-based access control (RBAC) at DocType, field, report, and row levels. Roles such as Accounts User, Accounts Manager, Auditor, and CFO define varying levels of financial authority. User Permissions can restrict data visibility by Company, Cost Center, or Project, ensuring multi-company isolation. Query Reports and Script Reports respect permission checks automatically unless explicitly overridden. Developers must implement additional permission validation in custom reports to prevent unauthorized exposure of GL data. Secure configuration ensures that sensitive financial information remains protected while still enabling operational efficiency.

Permission Enforcement Example

if not frappe.has_permission("GL Entry", "read"):
    frappe.throw("You do not have permission to access financial records.")

Role Configuration Table

RoleAccess Level
Accounts UserCreate financial entries
Accounts ManagerSubmit & cancel entries
AuditorRead-only financial access
CFOFull financial control

Security Workflow

  1. Create financial roles.
  2. Assign roles to users.
  3. Configure Role Permission Manager.
  4. Restrict report visibility.
  5. Test access scenarios across companies.

Conclusion: Enterprise Financial Reporting Mastery in ERPNext

Financial reporting in ERPNext is built upon a robust, GL-driven architecture that ensures real-time accuracy, scalability, compliance, and enterprise-grade flexibility. From foundational Chart of Accounts configuration to advanced Script Reports, multi-currency normalization, consolidated group reporting, budget variance analysis, automated scheduling, dashboard visualization, audit controls, and role-based security enforcement, every component plays a crucial role in delivering reliable financial intelligence. The system’s dynamic aggregation model eliminates dependency on static stored totals, ensuring that financial statements always reflect live transactional data. Performance optimization through indexing strategies supports large-scale enterprise deployments, while audit trail and access control mechanisms safeguard data integrity and regulatory compliance. When properly configured and governed, ERPNext transforms from a standard accounting tool into a comprehensive financial intelligence platform capable of supporting strategic decision-making, cross-company consolidation, and long-term enterprise growth.


No comments yet.

Add a comment
Ctrl+Enter to add comment

NEXEVES Footer