IO Engine#

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: Union[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:

EntityModel

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).#

IO MixIn#

Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.

Contributions to this module:

This module provides the building block interface for Django Ledger. The classes and functions contained in this module provide an interface to Django Ledger to create and manage Transactions into the Database. It also provides an optimized interface to push as much work as possible to the database without having to pull transactions from the database into the Python memory.

The database records the individual transactions associated with each Journal Entry. However, this interface aggregates transactions during the digest method based on a specific request. The Python interpreter is responsible for applying accounting rules to the transactions associated with each Journal Entry so the appropriate account balances are computed.

class django_ledger.io.io_core.IODatabaseMixIn#

The main entry point to query DB for transactions. The database_digest method pushes as much load as possible to the Database so transactions are aggregated at the database layer and are not pulled into memory. This is important por performance purposes since Entities may have a large amount of transactions to be aggregated.

The python_digest method aggregates and processes the raw data stored in the database and applies accounting rules to stored transactions.

This method also makes use of Closing Entries whenever possible to minimize the amount of data to aggregate during a specific call. Closing Entries can be considered “checkpoints”, which create materialized aggregation of transactions for commonly used dates. (i.e. Fiscal Year End, Month End, Quarter End, etc.). This approach helps minimize the number of transactions to aggregate for a given request.

database_digest(entity_slug: Optional[str] = None, unit_slug: Optional[str] = None, user_model: Optional[User] = None, from_date: Optional[Union[datetime, date]] = None, to_date: Optional[Union[datetime, date]] = None, by_activity: bool = False, by_tx_type: bool = False, by_period: bool = False, by_unit: bool = False, activity: Optional[str] = None, role: str = typing.Optional[str], accounts: Optional[Union[str, List[str], Set[str]]] = None, posted: bool = True, exclude_zero_bal: bool = True, use_closing_entries: bool = False, **kwargs) IOResult#

Performs the appropriate database aggregation query for a given request.

Parameters:
  • entity_slug (str) – EntityModel slug to use. If not provided it will be derived from the EntityModel instance. Will be validated against current EntityModel instance for safety. Defaults to None.

  • unit_slug (str) – EntityUnitModel used to query transactions. If provided will be validated against current EntityModelUnit instance. Defaults to None.

  • user_model (UserModel) – The django UserModel to validate against transaction ownership and permissions (i.e. Admin and Manager). Defaults to None.

  • from_date (date or datetime) – Stating date or datetime to query from (inclusive).

  • to_date (date or datetime) – End date or datetime to query to (inclusive).

  • activity (str) – Filters transactions to match specific activity. Defaults to None.

  • role (str) – Filters transactions to match specific role. Defaults to None.

  • accounts (str or List[str] ot Set[str]) – Optional list of accounts to query. Defaults to None (all).

  • posted (bool) – Consider only posted transactions. Defaults to True.

  • exclude_zero_bal (bool) – Excludes transactions with zero balance, if any.

  • by_activity (bool) – Returns results aggregated by activity if needed. Defaults to False.

  • by_tx_type (bool) – Returns results aggregated by DEBIT/CREDIT if needed. Defaults to False.

  • by_period (bool) – Returns results aggregated by accounting if needed. Defaults to False.

  • by_unit (bool) – Returns results aggregated by unit if needed. Defaults to False.

  • use_closing_entry (bool) – Overrides the DJANGO_LEDGER_USE_CLOSING_ENTRIES setting.

Return type:

IOResult

