IO Engine
IO Middleware
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
- Contributions to this module:
Miguel Sanda <msanda@arrobalytics.com>
IO Context
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
- Contributions to this module:
Miguel Sanda <msanda@arrobalytics.com>
- exception django_ledger.io.io_context.IODigestValidationError(message, code=None, params=None)
IO Library
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
- Contributions to this module:
Miguel Sanda <msanda@arrobalytics.com>
This module contains classes and functions used to document, dispatch and commit new transaction into the database.
- class django_ledger.io.io_library.IOBluePrint(name: str | None = None, precision_decimals: int = 2)
This class documents instructions required to assemble and dispatch transactions into the ledger.
- Parameters:
name (str, optional) – The human-readable name of the IOBluePrint instance.
precision_decimals (int) – The number of decimals to use when balancing transactions. Defaults to 2.
- commit(entity_model: EntityModel, user_model, ledger_model: str | LedgerModel | UUID | None = None, je_timestamp: str | datetime | date | None = None, post_new_ledgers: bool = False, post_journal_entries: bool = False, **kwargs) Dict
Commits the blueprint transactions to the database.
- Parameters:
entity_model (EntityModel) – The entity model instance where transactions will be committed.
user_model (UserModel) – The user model instance executing transactions to check for permissions.
ledger_model (Optional[Union[str, LedgerModel, UUID]]) – The ledger model instance identifier to be used for the transactions. If none, a new ledger will be created.
je_timestamp (date or datetime or str, optional) – The date and/or time to be used for the transactions. If none, localtime will be used.
post_new_ledgers (bool) – If True, newly created ledgers will be posted. Defaults to False.
post_journal_entries (bool) – If True, newly created journal entries will be posted. Defaults to False.
kwargs – Keyword arguments passed to the IO Library.
- Returns:
A dictionary containing the resulting models of the transactions.
- Return type:
Dict
- credit(account_code: str, amount: float | Decimal, description: str = None)
Registers a CREDIT to the specified account..
- Parameters:
account_code (str) – The account code to use for the transaction.
amount (float or Decimal) – The amount of the transaction.
description (str) – Description of the transaction.
- debit(account_code: str, amount: float | Decimal, description: str = None)
Registers a DEBIT to the specified account.
- Parameters:
account_code (str) – The account code to use for the transaction.
amount (float or Decimal) – The amount of the transaction.
description (str) – Description of the transaction.
- get_name(entity_model: EntityModel) str
Determines the name of the blueprint if none provided.
- Parameters:
entity_model (EntityModel) – The EntityModel instance where the resulting blueprint transactions will be stored.
- Returns:
The name of the blueprint.
- Return type:
str
- exception django_ledger.io.io_library.IOBluePrintValidationError(message, code=None, params=None)
- class django_ledger.io.io_library.IOCursor(io_library, entity_model: EntityModel, user_model, mode: IOCursorMode = IOCursorMode.PERMISSIVE, coa_model: ChartOfAccountModel | UUID | str | None = None)
Represents a Django Ledger cursor capable of dispatching transactions to the database. The Cursor class is responsible for coordinating the creation of new ledgers, journal entries and transactions It is a low level interface to the IOBlueprint and IOLibrary classes.
- Parameters:
io_library (IOLibrary) – The IOLibrary class that contains all the necessary instructions to dispatch the transactions.
entity_model (EntityModel) – The EntityModel instance that will be used for the new transactions.
user_model (UserModel) – The UserModel instance that will be used for the new transactions. Used for read permissions of QuerySets.
coa_model (ChartOfAccountModel or UUID or str.) – The ChartOfAccountModel instance that contains the accounts to be used for transactions. Instance, UUID or slug can be sued to retrieve the model.
- commit(je_timestamp: str | datetime | date | None = None, je_description: str | None = None, post_new_ledgers: bool = False, post_journal_entries: bool = False, **kwargs)
Commits the compiled blueprint transactions into the database. This action is irreversible and if journal entries are posted, the books will be immediately impacted by the new transactions. It is encouraged NOT to post anything until the transaction is reviews for accuracy.
- Parameters:
je_timestamp (Optional[Union[datetime, date, str]]) – The date or timestamp used for the committed journal entries. If none, localtime will be used.
je_description (Optional[str]) – The description of the journal entries. If none, no description will be used.
post_new_ledgers (bool) – If a new ledger is created, the ledger model will be posted to the database.
post_journal_entries (bool) – If new journal entries are created, the journal entry models will be posted to the database.
kwargs – Additional keyword arguments passed to the IO commit_txs function.
- compile_instructions() Dict
Compiles the blueprint instructions into Journal Entries and Transactions to be committed to the ledger.
- Returns:
A dictionary containing the compiled instructions.
- Return type:
Dict
- dispatch(name, ledger_model: str | LedgerModel | UUID | None = None, **kwargs)
Stages the instructions to be processed by the IOCursor class. This method does not commit the transactions into the database.
- Parameters:
name (str) – The registered blueprint name to be staged.
ledger_model (Optional[Union[str, LedgerModel, UUID]]) – Optional ledger model identifier to house the transactions associated with the blueprint. If none is provided, a new ledger model will be created.
kwargs – The keyword arguments to be passed to the blueprint function.
- get_account_model_qs() AccountModelQuerySet
Determines the AccountModelQuerySet associated with the Chart of Accounts specified.
- Return type:
- get_ledger_model_qs() LedgerModelQuerySet
Determines the ledger model queryset associated with the entity model and user model provided.
- Return type:
- is_committed() bool
Determines if the IOCursor instance has committed the transactions into the database. A cursor can only commit transactions once.
- Returns:
True if committed, False otherwise.
- Return type:
bool
- resolve_account_model_qs(codes: Set[str]) AccountModelQuerySet
Resolves the final AccountModelQuerySet associated with the given account codes used by the blueprint.
- Parameters:
codes (List[str]) – List of codes used during the execution of the blueprint.
- Returns:
The resolved AccountModelQuerySet associated with the given codes.
- Return type:
- resolve_ledger_model_qs() LedgerModelQuerySet
Resolves the final LedgerModelQuerySet associated with the provided ledger model identifiers used by the blueprints.
- Returns:
The resolved LedgerModelQuerySet associated with the given ledger model identifiers.
- Return type:
- class django_ledger.io.io_library.IOCursorMode(*values)
- exception django_ledger.io.io_library.IOCursorValidationError(message, code=None, params=None)
- class django_ledger.io.io_library.IOLibrary(name: str)
The IO Library is a centralized interface for documenting commonly used operations. The library will register and document the blueprints and their instructions so that they can be dispatched from anywhere in the application.
- Parameters:
name (str) – The human-readable name of the library (i.e. PayRoll, Expenses, Rentals, etc…)
- get_blueprint(name: str) Callable
Retrieves a blueprint by name.
- Parameters:
name (str) – The name of the blueprint to retrieve.
- Return type:
Callable
- get_cursor(entity_model: EntityModel, user_model, mode: IOCursorMode = IOCursorMode.PERMISSIVE, coa_model: ChartOfAccountModel | UUID | str | None = None) IOCursor
Creates a cursor instance for associated with the library, entity and user model.
- Parameters:
entity_model (EntityModel) – The entity model instance where transactions will be committed.
user_model (UserModel) – The user model instance executing the transactions.
coa_model (ChartOfAccountModel or UUID or str, optional) – The ChartOfAccountsModel instance or identifier used to determine the AccountModelQuerySet used for the transactions.
mode (IOCursorMode) – The Mode of the cursor instance. Defaults to IOCursorMode.PERMISSIVE.
- Return type:
- exception django_ledger.io.io_library.IOLibraryError(message, code=None, params=None)
- class django_ledger.io.io_library.TransactionInstructionItem(account_code: str, amount: Decimal | float, tx_type: str, description: str | None, account_model: AccountModel | None = None)
A class to represent a transaction instruction used during the development of transaction blueprints.
- account_code
The account code of the AccountModel as a String.
- Type:
str
- amount
The transaction amount as a Decimal value. Will be rounded to the nearest decimal place.
- Type:
Decimal
- tx_type
A choice of ‘debit’ or ‘credit’ transaction.
- Type:
str
- description
Description of the transaction.
- Type:
str
- account_model
The resolved account model for the transaction. Not to be modified. Defaults to None.
- Type:
IO Core
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
This module serves as a core component of the Django Ledger framework, providing an optimized interface and utilities for handling financial transactions, journal entries, and generating financial statements. It is designed to allow efficient interaction with the database, minimizing Python’s memory usage by emphasizing database-level aggregations while enforcing proper accounting principles.
Key Features:
Transaction and Journal Management: - Provides capabilities for creating, validating, and balancing transactions at the database level. - Supports integration of Closing Entries as optimizations for financial data aggregation.
Validation Utilities: - Validates transaction balances, timestamps, and input data for minimal errors. - Ensures consistency with Django Ledger configurations, such as handling timezone-awareness and closing dates.
Database Interaction: - Aggregation and querying of financial data at the database layer to improve memory efficiency. - Implements advanced filtering options for transactions based on attributes like activity, account roles, business units, and time periods. - Leverages Closing Entries as “checkpoints” to minimize aggregation workload on large datasets.
- Financial Statement Reports:
Offers functionalities to generate financial statements, including:
Balance Sheet
Income Statement
Cash Flow Statement
Supports PDF generation for these reports (if PDF support is enabled).
Extensibility: - Implements a layered architecture with reusable mixins (IODatabaseMixIn, IOReportMixIn, IOMixIn) that allow developers to customize behavior for specific use cases or extend functionality when needed.
Middleware and Ratios: - Includes middleware support for handling roles, financial groups, and ratios as additional processing layers for generated reports.
Classes:
IOResult: A data carrier class for managing aggregated transaction and account balance data during digest operations.
IODatabaseMixIn: Handles database interactions for aggregating transaction data efficiently and applying accounting rules.
IOReportMixIn: Offers methods for generating financial reports, including support for PDF output (if enabled).
IOMixIn: Combines database operations and reporting features into a single reusable mixin for comprehensive I/O management.
Functions:
- Utility Functions:
diff_tx_data(): Validates whether the credits and debits for a given transaction dataset are balanced.
check_tx_balance(): Ensures transaction datasets are corrected to be balanced if requested.
validate_io_timestamp(): Ensures that input dates or timestamps are valid and timezone-aware.
get_localtime(), get_localdate(): Retrieve local time or local date based on Django’s timezone settings.
validate_dates(): Validates and parses from_date and to_date inputs.
- Digest Operations:
database_digest(): Processes and aggregates transactions directly in the database with support for filters such as activity, role, and period.
python_digest(): Applies additional processing and group-by operations on transaction data after database-level aggregation.
digest(): A unified entry point for performing database digests and Python-level post-processing, with options to process roles, groups, ratios, and financial statements.
- Report Data Generation:
get_balance_sheet_statement(), get_income_statement(), get_cash_flow_statement(): Generate specific financial statements, with optional PDF output.
get_financial_statements(): Generate all key financial statements together (Balance Sheet, Income Statement, Cash Flow Statement).
Error Handling:
Custom Exceptions: - IOValidationError: Raised for input validation errors during transaction or journal entry processing.
Supported Features:
Database-level transaction aggregation for performance optimization.
Timezone-aware operations for timestamp handling.
Modular architecture leveraging mixins for different components.
Middleware for advanced role processing and financial grouping.
Optional PDF generation using settings from Django Ledger.
Notes:
Ensure DJANGO_LEDGER_PDF_SUPPORT_ENABLED is properly configured to enable PDF output in financial reports.
Closing Entries play a critical role in improving aggregation times for entities with significant transactions.
The module is designed to work seamlessly with Django’s ORM and custom models through utilities provided in the Django Ledger framework.
- class django_ledger.io.io_core.IODatabaseMixIn
Mix-in class for database interactions and aggregation for IO models.
This class is designed to encapsulate several common behaviors for models related to database queries and aggregations in the context of IO operations such as transactions, ledger models, and entity models. It facilitates the derivation of specific models, validation of query parameters, and execution of data aggregation queries with flexible filtering and grouping options.
- TRANSACTION_MODEL_CLASS
Specifies the Django model class for transactions. If None, a lazy loader will be used to determine the model dynamically.
- Type:
NoneType or Type
- JOURNAL_ENTRY_MODEL_CLASS
Specifies the Django model class for journal entries. If None, a lazy loader will be used to determine the model dynamically.
- Type:
NoneType or Type
- static aggregate_balances(k, g)
Aggregates balances from grouped data, providing a summarized representation of account attributes and their balances over a specified period. The function is used to compile essential details such as account identifiers, roles, activity, and balance, summarizing them for further processing or presentation.
- Parameters:
k (tuple) – A tuple consisting of grouped key values. Expected structure: - The first element represents the account UUID. - The second element represents the unit UUID. - The third and fourth elements represent the period year and month, respectively. - The sixth element represents the transaction type.
g (iterable) – An iterable of grouped account data, typically containing dictionaries with detailed account properties and their respective balance information.
- Returns:
A dictionary containing the aggregated balance information and related attributes, structured with the following keys: - ‘account_uuid’ - ‘coa_slug’ - ‘unit_uuid’ - ‘unit_name’ - ‘activity’ - ‘period_year’ - ‘period_month’ - ‘role_bs’ - ‘role’ - ‘code’ - ‘name’ - ‘balance_type’ - ‘tx_type’ - ‘balance’
- Return type:
dict
- commit_txs(je_timestamp: str | datetime | date, je_txs: List[Dict], je_posted: bool = False, je_ledger_model=None, je_unit_model=None, je_desc=None, je_origin=None, force_je_retrieval: bool = False, **kwargs)
Commits a set of financial transactions to a journal entry, after performing validation checks. Validations include ensuring balanced transactions, ensuring timestamp integrity, and verifying relationships between models. This method creates or retrieves a journal entry based on the provided details and assigns the given transactions accordingly, supporting conditional posting.
- Parameters:
je_timestamp (str or datetime or date) – The timestamp for the journal entry. Validates against entity’s closed periods and is required to be in a valid format.
je_txs (list of dict) – A list of transactions to be committed, each represented as a dictionary. Each transaction should include keys such as ‘account’, ‘amount’, ‘tx_type’, and ‘description’.
je_posted (bool, optional) – Whether the created or retrieved journal entry should be marked as posted after verification. Defaults to False.
je_ledger_model (object, optional) – An optional instance of LedgerModel used for validating ledger associations. If not provided, defaults to the current ledger model.
je_unit_model (object, optional) – An optional instance of EntityUnitModel used for validating entity unit associations with transactions.
je_desc (str, optional) – A description for the journal entry. Defaults to None if not provided.
je_origin (str, optional) – Specifies the origin or source of the journal entry. Defaults to None.
force_je_retrieval (bool, optional) – Whether to force retrieval of an existing journal entry with the given timestamp instead of creating a new one. Defaults to False.
**kwargs (dict) – Additional keyword arguments that may be required for handling specific customization details during journal entry creation or retrieval.
- Returns:
A tuple containing the journal entry model (je_model) and a list of transaction models (txs_models) created or associated with the journal entry.
- Return type:
tuple
- Raises:
IOValidationError – Raised for various validation errors including invalid timestamps, attempting to commit on locked or closed ledgers, association errors with ledger or entity models, and inability to retrieve a required journal entry.
- database_digest(entity_slug: str | None = None, unit_slug: str | None = None, user_model: User | None = None, from_date: datetime | date | None = None, to_date: datetime | date | None = None, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, by_unit: bool = False, activity: str | None = None, role: str = typing.Optional[str], accounts: str | List[str] | Set[str] | None = None, posted: bool = True, exclude_zero_bal: bool = True, use_closing_entries: bool = False, **kwargs) IOResult
Aggregates transaction data based on the provided parameters to generate a digest of financial entries. This method is designed to work with various models (EntityModel, EntityUnitModel, LedgerModel) and processes transactions, including handling closing entries to optimize database queries. The resulting data can be customized based on specific filters or aggregation criteria, such as activity, transaction type, or time periods.
- Parameters:
entity_slug (Optional[str]) – The identifier for the entity. Used to filter transactions for a specific entity in cases where the model operates at the entity level.
unit_slug (Optional[str]) – The identifier for the unit. Valid when filtering transactions for a specific unit within an entity.
user_model (Optional[UserModel]) – The user model instance. Represents the user context in which the transaction filtering applies.
from_date (Optional[Union[date, datetime]]) – The starting date for filtering transactions. Aggregates data from the given date if specified.
to_date (Optional[Union[date, datetime]]) – The ending date for filtering transactions. Aggregates data up to this date if specified.
by_activity (bool) – Determines whether results should be aggregated by activity. Defaults to False.
by_tx_type (bool) – Indicates if results should be grouped by transaction type. Defaults to False.
by_period (bool) – Determines if results should be grouped by time period (e.g., months). Defaults to False.
by_unit (bool) – Indicates whether transactions should be grouped by entity unit. Defaults to False.
activity (Optional[str]) – A specific activity identifier to filter results. If provided, only transactions related to this activity will be included.
role (Optional[str]) – A specific role to filter transactions by. Transactions matching this role will be included in the aggregation.
accounts (Optional[Union[str, List[str], Set[str]]]) – Specifies accounts to filter by. Can be a single account or a list/set of accounts. Filters transactions associated with the provided accounts.
posted (bool) – Indicates whether to filter transactions that are posted (committed). Defaults to True.
exclude_zero_bal (bool) – If True, transactions with zero-balance amounts will be excluded. Defaults to True.
use_closing_entries (bool) – Specifies whether closing entries should be used to optimize database aggregation. If not provided, the value is determined by the system-global setting.
kwargs (dict) – Additional parameters that can be passed for extended flexibility or customization when filtering and processing transactions.
- Returns:
An object containing the aggregated results, filtered transaction querysets, and metadata such as database query bounds or details about closing entry matches.
- Return type:
- digest(entity_slug: str | None = None, unit_slug: str | None = None, to_date: str | datetime | date | None = None, from_date: str | datetime | date | None = None, user_model: User | None = None, accounts: Set[str] | List[str] | None = None, role: Set[str] | List[str] | None = None, activity: str | None = None, signs: bool = True, process_roles: bool = False, process_groups: bool = False, process_ratios: bool = False, process_activity: bool = False, equity_only: bool = False, by_period: bool = False, by_unit: bool = False, by_activity: bool = False, by_tx_type: bool = False, balance_sheet_statement: bool = False, income_statement: bool = False, cash_flow_statement: bool = False, use_closing_entry: bool | None = None, **kwargs) IODigestContextManager
Processes financial data and generates various financial statements, ratios, or activity digests based on the provided arguments. The method applies specific processing pipelines, such as role processing, grouping, ratio computation, activity-based operations, or generating financial statements like balance sheet, income statement, and cash flow statement.
- Parameters:
entity_slug (Optional[str]) – The slug identifier for the entity to process the financial data for.
unit_slug (Optional[str]) – The slug identifier for the specific unit of the entity to filter the data for.
to_date (Optional[Union[date, datetime, str]]) – The upper limit of the date range for which the data will be processed. Can be a date, datetime, or ISO 8601 formatted str.
from_date (Optional[Union[date, datetime, str]]) – The lower limit of the date range for which the data will be processed. Can be a date, datetime, or ISO 8601 formatted str.
user_model (Optional[UserModel]) – A user model instance to filter data or apply user-specific permissions during processing.
accounts (Optional[Union[Set[str], List[str]]]) – A collection of account identifiers to filter the financial data to process.
role (Optional[Union[Set[str], List[str]]]) – A collection of roles used to filter or organize the data during processing.
activity (Optional[str]) – Specific activity identifier to filter or process the data for.
signs (bool, default=True) – If True, account roles with predefined signs will be applied to the financial data.
process_roles (bool, default=False) – If True, processes account roles and organizes financial data accordingly.
process_groups (bool, default=False) – If True, processes and organizes the financial data into predetermined account groups.
process_ratios (bool, default=False) – If True, computes and processes financial ratios for the provided data.
process_activity (bool, default=False) – If True, specific activity-based computation or segregation will be executed.
equity_only (bool, default=False) – Processes only equity-specific accounts if set to True.
by_period (bool, default=False) – Organizes or groups the output by accounting periods if True.
by_unit (bool, default=False) – Organizes or processes data specific to each unit when set to True.
by_activity (bool, default=False) – Groups or segregates the processed data by activity when True.
by_tx_type (bool, default=False) – Groups or organizes the result by transaction type when True.
balance_sheet_statement (bool, default=False) – If True, prepares a balance sheet statement as part of the processing.
income_statement (bool, default=False) – If True, generates an income statement as part of the processed result.
cash_flow_statement (bool, default=False) – If True, prepares a cash flow statement based on the provided data.
use_closing_entry (Optional[bool]) – Specifies whether to account for closing entries in the financial statement computation.
**kwargs – Additional named arguments that can be passed to adjust the behavior of specific processing modules or middleware.
- Returns:
A context manager instance containing the processed financial data and results, including financial statements, ratios, or any activity digest generated as per the input parameters.
- Return type:
IODigestContextManager
- get_entity_model_from_io()
Retrieves the entity model associated with the current instance.
This method determines the type of the current model instance and retrieves the corresponding entity model if applicable. If the instance itself is an EntityModel, it returns itself. If the instance is a ledgerModel or EntityUnitModel model, the associated entity model is retrieved from its attributes.
- Returns:
entity – Retrieves the associated entity model if the instance is a ledger or entity unit model.
- Return type:
- get_journal_entry_model()
Retrieves the class model for journal entries. If the JOURNAL_ENTRY_MODEL_CLASS attribute is set, it returns its value. Otherwise, it dynamically loads and returns the journal entry model using the lazy_loader.
- Returns:
The journal entry model class, either explicitly defined in JOURNAL_ENTRY_MODEL_CLASS or loaded dynamically.
- Return type:
Type
- get_transaction_model()
Retrieve the transaction model class used for handling transactions.
The method checks whether a specific transaction model class is explicitly set via the TRANSACTION_MODEL_CLASS attribute. If set, it returns that class as the transaction model. If not set, it falls back to a default transaction model obtained from the lazy_loader.get_txs_model() method.
- Returns:
The transaction model class defined in TRANSACTION_MODEL_CLASS or the default transaction model provided by lazy_loader.get_txs_model().
- Return type:
type
- is_entity_model()
Check if the instance is an EntityModel.
- Returns:
True if the instance is an entity model, False otherwise.
- Return type:
bool
- is_entity_unit_model()
Checks if the current instance is an EntityUnitModel.
- Returns:
True if the object is an instance of the entity unit model; False otherwise.
- Return type:
bool
- is_ledger_model()
Checks if the current instance is a LedgerModel.
- Returns:
True if the instance is of type ledger model, False otherwise.
- Return type:
bool
- python_digest(user_model: User | None = None, entity_slug: str | None = None, unit_slug: str | None = None, to_date: str | datetime | date | None = None, from_date: str | datetime | date | None = None, equity_only: bool = False, activity: str = None, role: Set[str] | List[str] | None = None, accounts: Set[str] | List[str] | None = None, signs: bool = True, by_unit: bool = False, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, use_closing_entries: bool = False, force_queryset_sorting: bool = False, **kwargs) IOResult
Computes and returns the digest of transactions for a given entity, unit, and optional filters such as date range, account role, and activity. The digest includes aggregated balances by specified group-by keys.
- Parameters:
user_model (Optional[UserModel]) – The user model to be used for the computation. Defaults to None.
entity_slug (Optional[str]) – The slug representing the entity to compute the digest for. Defaults to None.
unit_slug (Optional[str]) – The slug representing the unit within the entity. Defaults to None.
to_date (Optional[Union[date, datetime, str]]) – The end date for the transaction filter. Defaults to None.
from_date (Optional[Union[date, datetime, str]]) – The start date for the transaction filter. Defaults to None.
equity_only (bool) – Whether to compute results only for earnings-related accounts. Defaults to False.
activity (str) – An optional activity filter for transactions. Defaults to None.
role (Optional[Union[Set[str], List[str]]]) – The account roles to include in the digest. Defaults to None.
accounts (Optional[Union[Set[str], List[str]]]) – A list or set of specific accounts to include. Defaults to None.
signs (bool) – Whether to adjust the signs for the account balances based on balance type and account role. Defaults to True.
by_unit (bool) – Whether to group the results by unit. Defaults to False.
by_activity (bool) – Whether to group the results by activity. Defaults to False.
by_tx_type (bool) – Whether to group the results by transaction type. Defaults to False.
by_period (bool) – Whether to group the results by period (year and month). Defaults to False.
use_closing_entries (bool) – Whether to include closing entries in the computation. Defaults to False.
force_queryset_sorting (bool) – Whether to force sorting of the transaction queryset. Defaults to False.
**kwargs (dict) – Additional keyword arguments passed to the computation.
- Returns:
An object containing the transaction queryset, grouped and aggregated account balances, and other relevant digest information.
- Return type:
- class django_ledger.io.io_core.IOMixIn
Provides input and output functionalities by mixing in database and reporting environments.
This class is a mixin that combines functionalities from IODatabaseMixIn and IOReportMixIn. It is designed to integrate database input/output operations with report generation features seamlessly.
- class django_ledger.io.io_core.IOReportMixIn
Provides functionality for generating and managing financial reports.
This mixin class facilitates the generation, processing, and management of various financial statements, including balance sheet statements, income statements, and cash flow statements. Reports can be created in multiple formats, such as plain data representation or as PDF files. The class integrates support for financial data digestion and report serialization, including saving PDF reports to specified file paths. Common use cases include generating summarized financial data for reporting purposes and outputting them in PDF format.
- PDF_REPORT_ORIENTATION
Indicates the orientation of the generated PDF reports (‘P’ for portrait, ‘L’ for landscape).
- Type:
str
- PDF_REPORT_MEASURE_UNIT
Specifies the measurement unit used in the PDF reports (e.g., ‘mm’, ‘cm’).
- Type:
str
- PDF_REPORT_PAGE_SIZE
Defines the size of the pages in the generated PDF reports (e.g., ‘Letter’, ‘A4’).
- Type:
str
- ReportTuple
A tuple structure containing three fields: balance_sheet_statement, income_statement, and cash_flow_statement. Each field represents a respective financial report.
- Type:
namedtuple
- class ReportTuple(balance_sheet_statement, income_statement, cash_flow_statement)
- balance_sheet_statement
Alias for field number 0
- cash_flow_statement
Alias for field number 2
- income_statement
Alias for field number 1
- digest_balance_sheet(to_date: date | datetime, user_model: User | None = None, txs_queryset: QuerySet | None = None, **kwargs: Dict) IODigestContextManager
Digest the balance sheet for a specific time period, user, and optionally a specific set of transactions. Returns a context manager for digesting the specified balance sheet data.
- Parameters:
to_date (Union[date, datetime]) – The date till which the balance sheet needs to be digested, including transactions occurring on this date.
user_model (Optional[UserModel], optional) – The model instance representing the user whose balance sheet is to be digested. This can be None to indicate no specific user.
txs_queryset (Optional[QuerySet], optional) – A queryset containing specific transactions to be included in the calculation. If not provided, all transactions up to to_date will be considered.
kwargs (Dict) – Additional keyword arguments that can be used for the digestion process. Allows flexible filtering or additional specifications.
- Returns:
A context manager for handling the digestion process of the balance sheet.
- Return type:
IODigestContextManager
- digest_cash_flow_statement(from_date: date | datetime, to_date: date | datetime, user_model: User | None = None, txs_queryset: QuerySet | None = None, **kwargs) IODigestContextManager
Generates a digest of the cash flow statement for a specified date range, user model, and optional transaction query set. This method utilizes an internal digest mechanism to compile and return the cash flow statement context.
- Parameters:
from_date (Union[date, datetime]) – The start date of the period for the cash flow statement.
to_date (Union[date, datetime]) – The end date of the period for the cash flow statement.
user_model (Optional[UserModel]) – The user model instance for which the digest is generated. If None, the default user model is used.
txs_queryset (Optional[QuerySet]) – An optional queryset of transactions to include in the digest. If None, defaults to all transactions within the date range.
**kwargs (dict) – Additional keyword arguments passed to the digest function.
- Returns:
Context manager providing the digested cash flow statement.
- Return type:
IODigestContextManager
- digest_financial_statements(from_date: date | datetime, to_date: date | datetime, user_model: User | None = None, **kwargs) IODigestContextManager
Digest financial statements within a given date range, allowing optional customization through kwargs. The method processes and provides access to balance sheet statements, income statements, and cash flow statements for the specified date range. Results are encapsulated in an IODigestContextManager for ease of management.
The function provides flexibility to include a user model for domain-specific processing needs while ensuring support for both date and datetime objects.
- Parameters:
from_date (date or datetime) – The starting date of the range for which financial statements are to be processed.
to_date (date or datetime) – The ending date of the range for which financial statements are to be processed.
user_model (Optional[UserModel], default=None) – A user model instance that allows for context-specific processing during the digestion of financial statements.
kwargs (dict) – Additional optional parameters that may be used to further customize the processing of financial statements.
- Returns:
Represents the context manager containing the digested financial statements for the specified date range.
- Return type:
IODigestContextManager
- digest_income_statement(from_date: date | datetime, to_date: date | datetime, user_model: User | None = None, txs_queryset: QuerySet | None = None, **kwargs) IODigestContextManager
Digest the income statement within the specified date range and optionally filter by user and transaction queryset.
This method generates a digest context manager for the income statement, allowing granular control over the data derived within the requested range and applying any additional filters provided. It supports optional user and transaction queryset filters for tailored data processing.
- Parameters:
from_date (Union[date, datetime]) – The starting date for filtering the income statement.
to_date (Union[date, datetime]) – The ending date for filtering the income statement.
user_model (Optional[UserModel], optional) – An optional user model instance to filter income statement data by a specific user.
txs_queryset (Optional[QuerySet], optional) – An optional transaction queryset to filter the income statement by specific transaction records.
**kwargs (dict) – Additional keyword arguments for customization or requirements in the income statement digest generation process.
- Returns:
A context manager containing the processed income statement data.
- Return type:
IODigestContextManager
- get_balance_sheet_statement(to_date: date | datetime, subtitle: str | None = None, filepath: Path | None = None, filename: str | None = None, user_model: User | None = None, save_pdf: bool = False, **kwargs) IODigestContextManager
Generates a balance sheet statement with an option to save it as a PDF file.
This method fetches and processes financial data to create a balance sheet statement using the provided date range, user model, and additional optional settings. It supports generating a PDF output for the balance sheet if configured. The class responsible for PDF generation is dynamically loaded, allowing modularity and flexibility.
Note that PDF generation functionality is dependent on the presence of the DJANGO_LEDGER_PDF_SUPPORT_ENABLED flag. If the flag is not enabled, the method raises an exception.
- Parameters:
to_date (Union[date, datetime]) – The end date for the balance sheet report. The data will be considered up to this date for the financial statement.
subtitle (Optional[str], default=None) – An optional subtitle for the generated report. This can be used to include additional context or descriptions in the report.
filepath (Optional[Path], default=None) – Specifies the directory path where the PDF file should be saved. If not provided, a default directory is used based on application settings.
filename (Optional[str], default=None) – Name of the file to save the PDF report. Defaults to an automatically generated filename if not provided.
user_model (Optional[UserModel], default=None) – The user context associated with the balance sheet report. Includes permissions or specific user-related data.
save_pdf (bool, default=False) – A flag indicating whether the balance sheet should be saved as a PDF. If True, the method generates and stores the PDF in the specified location.
**kwargs – Additional keyword arguments required for generating the balance sheet. It may include filtering, formatting, or any other relevant parameters.
- Returns:
The context manager object handling the generated balance sheet, either in memory or in saved PDF format. If the save_pdf option is enabled, the PDF report is saved at the specified location.
- Return type:
IODigestContextManager
- get_cash_flow_statement(from_date: date | datetime, to_date: date | datetime, subtitle: str | None = None, filepath: Path | None = None, filename: str | None = None, user_model: User | None = None, save_pdf: bool = False, **kwargs)
Generates a cash flow statement report within a specified date range and provides an option to save the report as a PDF file. The method retrieves financial data, processes it into a structured cash flow statement, and uses a PDF report generator to create the report.
- Parameters:
from_date (Union[date, datetime]) – The start date for the cash flow statement.
to_date (Union[date, datetime]) – The end date for the cash flow statement.
subtitle (Optional[str], default=None) – Subtitle text for the report.
filepath (Optional[Path], default=None) – The directory path where the PDF report will be saved. Defaults to the base directory if not provided.
filename (Optional[str], default=None) – The name of the PDF report file. If not provided, a default name is generated.
user_model (Optional[UserModel], default=None) – The user model instance, optionally used for filtering or customization of the report content.
save_pdf (bool, default=False) – Flag to save the generated report as a PDF file.
kwargs (dict) – Additional keyword arguments that are passed to the digest_cash_flow_statement method for further customization or additional processing.
- Returns:
An instance of the cash flow statement report class, either saved as a PDF if save_pdf is True or ready for further processing or display.
- Return type:
CashFlowStatementReport
- Raises:
IOValidationError – If PDF support is not enabled in the system’s Django ledger configuration.
- get_financial_statements(from_date: date | datetime, to_date: date | datetime, dt_strfmt: str = '%Y%m%d', user_model: User | None = None, save_pdf: bool = False, filepath: Path | None = None, **kwargs) ReportTuple
Generates financial statements for a specified date range, optionally saving them as PDF files. This method consolidates the balance sheet, income statement, and cash flow statement for the given dates. If PDF saving is enabled, the financial statements will be saved to the specified path or the application’s base directory. The results are returned as a tuple containing the reports.
- Parameters:
from_date (Union[date, datetime]) – The start date for the financial statements.
to_date (Union[date, datetime]) – The end date for the financial statements.
dt_strfmt (str) – The string format used for the filenames of the generated PDF reports. Defaults to ‘%Y%m%d’.
user_model (Optional[UserModel], optional) – The user model instance, if applicable. Defaults to None.
save_pdf (bool, optional) – Determines whether to save the generated financial statements as PDF files. Defaults to False.
filepath (Optional[Path], optional) – The directory path where the PDF files will be saved. If not provided, the files will be saved in the application’s base directory. Defaults to None.
**kwargs – Additional keyword arguments for customizing financial statement generation.
- Returns:
A named tuple containing the generated balance sheet, income statement, and cash flow statement as objects.
- Return type:
- Raises:
IOValidationError – Raised if PDF support is not enabled in the application configuration.
- get_income_statement(from_date: date | datetime, to_date: date | datetime, subtitle: str | None = None, filepath: Path | None = None, filename: str | None = None, user_model: User | None = None, txs_queryset: QuerySet | None = None, save_pdf: bool = False, **kwargs)
Generates an income statement report for a specific time period and allows optional PDF saving functionality. The function utilizes configurations, user-provided parameters, and transactions data to create an income statement report, which can either be returned as a report object or saved as a PDF on the filesystem.
- Parameters:
from_date (date or datetime) – The starting date of the income statement period. Must be provided.
to_date (date or datetime) – The ending date of the income statement period. Must be provided.
subtitle (str, optional) – An optional subtitle for the income statement report.
filepath (Path, optional) – The directory path where the PDF report should be saved, if save_pdf is set to True.
filename (str, optional) – The filename for the PDF report. If not provided, a default filename is generated.
user_model (UserModel, optional) – A user model instance, providing additional context or filtering for the income statement generation.
txs_queryset (QuerySet, optional) – A queryset containing transactions data to be included in the income statement report. If not provided, transactions may be automatically determined by other parameters or configurations.
save_pdf (bool) – Indicates whether the generated income statement should be saved as a PDF file. Defaults to False.
**kwargs – Additional optional keyword arguments for further customization or filtering.
- Raises:
IOValidationError – Raised if PDF support is not enabled in the configuration. The error provides a message suggesting installing PDF support.
- Returns:
A configured instance of the IncomeStatementReport class, representing the generated income statement report. If save_pdf is True, the report will also be saved as a PDF file at the specified location.
- Return type:
IncomeStatementReport
- class django_ledger.io.io_core.IOResult(db_from_date: date | None = None, db_to_date: date | None = None, ce_match: bool = False, ce_from_date: date | None = None, ce_to_date: date | None = None, accounts_digest: List[Dict] | None = None)
Represents the input-output result schema for data aggregation and processing.
This class encapsulates details related to database aggregation, closing entry lookup parameters, and the final dataset used for evaluation. It also provides utility to check bounded date constraints for closing entry lookups.
- db_from_date
The starting date for database aggregation queries.
- Type:
Optional[date]
- db_to_date
The ending date for database aggregation queries.
- Type:
Optional[date]
- ce_match
Indicates whether closing entry matches are applicable.
- Type:
bool
- ce_from_date
The starting date for closing entry lookups.
- Type:
Optional[date]
- ce_to_date
The ending date for closing entry lookups.
- Type:
Optional[date]
- txs_queryset
The final queryset used for evaluation, typically containing processed transaction data.
- accounts_digest
A summary or aggregation of account balances derived from the processed data.
- Type:
Optional[List[Dict]]
- exception django_ledger.io.io_core.IOValidationError(message, code=None, params=None)
- django_ledger.io.io_core.check_tx_balance(tx_data: list, perform_correction: bool = False) bool
Checks the validity of a list of transactions and optionally corrects the balance discrepancy if any. The function assesses whether the total balance from the transactions satisfies the predefined tolerance settings. If perform_correction is enabled, it adjusts the transactions iteratively to correct discrepancies.
- Parameters:
tx_data (list) – A list of transaction data where each transaction contains information such as amount and type (‘debit’ or ‘credit’).
perform_correction (bool, optional) – A flag indicating whether to attempt to correct balance discrepancies in the transaction data. Defaults to False.
- Returns:
Returns True if the transactions are valid and satisfy the balance tolerance (with or without correction). Returns False otherwise.
- Return type:
bool
- django_ledger.io.io_core.diff_tx_data(tx_data: list, raise_exception: bool = True)
Calculates the difference between credits and debits in a transaction dataset and validates if the transactions are in balance. Supports both dictionary-like data and TransactionModel objects.
The function checks whether the provided transaction data is in balance by comparing the sum of credits and debits. If they are not in balance, the function optionally raises an exception when the discrepancy exceeds the defined tolerance limit. It also indicates whether the transaction data is modeled using TransactionModel.
- Parameters:
tx_data (list) – A list of transactions, which can either be dictionaries or instances of TransactionModel. Each transaction must have an amount field and a tx_type field. The tx_type should be either ‘credit’ or ‘debit’.
raise_exception (bool, optional) – Whether to raise an exception if the transactions are not balanced and the difference exceeds the defined tolerance value. Defaults to True.
- Returns:
- A tuple containing the following:
IS_TX_MODEL (bool): Indicates whether the transaction data uses the TransactionModel.
is_valid (bool): Indicates whether the total credits match the total debits within the defined tolerance.
diff (float): The difference between the sum of credits and the sum of debits.
- Return type:
tuple
- Raises:
ValidationError – If the tx_data is neither a list of dictionaries nor a list of TransactionModel instances.
TransactionNotInBalanceError – If the transactions are not in balance (when is_valid is False), the difference exceeds the maximum tolerance, and raise_exception is True.
- django_ledger.io.io_core.get_localdate() date
Fetches the current local date, optionally considering time zone settings.
This function retrieves the current local date. If the global settings indicate the use of time zones (USE_TZ is True), the date is determined based on the local time zone. Otherwise, the date is based on the system’s local time without any time zone consideration.
- Returns:
The current local date, adjusted for the time zone setting if applicable.
- Return type:
date
- django_ledger.io.io_core.get_localtime(tz=None) datetime
Retrieve the local time based on the specified timezone.
Determines the local time depending on whether timezone support (
USE_TZ
) is enabled in global settings. If timezone support is enabled, it uses the localtime function to obtain the local time according to the provided timezone. If timezone support is disabled, it defaults to the current time with respect to the given timezone.- Parameters:
tz (timezone or None, optional) – The timezone to determine the local time. If None, defaults to the system timezone.
- Returns:
A datetime object representing the calculated local time.
- Return type:
datetime
- django_ledger.io.io_core.validate_activity(activity: str, raise_404: bool = False)
Validates the given activity against the list of valid activities and raises appropriate exceptions if it is invalid.
This function checks whether the provided activity is included in the list of valid activities defined within the JournalEntryModel. It raises a ValidationError or Http404 error depending on the value of raise_404 if the activity is not valid. If the activity is valid or not provided, it returns the activity unaltered.
- Parameters:
activity (str) – The activity string to validate against the valid activities.
raise_404 (bool, optional) – Whether to raise an Http404 error instead of ValidationError when the activity is invalid. Default is False.
- Returns:
The activity string if it is valid.
- Return type:
str
- Raises:
ValidationError – If the activity is invalid and raise_404 is False.
Http404 – If the activity is invalid and raise_404 is True.
- django_ledger.io.io_core.validate_dates(from_date: str | datetime | date | None = None, to_date: str | datetime | date | None = None) Tuple[date, date]
Validates and converts the input dates to date objects. This function ensures that the provided from_date and to_date are correctly parsed into date objects. If the dates are given as strings or datetime objects, they will be validated and converted to date objects accordingly.
- Parameters:
from_date (str, datetime, date, optional) – The start date, which can be provided as a string, datetime, or date object. If not provided, it may default depending on the implementation of the validate_io_timestamp function.
to_date (str, datetime, date, optional) – The end date, which can be provided as a string, datetime, or date object. If not provided, it may default depending on the implementation of the validate_io_timestamp function.
- Returns:
A tuple containing the validated from_date and to_date as date objects. The first element is the validated start date, and the second element is the validated end date.
- Return type:
Tuple[date, date]
- django_ledger.io.io_core.validate_io_timestamp(dt: str | date | datetime, no_parse_localdate: bool = True) datetime | date | None
Validates and processes a given date or datetime input and returns a processed datetime or date object depending on the parsing and processing results. This function is designed to handle multiple types of inputs including strings, date objects, and datetime objects, while accounting for timezone awareness and other scenarios where inputs may be invalid or improperly formed.
- Parameters:
dt (Union[str, date, datetime]) – The input value to be validated and processed. This can be a string representing a date or datetime, a date object, or a datetime object. If the input is invalid or cannot be parsed, an error will be raised.
no_parse_localdate (bool, optional) – A flag to indicate if the local date should be returned directly when the input cannot be parsed or is unavailable. Defaults to True.
- Returns:
Returns a timezone-aware or naive datetime object that was processed depending on input and timezone settings. May also return a date object in specific scenarios. Returns None if the input is empty or invalid.
- Return type:
Optional[Union[datetime, date]]
- Raises:
InvalidDateInputError – Raised when the provided string cannot be parsed into a valid date or datetime object.
Notes
The function handles both timezone-aware and naive datetime objects, and attempts to make objects timezone-aware when global time zone settings are enabled.
String inputs are first attempted to be parsed into date objects before attempting to parse them into datetime objects if the initial attempt fails.
When no_parse_localdate is True, the function defaults to returning the local time for cases where parsing is not possible.
Account Roles
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
- Contributions to this module:
Miguel Sanda <msanda@arrobalytics.com>
- django_ledger.io.roles.validate_roles(roles: str | List[str], raise_exception: bool = True) Set[str]
Validates a given role identifier against the valid role available. :param roles: The role or list of roles to validate. :type roles: str or list :param raise_exception: Raises InvalidRoleError if any of the roles provided if not valid. :type raise_exception: bool
- Returns:
A set of the valid roles.
- Return type:
set
Financial Ratios
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
Contributions to this module: Miguel Sanda <msanda@arrobalytics.com>
Random Data Generation
Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.
Contributions to this module: Miguel Sanda <msanda@arrobalytics.com>
This is a random data generator module used during the testing of the API and for Educational purposes.
The class EntityDataGenerator will only work on new entities that contain no Transactions. This is with the intention of avoiding unintentional commingling with an actual EntityModel with production data and the data generated randomly.
This class will conveniently create a Chart of Accounts and populate the database will Bills, Invoices and various other Transactions. The user will be able to immediately browse the Entity data by clicking on the newly created entity’s details page.
All data generated is random and fake, not related to any other entity data.
- class django_ledger.io.io_generator.EntityDataGenerator(user_model, entity_model: EntityModel | str, start_dttm: datetime, capital_contribution: Decimal, days_forward: int, tx_quantity: int = 25)
A random data generator for Entity Models. Requires a user to me the entity model administrator.
- user_model
The Django user model that administers the entity.
- Type:
UserModel
- entity_model
The Entity model to populate.
- Type:
- start_dttm
The start datetime for new transactions. All transactions will be posted no earlier than this date.
- Type:
datetime
- capital_contribution
The initial capital contribution amount for the Entity Model. This will help fund the entity.
- Type:
Decimal
- days_forward
The number of days to span from the start_dttm for new transactions.
- Type:
int
- exception django_ledger.io.io_generator.EntityModelValidationError(message, code=None, params=None)
- django_ledger.io.io_generator.random() x in the interval [0, 1).