python_digest(user_model: Optional[User] = None, entity_slug: Optional[str] = None, unit_slug: Optional[str] = None, to_date: Optional[Union[date, datetime, str]] = None, from_date: Optional[Union[date, datetime, str]] = None, equity_only: bool = False, activity: Optional[str] = None, role: Optional[Union[Set[str], List[str]]] = None, accounts: Optional[Union[Set[str], List[str]]] = 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#

Performs the appropriate transaction post-processing after DB aggregation..

Parameters:
  • entity_slug (str) – EntityModel slug to use. If not provided it will be derived from the EntityModel instance. Will be validated against current EntityModel instance for safety. Defaults to None.

  • unit_slug (str) – EntityUnitModel used to query transactions. If provided will be validated against current EntityModelUnit instance. Defaults to None.

  • user_model (UserModel) – The django UserModel to validate against transaction ownership and permissions (i.e. Admin and Manager). Defaults to None.

  • from_date (date or datetime) – Stating date or datetime to query from (inclusive).

  • to_date (date or datetime) – End date or datetime to query to (inclusive).

  • activity (str) – Filters transactions to match specific activity. Defaults to None.

  • role (str) – Filters transactions to match specific role. Defaults to None.

  • accounts (str or List[str] ot Set[str]) – Optional list of accounts to query. Defaults to None (all).

  • by_activity (bool) – Returns results aggregated by activity if needed. Defaults to False.

  • by_tx_type (bool) – Returns results aggregated by DEBIT/CREDIT if needed. Defaults to False.

  • by_period (bool) – Returns results aggregated by accounting if needed. Defaults to False.

  • by_unit (bool) – Returns results aggregated by unit if needed. Defaults to False.

  • equity_only (bool) – Performs aggregation only on accounts that impact equity only (i.e. Income Statement Generation). Avoids unnecessary inclusion of accounts not relevant to what’s needed.

  • signs (bool) – Changes the balance of an account to negative if it represents a “negative” for display purposes. (i.e. Expense accounts will show balance as negative and Income accounts as positive.)

  • force_closing_entry_use (bool) – Forces the use of closing entries if DJANGO_LEDGER_USE_CLOSING_ENTRIES setting is set to False.

  • force_queryset_sorting (bool) – Forces sorting of the TransactionModelQuerySet before aggregation balances. Defaults to false.

Return type:

IOResult

class django_ledger.io.io_core.IOMixIn#
class django_ledger.io.io_core.IOResult(db_from_date: Optional[date] = None, db_to_date: Optional[date] = None, ce_match: bool = False, ce_from_date: Optional[date] = None, ce_to_date: Optional[date] = None, accounts_digest: Optional[List[Dict]] = None)#

A carrier class to store IO digest information during the digest call.

exception django_ledger.io.io_core.IOValidationError(message, code=None, params=None)#
django_ledger.io.io_core.get_localdate() date#

Convenience function to retrieve the local date of the current system based on the USE_TZ django setting.

Return type:

date

django_ledger.io.io_core.get_localtime(tz=None) datetime#

Convenience function to retrieve the localtime of the current system based on the USE_TZ django setting.

Parameters:

tz (ZoneInfo) – Optional timezone to use, otherwise the system timezone is used.

Return type:

datetime

IO Context#

Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.

Contributions to this module:

IO Library#

Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.

Contributions to this module:

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: Optional[str] = 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: Optional[Union[str, LedgerModel, UUID]] = None, je_timestamp: Optional[Union[date, datetime, str]] = 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: Union[float, Decimal], description: Optional[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: Union[float, Decimal], description: Optional[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, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Optional[Union[date, datetime, str]] = 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.

  • 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: Optional[Union[str, LedgerModel, UUID]] = 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:

AccountModelQuerySet

get_ledger_model_qs() LedgerModelQuerySet#

Determines the ledger model queryset associated with the entity model and user model provided.

Return type:

LedgerModelQuerySet

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: List[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:

AccountModelQuerySet

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:

LedgerModelQuerySet

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, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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.

Return type:

IOCursor

exception django_ledger.io.io_library.IOLibraryError(message, code=None, params=None)#
class django_ledger.io.io_library.TransactionInstructionItem(account_code: str, amount: Union[Decimal, float], tx_type: str, description: Optional[str], account_model: Optional[AccountModel] = 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:

AccountModel

IO Digest#

Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.

Contributions to this module:
exception django_ledger.io.io_digest.IODigestValidationError(message, code=None, params=None)#

Account Roles#

Django Ledger created by Miguel Sanda <msanda@arrobalytics.com>. Copyright© EDMA Group Inc licensed under the GPLv3 Agreement.

Contributions to this module:
django_ledger.io.roles.validate_roles(roles: Union[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