Models

Model Dependency Diagram

_images/ModelDependency.png

Database Fields

_images/ModelDependencyDetail.png

Entity Model

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

The EntityModel represents the Company, Corporation, Legal Entity, Enterprise or Person that engage and operate as a business. EntityModels can be created as part of a parent/child model structure to accommodate complex corporate structures where certain entities may be owned by other entities and may also generate consolidated financial statements.

Another use case of parent/child model structures is the coordination and authorization of inter-company transactions across multiple related entities. The EntityModel encapsulates all LedgerModel, JournalEntryModel and TransactionModel which is the core structure of Django Ledger in order to track and produce all financials.

The EntityModel must be assigned an Administrator at creation, and may have optional Managers that will have the ability to operate on such EntityModel.

EntityModels may also have different financial reporting periods, (also known as fiscal year), which start month is specified at the time of creation. All key functionality around the Fiscal Year is encapsulated in the EntityReportMixIn.

class django_ledger.models.entity.EntityManagementModel(*args, **kwargs)

EntityManagement Model Base Class From Abstract

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.entity.EntityManagementModelAbstract(*args, **kwargs)

Entity Management Model responsible for manager permissions to read/write.

class django_ledger.models.entity.EntityModel(*args, **kwargs)

Entity Model Base Class From Abstract

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.entity.EntityModelAbstract(*args, **kwargs)

The base implementation of the EntityModel. The EntityModel represents the Company, Corporation, Legal Entity, Enterprise or Person that engage and operate as a business. The base model inherit from the Materialized Path Node of the Django Treebeard library. This allows for complex parent/child relationships between Entities to be tracked and managed properly.

The EntityModel also inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

name

The name of the Company, Enterprise, Person, etc. used to identify the Entity.

Type:

str

admin

The Django UserModel that will be assigned as the administrator of the EntityModel.

Type:

UserModel

default_coa

The default Chart of Accounts Model of the Entity. EntityModel can have multiple Chart of Accounts but only one can be assigned as default.

Type:

ChartOfAccounts

managers

The Django UserModels that will be assigned as the managers of the EntityModel by the admin.

Type:

UserModel

hidden

A flag used to hide the EntityModel from QuerySets. Defaults to False.

Type:

bool

accrual_method
A flag used to define which method of accounting will be used to produce financial statements.
  • If False, Cash Method of Accounting will be used.

  • If True, Accrual Method of Accounting will be used.

Type:

bool

fy_start_month

An integer that specifies the month that the Fiscal Year starts.

Type:

int

picture

The image or logo used to identify the company on reports or UI/UX.

class Meta
clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

create_account(code: str, role: str, name: str, balance_type: str, active: bool = False, coa_model: ChartOfAccountModel | UUID | str | None = None, raise_exception: bool = True) AccountModel

Creates a new AccountModel for the EntityModel.

Parameters:
  • code (str) – The AccountModel code of the new Account.

  • role (str) – The choice of role that the new Account belongs to.

  • name (str) – The name of the new Account.

  • balance_type (str) – The balance type of the new account. Possible values are ‘debit’ or ‘credit’.

  • active (bool) – Active status of the new account.

  • coa_model (ChartOfAccountModel, UUID, str) – The ChartOfAccountsModel UUID, model instance or slug to pull accounts from. Uses default Coa if not provided.

  • raise_exception (bool) – Raises EntityModelValidationError if ChartOfAccountsModel is not valid for the EntityModel instance.

Returns:

The ChartOfAccountModel and AccountModel instance just created.

Return type:

A tuple of ChartOfAccountModel, AccountModel

create_account_by_kwargs(account_model_kwargs: Dict, coa_model: ChartOfAccountModel | UUID | str | None = None, raise_exception: bool = True) Tuple[ChartOfAccountModel, AccountModel]

Creates a new AccountModel for the EntityModel by passing AccountModel KWARGS. This is a legacy method for creating a new AccountModel for the EntityModel. Will be deprecated in favor of create_account().

Parameters:
  • coa_model (ChartOfAccountModel, UUID, str) – The ChartOfAccountsModel UUID, model instance or slug to pull accounts from. Uses default Coa if not provided.

  • account_model_kwargs (dict) – A dictionary of kwargs to be used to create the new AccountModel instance.

  • raise_exception (bool) – Raises EntityModelValidationError if ChartOfAccountsModel is not valid for the EntityModel instance.

Returns:

The ChartOfAccountModel and AccountModel instance just created.

Return type:

A tuple of ChartOfAccountModel, AccountModel

create_bank_account(name: str, account_type: str, active=False, account_model: AccountModel | None = None, coa_model: ChartOfAccountModel | UUID | str | None = None, bank_account_model_kwargs: Dict | None = None, commit: bool = True)

Create a bank account entry for the entity model with specified attributes and validation.

This method creates a new instance of BankAccountModel, validates the given inputs, and saves it to the database if commit is set to True.

Parameters:
  • name (str) – The name of the bank account to be created.

  • account_type (str) – The account type. It must be one of the valid types defined in BankAccountModel.VALID_ACCOUNT_TYPES.

  • active (bool, optional) – A flag indicating whether the account is active. Defaults to False.

  • account_model (Optional[AccountModel], optional) – An optional pre-existing account model instance to link to the bank account.

  • coa_model (Optional[Union[ChartOfAccountModel, UUID, str]], optional) – The chart of account model or an identifier to filter accounts. Can accept a UUID, string, or ChartOfAccountModel.

  • bank_account_model_kwargs (Optional[Dict], optional) – Additional keyword arguments to initialize the BankAccountModel instance. Defaults to an empty dictionary.

  • commit (bool, optional) – Flag indicating whether to save the created bank account to the database. Defaults to True.

Returns:

The newly created and optionally saved instance of the bank account model.

Return type:

BankAccountModel

create_bill(vendor_model: VendorModel | UUID | str, terms: str, date_draft: datetime | date | None = None, xref: str | None = None, cash_account: AccountModel | None = None, prepaid_account: AccountModel | None = None, payable_account: AccountModel | None = None, additional_info: Dict | None = None, ledger_name: str | None = None, coa_model: ChartOfAccountModel | UUID | str | None = None, commit: bool = True)

Creates a new BillModel for the EntityModel instance. Bill will have DRAFT status.

Parameters:
  • vendor_model (VendorModel or UUID or str) – The VendorModel, VendorModel UUID or VendorModel Number

  • terms (str) – Payment terms of the new BillModel. A choice of BillModel.TERM_CHOICES_VALID

  • date_draft (date or datetime) – Date to use as draft date for the new BillModel.

  • xref (str) – Optional External Reference for the Bill (i.e. Vendor invoice number.)

  • cash_account (AccountModel) – Optional CASH AccountModel associated with the new BillModel. Defaults to CASH default AccountModel role.

  • prepaid_account (AccountModel) – Optional PREPAID AccountModel associated with the new BillModel for accruing purposes. Defaults to PREPAID default AccountModel role.

  • payable_account (AccountModel) – Optional PAYABLE AccountModel associated with the new BillModel for accruing purposes. Defaults to ACCOUNTS PAYABLE default AccountModel role.

  • additional_info (Dict) – Additional user-defined information stored as JSON in the Database.

  • ledger_name (str) – Optional LedgerModel name to be assigned to the BillModel instance.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels

  • commit (bool) – If True, commits the new BillModel in the Database.

Returns:

The newly created BillModel in DRAFT state.

Return type:

BillModel

create_chart_of_accounts(assign_as_default: bool = False, coa_name: str | None = None, commit: bool = False) ChartOfAccountModel

Creates a Chart of Accounts for the Entity Model and optionally assign it as the default Chart of Accounts. EntityModel must have a default Chart of Accounts before being able to transact.

Parameters:
  • coa_name (str) – The new CoA name. If not provided will be auto generated based on the EntityModel name.

  • commit (bool) – Commits the transaction into the DB. A ChartOfAccountModel will

  • assign_as_default (bool) – Assigns the newly created ChartOfAccountModel as the EntityModel default_coa.

Returns:

The newly created chart of accounts model.

Return type:

ChartOfAccountModel

create_customer(customer_model_kwargs: Dict, commit: bool = True) CustomerModel

Creates a new CustomerModel associated with the EntityModel instance.

Parameters:
  • customer_model_kwargs (dict) – The kwargs to be used for the new CustomerModel.

  • commit (bool) – Saves the CustomerModel instance in the Database.

Return type:

CustomerModel

classmethod create_entity(name: str, use_accrual_method: bool, admin: User, fy_start_month: int, parent_entity=None)

Convenience Method to Create a new Entity Model. This is the preferred method to create new Entities in order to properly handle potential parent/child relationships between EntityModels.

Parameters:
  • name (str) – The name of the new Entity.

  • use_accrual_method (bool) – If True, accrual method of accounting will be used, otherwise Cash Method of accounting will be used.

  • fy_start_month (int) – The month which represents the start of a new fiscal year. 1 represents January, 12 represents December.

  • admin (UserModel) – The administrator of the new EntityModel.

  • parent_entity (EntityModel) – The parent Entity Model of the newly created Entity. If provided, the admin user must also be admin of the parent company.

create_estimate(estimate_title: str, contract_terms: str, customer_model: CustomerModel | UUID | str, date_draft: date | None = None, commit: bool = True)

Creates a new EstimateModel for the EntityModel instance. Estimate will have DRAFT status.

Parameters:
  • estimate_title (str) – A user defined title for the Estimate.

  • date_draft (date) – Optional date to use as Draft Date. Defaults to localdate() if None.

  • customer_model (CustomerModel or UUID or str) – The CustomerModel, CustomerModel UUID or CustomerModel Number

  • contract_terms (str) – A choice of EstimateModel.CONTRACT_TERMS_CHOICES_VALID

  • commit (bool) – If True, commits the new PO in the Database. Defaults to True.

Returns:

The newly created PurchaseOrderModel in DRAFT state.

Return type:

PurchaseOrderModel

create_invoice(customer_model: VendorModel | UUID | str, terms: str, cash_account: AccountModel | None = None, prepaid_account: AccountModel | None = None, payable_account: AccountModel | None = None, additional_info: Dict | None = None, ledger_name: str | None = None, coa_model: ChartOfAccountModel | UUID | str | None = None, date_draft: date | None = None, commit: bool = True)

Creates a new InvoiceModel for the EntityModel instance. Invoice will have DRAFT status.

Parameters:
  • customer_model (CustomerModel or UUID or str) – The CustomerModel, CustomerModel UUID or CustomerModel Number

  • terms (str) – A choice of InvoiceModel.TERM_CHOICES_VALID

  • cash_account (AccountModel) – Optional CASH AccountModel associated with the new InvoiceModel. Defaults to CASH default AccountModel role.

  • prepaid_account (AccountModel) – Optional PREPAID AccountModel associated with the new InvoiceModel for accruing purposes. Defaults to PREPAID default AccountModel role.

  • payable_account (AccountModel) – Optional PAYABLE AccountModel associated with the new InvoiceModel for accruing purposes. Defaults to ACCOUNTS PAYABLE default AccountModel role.

  • additional_info (Dict) – Additional user-defined information stored as JSON in the Database.

  • ledger_name (str) – Optional LedgerModel name to be assigned to the InvoiceModel instance.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels

  • date_draft (date) – Optional date to use as Draft Date. Defaults to localdate() if None.

  • commit (bool) – If True, commits the new BillModel in the Database.

Returns:

The newly created InvoiceModel in DRAFT state.

Return type:

InvoiceModel

create_item_expense(name: str, expense_type: str, uom_model: UUID | UnitOfMeasureModel, expense_account: UUID | AccountModel | None = None, coa_model: ChartOfAccountModel | UUID | str | None = None, commit: bool = True) ItemModel

Creates a new items of type EXPENSE.

Parameters:
  • name (str) – The name of the new service.

  • expense_type (str) – The type of expense. A choice of ItemModel.ITEM_TYPE_CHOICES

  • uom_model – The UOM UUID or UnitOfMeasureModel of the Service. Will be validated if provided.

  • expense_account (AccountModel) – Optional EXPENSE_OPERATIONAL AccountModel associated with the new Expense Item. Defaults to EXPENSE_OPERATIONAL default AccountModel role.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels.

  • commit (bool) – Commits the ItemModel in the DB. Defaults to True.

Return type:

ItemModel

create_item_inventory(name: str, uom_model: UUID | UnitOfMeasureModel, item_type: str, inventory_account: UUID | AccountModel | None = None, coa_model: ChartOfAccountModel | UUID | str | None = None, commit: bool = True)

Creates a new items of type INVENTORY.

Parameters:
  • name (str) – The name of the new service.

  • item_type (str) – The type of expense. A choice of ItemModel.ITEM_TYPE_CHOICES

  • uom_model – The UOM UUID or UnitOfMeasureModel of the Service. Will be validated if provided.

  • inventory_account (AccountModel) – Optional ASSET_CA_INVENTORY AccountModel associated with the new Expense Item. Defaults to ASSET_CA_INVENTORY default AccountModel role.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels.

  • commit (bool) – Commits the ItemModel in the DB. Defaults to True.

Return type:

ItemModel

create_item_product(name: str, item_type: str, uom_model: UUID | UnitOfMeasureModel, coa_model: ChartOfAccountModel | UUID | str | None = None, commit: bool = True) ItemModel

Creates a new items of type PRODUCT.

Parameters:
  • name (str) – Name of the new service.

  • item_type (str) – The type of product. A choice of ItemModel.ITEM_TYPE_CHOICES

  • uom_model – The UOM UUID or UnitOfMeasureModel of the Service. Will be validated if provided.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels.

  • commit (bool) – Commits the ItemModel in the DB. Defaults to True.

Returns:

The created Product.

Return type:

ItemModel

create_item_service(name: str, uom_model: UUID | UnitOfMeasureModel, coa_model: ChartOfAccountModel | UUID | str | None = None, commit: bool = True) ItemModel

Creates a new items of type SERVICE.

Parameters:
  • name (str) – Name of the new service.

  • uom_model – The UOM UUID or UnitOfMeasureModel of the Service. Will be validated if provided.

  • coa_model (ChartOfAccountModel) – Optional ChartOfAccountsModel to use when fetching default role AccountModels.

  • commit (bool) – Commits the ItemModel in the DB. Defaults to True.

Returns:

The created Service.

Return type:

ItemModel

create_purchase_order(po_title: str | None = None, estimate_model=None, date_draft: date | None = None, commit: bool = True)

Creates a new PurchaseOrderModel for the EntityModel instance. PO will have DRAFT status.

Parameters:
  • po_title (str) – The user defined title for the new Purchase Order Model.

  • date_draft (date) – Optional date to use as Draft Date. Defaults to localdate() if None.

  • estimate_model (EstimateModel) – The EstimateModel to associate the PO for tracking.

  • commit (bool) – If True, commits the new PO in the Database. Defaults to True.

Returns:

The newly created PurchaseOrderModel in DRAFT state.

Return type:

PurchaseOrderModel

create_uom(name: str, unit_abbr: str, active: bool = True, commit: bool = True) UnitOfMeasureModel

Creates a new Unit of Measure Model associated with the EntityModel instance

Parameters:
  • name (str) – The user defined name of the new Unit of Measure Model instance.

  • unit_abbr (str) – The unique slug abbreviation of the UoM model. Will be indexed.

  • active (bool) – Mark this UoM as active.

  • commit (bool) – Saves the model in the DB if True. Defaults to True

Return type:

UnitOfMeasureModel

create_vendor(vendor_model_kwargs: Dict, commit: bool = True) VendorModel

Creates a new VendorModel associated with the EntityModel instance.

Parameters:
  • vendor_model_kwargs (dict) – The kwargs to be used for the new VendorModel.

  • commit (bool) – Saves the VendorModel instance in the Database.

Return type:

VendorModel

generate_slug(commit: bool = False, raise_exception: bool = True, force_update: bool = False) str

Convenience method to create the EntityModel slug.

Parameters:
  • force_update (bool) – If True, will update the EntityModel slug.

  • raise_exception (bool) – Raises ValidationError if EntityModel already has a slug.

  • commit (bool) – If True,

static generate_slug_from_name(name: str) str

Uses Django’s slugify function to create a valid slug from any given string.

Parameters:

name (str) – The name or string to slugify.

Return type:

The slug as a String.

get_accounts_url() str

The EntityModel Code of Accounts llist import URL.

Returns:

EntityModel Code of Accounts llist import URL as a string.

Return type:

str

get_accounts_with_codes(code_list: str | List[str] | Set[str], coa_model: ChartOfAccountModel | UUID | str | None = None) AccountModelQuerySet

Fetches the AccountModelQuerySet with provided code list.

Parameters:
  • coa_model (ChartOfAccountModel, UUID, str) – The ChartOfAccountsModel UUID, model instance or slug to pull accounts from. Uses default Coa if not provided.

  • code_list (list or str) – Code or list of codes to fetch.

Returns:

The requested AccountModelQuerySet with applied code filter.

Return type:

AccountModelQuerySet

get_all_accounts(active: bool = True, order_by: Tuple[str] | None = ('code',)) AccountModelQuerySet

Fetches all AccountModelQuerySet associated with the EntityModel.

Parameters:
  • active (bool) – Selects only active accounts.

  • order_by (list of strings.) – Optional list of fields passed to the order_by QuerySet method.

Returns:

The AccountModelQuerySet of the assigned default CoA.

Return type:

AccountModelQuerySet

get_all_coa_accounts(order_by: Tuple[str] | None = ('code',), active: bool = True) Tuple[ChartOfAccountModelQuerySet, Dict[ChartOfAccountModel, AccountModelQuerySet]]

Fetches all the AccountModels associated with the EntityModel grouped by ChartOfAccountModel.

Parameters:
  • active (bool) – Selects only active accounts.

  • order_by (list of strings.) – Optional list of fields passed to the order_by QuerySet method.

Returns:

Tuple – The ChartOfAccountModelQuerySet and a grouping of AccountModels by ChartOfAccountModel as keys.

Return type:

Tuple[ChartOfAccountModelQuerySet, Dict[ChartOfAccountModel, AccountModelQuerySet]

get_balance_sheet_url() str

The EntityModel Balance Sheet Statement URL.

Returns:

EntityModel Balance Sheet Statement URL as a string.

Return type:

str

get_bank_accounts(active: bool = True) BankAccountModelQuerySet

Fetches a QuerySet of BankAccountModels associated with the EntityModel instance.

Parameters:

active (bool) – If True, returns only active Bank Accounts. Defaults to True.

Return type:

BankAccountModelQuerySet

get_banks_url() str

The EntityModel bank account list URL.

Returns:

EntityModel bank account list URL as a string.

Return type:

str

get_bills()

Fetches a QuerySet of BillModels associated with the EntityModel instance.

Return type:

BillModelQuerySet

get_bills_url() str

The EntityModel bill list URL.

Returns:

EntityModel bill list URL as a string.

Return type:

str

get_cashflow_statement_url() str

The EntityModel Cashflow Statement URL.

Returns:

EntityModel Cashflow Statement URL as a string.

Return type:

str

get_coa_accounts(coa_model: ChartOfAccountModel | UUID | str | None = None, active: bool = True, locked: bool = False, order_by: Tuple | None = ('code',), return_coa_model: bool = False) AccountModelQuerySet | Tuple[ChartOfAccountModel, AccountModelQuerySet]

Fetches the AccountModelQuerySet for a specific ChartOfAccountModel.

Parameters:
  • coa_model (ChartOfAccountModel, UUID, str) – The ChartOfAccountsModel UUID, model instance or slug to pull accounts from. If None, will use default CoA.

  • active (bool) – Selects only active accounts.

  • locked (bool) – Selects only locked accounts.

  • order_by (list of strings.) – Optional list of fields passed to the order_by QuerySet method.

Returns:

The AccountModelQuerySet of the assigned default CoA.

Return type:

AccountModelQuerySet

get_coa_model_qs(active: bool = True)

Fetches the current Entity Model instance Chart of Accounts Model Queryset.

Parameters:

active (bool) – Returns only active Chart of Account Models. Defaults to True.

Return type:

ChartOfAccountModelQuerySet

get_customers(active: bool = True) CustomerModelQueryset

Fetches the CustomerModel associated with the EntityModel instance.

Parameters:

active (bool) – Active CustomerModel only. Defaults to True.

Returns:

The EntityModel instance CustomerModelQueryset with applied filters.

Return type:

CustomerModelQueryset

get_customers_url() str

The EntityModel customers list URL.

Returns:

EntityModel customers list URL as a string.

Return type:

str

get_dashboard_url() str

The EntityModel Dashboard URL.

Returns:

EntityModel dashboard URL as a string.

Return type:

str

get_data_import_url() str

The EntityModel transaction import URL.

Returns:

EntityModel transaction import URL as a string.

Return type:

str

get_default_account_for_role(role: str, coa_model: ChartOfAccountModel | None = None) AccountModel

Gets the given role default AccountModel from the provided CoA. CoA will be validated against the EntityModel instance.

Parameters:
  • role (str) – The CoA role to fetch the corresponding default Account Model.

  • coa_model (ChartOfAccountModel) – The CoA Model to pull default account from. If not provided, will use EntityModel default CoA.

Returns:

The default account model for the specified CoA role.

Return type:

AccountModel

get_default_coa(raise_exception: bool = True) ChartOfAccountModel | None

Fetches the EntityModel default Chart of Account.

Parameters:

raise_exception (bool) – Raises exception if no default CoA has been assigned.

Returns:

The EntityModel default ChartOfAccount.

Return type:

ChartOfAccountModel

get_default_coa_accounts(active: bool = True, order_by: Tuple[str] | None = ('code',), raise_exception: bool = True) AccountModelQuerySet | None

Fetches the default AccountModelQuerySet.

Parameters:
  • active (bool) – Selects only active accounts.

  • order_by (list of strings.) – Optional list of fields passed to the order_by QuerySet method.

  • raise_exception (bool) – Raises EntityModelValidationError if no default_coa found.

Returns:

The AccountModelQuerySet of the assigned default CoA.

Return type:

AccountModelQuerySet

get_delete_url() str

The EntityModel delete URL.

Returns:

EntityModel delete URL as a string.

Return type:

str

get_estimates()

Fetches a QuerySet of EstimateModels associated with the EntityModel instance.

Return type:

EstimateModelQuerySet

get_income_statement_url() str

The EntityModel Income Statement URL.

Returns:

EntityModel Income Statement URL as a string.

Return type:

str

get_invoices()

Fetches a QuerySet of InvoiceModels associated with the EntityModel instance.

Return type:

InvoiceModelQuerySet

get_invoices_url() str

The EntityModel invoice list URL.

Returns:

EntityModel invoice list URL as a string.

Return type:

str

get_items_all(active: bool = True) ItemModelQuerySet

Fetches all EntityModel instance ItemModel’s. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_items_expenses(active: bool = True) ItemModelQuerySet

Fetches all EntityModel instance ItemModel’s that qualify as Products. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_items_inventory(active: bool = True)

Fetches all EntityModel instance ItemModel’s that qualify as inventory. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_items_inventory_wip(active: bool = True)

Fetches all EntityModel instance ItemModel’s that qualify as work in progress inventory. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_items_products(active: bool = True) ItemModelQuerySet

Fetches all EntityModel instance ItemModel’s that qualify as Products. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_items_services(active: bool = True) ItemModelQuerySet

Fetches all EntityModel instance ItemModel’s that qualify as Services. QuerySet selects relevant related fields to avoid additional DB queries for most use cases.

Parameters:

active (bool) – Filters the QuerySet to active accounts only. Defaults to True.

Return type:

ItemModelQuerySet

get_ledgers_url() str

The EntityModel Ledger List URL.

Returns:

EntityModel ledger list URL as a string.

Return type:

str

get_manage_url() str

The EntityModel Manage URL.

Returns:

EntityModel manage URL as a string.

Return type:

str

get_purchase_orders()

Fetches a QuerySet of PurchaseOrderModels associated with the EntityModel instance.

Return type:

PurchaseOrderModelQuerySet

get_uom_all() UnitOfMeasureModelQuerySet

Fetches the EntityModel instance Unit of Measures QuerySet.

Return type:

UnitOfMeasureModelQuerySet

get_vendors(active: bool = True) VendorModelQuerySet

Fetches the VendorModels associated with the EntityModel instance.

Parameters:

active (bool) – Active VendorModels only. Defaults to True.

Returns:

The EntityModel instance VendorModelQuerySet with applied filters.

Return type:

VendorModelQuerySet

get_vendors_url() str

The EntityModel vendors list URL.

Returns:

EntityModel vendors list URL as a string.

Return type:

str

has_default_coa() bool

Determines if the EntityModel instance has a Default CoA.

Returns:

True if EntityModel instance has a Default CoA.

Return type:

bool

static inventory_adjustment(counted_qs, recorded_qs) defaultdict

Computes the necessary inventory adjustment to update balance sheet.

Parameters:
  • counted_qs (ItemTransactionModelQuerySet) – Inventory recount queryset from Purchase Order received inventory. See ItemTransactionModelManager.inventory_count. Expects ItemTransactionModelQuerySet to be formatted “as values”.

  • recorded_qs (ItemModelQuerySet) – Inventory received currently recorded for each inventory item. See ItemTransactionModelManager.inventory_count Expects ItemModelQuerySet to be formatted “as values”.

Returns:

A dictionary with necessary adjustments with keys as tuple:
  1. item_model_id

  2. item_model__name

  3. item_model__uom__name

Return type:

defaultdict

populate_default_coa(activate_accounts: bool = False, force: bool = False, ignore_if_default_coa: bool = True, coa_model: ChartOfAccountModel | None = None, commit: bool = True)

Populates the EntityModel default CoA with the default Chart of Account list provided by Django Ledger or user defined. See DJANGO_LEDGER_DEFAULT_COA setting.

Parameters:
  • activate_accounts (bool) – Activates all AccountModels for immediate use. Defaults to False.

  • force (bool) – Forces the creation of accounts even if other accounts are present. Defaults to False.

  • ignore_if_default_coa (bool) – Raises exception if EntityModel already has a default CoA. Defaults to True.

  • coa_model (ChartOfAccountModel) – Optional CoA Model to populate. Will be validated against EntityModel if provided.

  • commit (bool)

  • True. (' Commits the newly created CoA into the Database. Defaults to)

recorded_inventory(item_qs: ItemModelQuerySet | None = None, as_values: bool = True) ItemModelQuerySet

Recorded inventory on the books marked as received. PurchaseOrderModel drives the ordering and receiving of inventory. Once inventory is marked as “received” recorded inventory of each item is updated by calling update_inventory. This function returns relevant values of the recoded inventory, including Unit of Measures.

Parameters:
  • item_qs (ItemModelQuerySet) – Pre fetched ItemModelQuerySet. Avoids additional DB Query.

  • as_values (bool) – Returns a list of dictionaries by calling the Django values() QuerySet function.

Returns:

The ItemModelQuerySet containing inventory ItemModels with additional Unit of Measure information.

Return type:

ItemModelQuerySet

update_inventory(commit: bool = False) Tuple[defaultdict, ItemTransactionModelQuerySet, ItemModelQuerySet]

Triggers an inventory recount with optional commitment of transaction.

Parameters:

commit – Updates all inventory ItemModels with the new inventory count.

Returns:

Return a tuple as follows:
  1. All necessary inventory adjustments as a dictionary.

  2. The recounted inventory.

  3. The recorded inventory on Balance Sheet.

Return type:

Tuple[defaultdict, ItemTransactionModelQuerySet, ItemModelQuerySet]

validate_account_model_for_coa(account_model: AccountModel, coa_model: ChartOfAccountModel, raise_exception: bool = True) bool

Validates that the AccountModel provided belongs to the CoA Model provided.

Parameters:
  • account_model (AccountModel) – The AccountModel to validate.

  • coa_model (ChartOfAccountModel) – The ChartOfAccountModel to validate against.

  • raise_exception (bool) – Raises EntityModelValidationError if AccountModel is invalid for the EntityModel and CoA instance.

Returns:

True if valid, else False.

Return type:

bool

validate_chart_of_accounts_for_entity(coa_model: ChartOfAccountModel, raise_exception: bool = True) bool

Validates the CoA Model against the EntityModel instance.

Parameters:
  • coa_model (ChartOfAccountModel) – The CoA Model to validate.

  • raise_exception (bool) – Raises EntityModelValidationError if CoA Model is not valid for the EntityModel instance.

Returns:

True if valid, else False.

Return type:

bool

validate_item_qs(item_qs: ItemModelQuerySet, raise_exception: bool = True) bool

Validates the given ItemModelQuerySet against the EntityModel instance. :param item_qs: The ItemModelQuerySet to validate. :type item_qs: ItemModelQuerySet :param raise_exception: Raises EntityModelValidationError if ItemModelQuerySet is not valid. :type raise_exception: bool

Returns:

True if valid, else False.

Return type:

bool

class django_ledger.models.entity.EntityModelClosingEntryMixIn

Closing Entries provide

class django_ledger.models.entity.EntityModelFiscalPeriodMixIn

This class encapsulates the functionality needed to determine the start and end of all financial periods of an EntityModel. At the moment of creation, an EntityModel must be assigned a calendar month which is going to determine the start of the Fiscal Year.

get_fiscal_quarter_dates(year: int, quarter: int, fy_start_month: int = None) Tuple[date, date]

Convenience method to get in one shot both, fiscal year quarter start and end dates.

Parameters:
  • year (int) – The fiscal year associated with the requested start and end date.

  • quarter (int) – The quarter number associated with the requested start and end date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

Both, the date when the requested EntityModel fiscal year quarter start and end date as a tuple. The start date will be first.

Return type:

tuple

get_fiscal_year_dates(year: int, fy_start_month: int = None) Tuple[date, date]

Convenience method to get in one shot both, fiscal year start and end dates.

Parameters:
  • year (int) – The fiscal year associated with the requested start and end date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

Both, the date when the requested EntityModel fiscal year start and end date as a tuple. The start date will be first.

Return type:

tuple

get_fy_end(year: int, fy_start_month: int = None) date

The fiscal year ending date of the EntityModel, according to its settings.

Parameters:
  • year (int) – The fiscal year associated with the requested end date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

The date when the requested EntityModel fiscal year ends.

Return type:

date

get_fy_for_date(dt: date | datetime, as_str: bool = False) str | int

Given a known date, returns the EntityModel fiscal year associated with the given date.

Parameters:
  • dt (date) – Date to evaluate.

  • as_str (bool) – If True, return date as a string.

Returns:

Fiscal year as an integer or string, depending on as_str parameter.

Return type:

str or date

get_fy_start(year: int, fy_start_month: int | None = None) date

The fiscal year start date of the EntityModel, according to its settings.

Parameters:
  • year (int) – The fiscal year associated with the requested start date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

The date when the requested EntityModel fiscal year starts.

Return type:

date

get_fy_start_month() int

The fiscal year start month represents the month (as an integer) when the assigned fiscal year of the EntityModel starts.

Returns:

An integer representing the month that the fiscal year starts.

Return type:

int

Examples

  • 1 -> January.

  • 4 -> April.

  • 9 -> September.

get_quarter_end(year: int, quarter: int, fy_start_month: int = None) date

The fiscal year quarter ending date of the EntityModel, according to its settings.

Parameters:
  • year (int) – The fiscal year associated with the requested end date.

  • quarter (int) – The quarter number associated with the requested end date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

The date when the requested EntityModel quarter ends.

Return type:

date

get_quarter_start(year: int, quarter: int, fy_start_month: int = None) date

The fiscal year quarter starting date of the EntityModel, according to its settings.

Parameters:
  • year (int) – The fiscal year associated with the requested start date.

  • quarter (int) – The quarter number associated with the requested start date.

  • fy_start_month (int) – Optional fiscal year month start. If passed, it will override the EntityModel setting.

Returns:

The date when the requested EntityModel quarter starts.

Return type:

date

validate_month(month: int)

Validates the month as a valid parameter for other functions. Makes sure that only integers between 1 and 12 are used to refer to a particular month. Prevents injection of invalid values from views into the IOMixIn.

Parameters:

month (int) – The month number to validate.

Raises:

ValidationError – If month is not valid.

validate_quarter(quarter: int)

Validates the quarter as a valid parameter for other functions. Makes sure that only integers 1,2,3, or 4 are used to refer to a particular Quarter. Prevents injection of invalid values from views into the IOMixIn.

Parameters:

quarter (int) – The quarter number to validate.

Raises:

ValidationError – If quarter is not valid.

class django_ledger.models.entity.EntityModelManager(*args, **kwargs)

A custom defined EntityModel Manager. This ModelManager uses the custom defined EntityModelQuerySet as default. Inherits from the Materialized Path Node Manager to include the necessary methods to manage tree-like models. This Model Manager keeps track and maintains a root/parent/child relationship between Entities for the purposes of producing consolidated financial statements.

Examples

>>> user = request.user
>>> entity_model_qs = EntityModel.objects.for_user(user_model=user)
for_user(user_model, authorized_superuser: bool = False)

This QuerySet guarantees that Users do not access or operate on EntityModels that don’t have access to. This is the recommended initial QuerySet.

Parameters:
  • user_model – The Django User Model making the request.

  • authorized_superuser – Allows any superuser to access the EntityModel. Default is False.

Returns:

A filtered QuerySet of EntityModels that the user has access. The user has access to an Entity if:
  1. Is the Administrator.

  2. Is a manager.

Return type:

EntityModelQuerySet

get_queryset()

Sets the custom queryset as the default.

class django_ledger.models.entity.EntityModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined EntityModel QuerySet. Inherits from the Materialized Path Node QuerySet Class from Django Treebeard.

hidden()

A QuerySet of all hidden EntityModel.

Returns:

A filtered QuerySet of hidden EntityModels only.

Return type:

EntityModelQuerySet

visible()

A Queryset of all visible EntityModel.

Returns:

A filtered QuerySet of visible EntityModels only.

Return type:

EntityModelQuerySet

exception django_ledger.models.entity.EntityModelValidationError(message, code=None, params=None)
class django_ledger.models.entity.EntityStateModel(*args, **kwargs)

Entity State Model Base Class from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.entity.EntityStateModelAbstract(*args, **kwargs)

Entity Unit Model

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

An EntityUnit is a logical, user-defined grouping assigned to JournalEntryModels, helping to segregate business operations into distinct components. Examples of EntityUnits may include departments (e.g., Human Resources, IT), office locations, real estate properties, or any other labels relevant to the business.

EntityUnits are self-contained entities, meaning that double-entry accounting rules apply to all transactions associated with them. When an Invoice or Bill is updated, the migration process generates the corresponding Journal Entries for each relevant unit. This allows invoices or bills to split specific items into different units, with the migration process allocating costs to each unit accordingly.

Key advantages of EntityUnits:
  1. EntityUnits can generate their own financial statements, providing deeper insights into the specific operations of the business.

  2. EntityUnits can be assigned to specific items on Bills and Invoices, offering flexibility to track inventory, expenses, or income associated with distinct business units.

class django_ledger.models.unit.EntityUnitModel(*args, **kwargs)

Base Model Class for EntityUnitModel

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.unit.EntityUnitModelAbstract(*args, **kwargs)

Base implementation of the EntityUnitModel.

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

slug

A unique, indexed identifier for the EntityUnitModel instance used in URLs and queries.

Type:

str

entity

The EntityModel associated with this EntityUnitModel.

Type:

EntityModel

document_prefix

A predefined prefix automatically incorporated into JournalEntryModel document numbers. Max Length 3. May be user defined. Must be unique for the EntityModel.

Type:

str

active

Active EntityUnits may transact. Inactive units are considered archived. Defaults to True.

Type:

bool

hidden

Hidden Units will not show on drop down menus on the UI. Defaults to False.

Type:

bool

class Meta
clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

create_entity_unit_slug(name: str | None = None, force: bool = False, add_suffix: bool = True, k: int = 5) str

Automatically generates a EntityUnitModel slug. If slug is present, will not be replaced. Called during the clean() method.

Parameters:
  • force (bool) – Forces generation of new slug if already present.

  • name (str) – The name used to create slug. If none, the unit name will be used.

  • add_suffix (bool) – Adds a random suffix to the slug. Defaults to True.

  • k (int) – Length of the suffix if add_suffix is True. Defaults to 5.

Returns:

The EntityUnitModel slug, regardless if generated or not.

Return type:

str

get_dashboard_url() str

The dashboard URL of the EntityModelUnit.

Returns:

The EntityModelUnit instance dashboard URL.

Return type:

str

class django_ledger.models.unit.EntityUnitModelManager(*args, **kwargs)
for_entity(entity_slug: str, user_model)

Fetches a QuerySet of EntityUnitModels associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Returns:

Returns a EntityUnitModelQuerySet with applied filters.

Return type:

EntityUnitModelQuerySet

get_queryset()

Sets the custom queryset as the default.

class django_ledger.models.unit.EntityUnitModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined EntityUnitModel Queryset.

exception django_ledger.models.unit.EntityUnitModelValidationError(message, code=None, params=None)

Account Model

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

AccountModel

The AccountModel is a fundamental component of the Django Ledger system, responsible for categorizing and organizing financial transactions related to an entity’s assets, liabilities, and equity.

Account Types

In accordance with accounting principles, each AccountModel must be classified as either:

  1. DEBIT-type balance account

  2. CREDIT-type balance account

The account type determines how transactions affect the account’s balance.

Double Entry Accounting

The AccountModel is crucial in implementing double entry accounting systems:

  • For DEBIT-type accounts: - A DEBIT increases the balance - A CREDIT decreases the balance

  • For CREDIT-type accounts: - A CREDIT increases the balance - A DEBIT decreases the balance

Chart of Accounts

Users have the flexibility to adopt a chart of accounts that best suits their EntityModel. Django Ledger provides a default Chart of Accounts when creating a new EntityModel, which can be customized as needed.

Account Roles

All AccountModels must be assigned a role from the ACCOUNT_ROLES function in django_ledger.io.roles. Roles serve several purposes:

  1. Group accounts into common namespaces

  2. Provide consistency across user-defined fields

  3. Enable accurate generation of financial statements

  4. Facilitate financial ratio calculations

class django_ledger.models.accounts.AccountModel(*args, **kwargs)

Base Account Model from Account Model Abstract Class

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.accounts.AccountModelAbstract(*args, **kwargs)

Abstract class representing an Account Model.

BALANCE_TYPE

List of choices for the balance type of the account. Options include ‘Credit’ and ‘Debit’.

Type:

list

uuid

Unique identifier for each account instance.

Type:

UUIDField

code

Code representing the account, constrained by length and specific validation rules.

Type:

CharField

name

Name of the account, constrained by length.

Type:

CharField

role

Role associated with the account, with specific predefined choices.

Type:

CharField

role_default

Flag indicating if this account is the default for its role.

Type:

BooleanField

balance_type

Type of balance the account holds, must be either ‘debit’ or ‘credit’.

Type:

CharField

locked

Indicates whether the account is locked.

Type:

BooleanField

active

Indicates whether the account is active.

Type:

BooleanField

coa_model

Reference to the associated ChartOfAccountModel.

Type:

ForeignKey

class Meta
activate(commit: bool = True, raise_exception: bool = True, **kwargs)

Checks if the Account Model instance can be activated, then Activates the AccountModel instance. Raises exception if AccountModel cannot be activated.

Parameters:
  • commit (bool, optional) – If True, commit the changes to the database by calling the save method.

  • raise_exception (bool, optional) – If True, raises an AccountModelValidationError if the account cannot be activated.

  • kwargs (dict) – Additional parameters that can be passed for further customization.

can_activate()

Determines if the object can be activated.

Returns:

True if the object is inactive, otherwise False.

Return type:

bool

can_deactivate()

Determine if the object can be deactivated.

Checks if the active attribute is set to True.

Returns:

True if the object is currently active and can be deactivated, otherwise False.

Return type:

bool

can_transact() bool

Determines if a transaction can be performed based on multiple conditions.

Returns:

  • bool – True if all conditions are met, enabling a transaction; False otherwise.

  • Conditions

  • 1. The chart of accounts (coa_model) must be active.

  • 2. The entity must not be locked.

  • 3. The entity itself must be active.

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

classmethod create_account(name: str, role: bool, balance_type: str, is_role_default: bool = False, locked: bool = False, active: bool = False, **kwargs)

Create a new AccountModel instance, managing parent/child relationships properly.

This convenience method ensures correct creation of new accounts, handling the intricate logic needed for maintaining hierarchical relationships between accounts.

Parameters:
  • name (str) – Name of the new account entity.

  • role (str) – Role assigned to the account.

  • balance_type (str) – Type of balance associated with the account. Must be either ‘debit’ or ‘credit’.

  • is_role_default (bool, optional) – Indicates if the account should be the default for its role. Only one default account per role is allowed. Defaults to False.

  • locked (bool, optional) – Flags the account as locked. Defaults to False.

  • active (bool, optional) – Flags the account as active. Defaults to True.

  • **kwargs (dict, optional) – Additional attributes for account creation.

Returns:

The newly created AccountModel instance.

Return type:

AccountModel

deactivate(commit: bool = True, raise_exception: bool = True, **kwargs)

Checks if the Account Model instance can be de-activated, then De-activates the AccountModel instance. Raises exception if AccountModel cannot be de-activated.

Parameters:
  • commit (bool, optional) – If True, commit the changes to the database by calling the save method.

  • raise_exception (bool, optional) – If True, raises an AccountModelValidationError if the account cannot be activated.

  • kwargs (dict) – Additional parameters that can be passed for further customization.

generate_random_code()

Generates a random code for the account adding a prefix 1-6 depending on account role.

Raises:

AccountModelValidationError – If the account role is not assigned before code generation.

Returns:

A randomly generated code prefixed with a role-based prefix.

Return type:

str

get_account_move_choice_queryset()

Retrieves a filtered queryset of account models that the current Account Model instance can be a child of.

The queryset is filtered based on the specified role and its hierarchical parent roles. Account models with a UUID matching the current instance’s UUID are excluded from the results.

Returns:

A filtered set of account models suitable for moving the current instance under.

Return type:

QuerySet

get_code_prefix() str

Returns the code prefix based on the account type.

This method determines the account type by calling the respective account type methods and returns the corresponding code prefix based on Accounting best practices..

Returns:

The code prefix for the account type. The possible values are: ‘1’ for assets, ‘2’ for liabilities, ‘3’ for capital, ‘4’ for income, ‘5’ for cost of goods sold (COGS), ‘6’ for expenses.

Return type:

str

Raises:

AccountModelValidationError – If the account role does not match any of the predefined categories.

get_html_pixel_indent()

Calculates the pixel indentation for HTML elements based on the depth attribute for UI purposes

Returns:

The calculated pixel indentation as a string with ‘px’ suffix.

Return type:

str

get_root_role() str

Returns the root role corresponding to the account type.

Returns:

The root role corresponding to the account type.

Return type:

str

Raises:

AccountModelValidationError – If no valid role match is found for the account’s role.

is_active() bool

Determines if the current instance is active.

Returns:

True if the instance is active, otherwise False

Return type:

bool

is_asset() bool

Determines if the current Account Model role of the instance is considered an asset.

Returns:

True if the role is part of the GROUP_ASSETS, False otherwise.

Return type:

bool

is_capital() bool

Checks if the current Account Model role is in the capital group.

Returns:

True if the role is in GROUP_CAPITAL, otherwise False.

Return type:

bool

is_coa_root()

Check if the current Account Model role is ‘ROOT_COA’.

Returns:

True if the role is ‘ROOT_COA’, False otherwise.

Return type:

bool

is_cogs() bool

Determines if the role of the object is part of the GROUP_COGS.

Returns:

True if the object’s role is part of the GROUP_COGS, False otherwise.

Return type:

bool

is_credit()

Checks if the Account Model has a CREDIT balance type.

Returns:

True if account has a CREDIT balance, else False.

Return type:

bool

is_debit() bool

Checks if the account has a DEBIT balance type.

Returns:

True if account has a DEBIT balance, else False.

Return type:

bool

is_expense() bool

Checks if the current Account Model role is categorized under GROUP_EXPENSES.

Parameters:

None

Returns:

True if role is in GROUP_EXPENSES, otherwise False.

Return type:

bool

is_income() bool

Determines whether the current Account Model role belongs to the income group.

Parameters:

self (object) – The instance of the class containing attribute ‘role’.

Returns:

True if the role is in the GROUP_INCOME list, False otherwise.

Return type:

bool

is_indented()

Check if the current depth level is greater than 2.

Returns:

True if the depth is greater than 2, False otherwise.

Return type:

bool

is_liability() bool

Determines if the current Account Model role is considered a liability.

Returns:

True if the role is part of GROUP_LIABILITIES, otherwise False.

Return type:

bool

is_locked() bool

Determines if the current object is locked.

Returns:

True if the object is locked, False otherwise.

Return type:

bool

is_root_account()

Checks if the current user’s role belongs to the ROOT_GROUP.

Returns:

True if the role is in the ROOT_GROUP, False otherwise

Return type:

bool

property role_bs: str

Returns the principal role of the account on the balance sheet.

The principal role can be one of the following: - ‘asset’ - ‘liability’ - ‘equity’

Returns:

A string representing the principal role of the account on the balance sheet.

Return type:

str

class django_ledger.models.accounts.AccountModelManager(*args, **kwargs)

AccountModelManager class provides methods to manage and retrieve AccountModel objects. It inherits from MP_NodeManager for tree-like model implementation.

for_entity(user_model, entity_model, coa_slug: str | None = None) AccountModelQuerySet

Retrieve accounts associated with a specified EntityModel and Chart of Accounts.

Parameters:
  • user_model (User) – The Django User instance initiating the request. Used to check for required permissions.

  • entity_model (Union[EntityModel, str]) – An instance of EntityModel or its slug. This determines the entity whose accounts are being retrieved. A database query will be carried out to identify the default Chart of Accounts.

  • coa_slug (Optional[str], default=None) – The slug for a specific Chart of Accounts to be used. If None, the default Chart of Accounts will be selected.

Returns:

A QuerySet containing accounts associated with the specified EntityModel and Chart of Accounts.

Return type:

AccountModelQuerySet

Raises:

AccountModelValidationError – If the entity_model is neither an instance of EntityModel nor a string.

for_user(user_model) AccountModelQuerySet
Parameters:

user_model (UserModel) – The user model instance to use for filtering.

Returns:

The filtered queryset based on the user’s permissions. Superusers get the complete queryset whereas other users get a filtered queryset based on their role as admin or manager in the entity.

Return type:

AccountModelQuerySet

get_queryset() AccountModelQuerySet

Retrieve and return athe default AccountModel QuerySet.

The query set is ordered by the ‘path’ field and uses ‘select_related’ to reduce the number of database queries by retrieving the related ‘coa_model’.

Returns:

An instance of AccountModelQuerySet ordered by ‘path’ and prefetching related ‘coa_model’.

Return type:

AccountModelQuerySet

class django_ledger.models.accounts.AccountModelQuerySet(model=None, query=None, using=None, hints=None)

Custom QuerySet for AccountModel inheriting from MP_NodeQuerySet.

active()

Filters the queryset to include only active items.

Returns:

A filtered queryset containing only the items marked as active.

Return type:

AccountModelQuerySet

can_transact()

Filter the queryset to include only accounts that can accept new transactions.

Returns:

A QuerySet containing the filtered results.

Return type:

QuerySet

expenses()

Retrieve a queryset containing expenses filtered by specified roles.

This method filters the expenses based on roles defined in the GROUP_EXPENSES constant. It ensures that only the relevant expenses associated with the specified roles are included in the queryset.

Returns:

A queryset consisting of expenses filtered according to the roles in GROUP_EXPENSES.

Return type:

AccountModelQuerySet

for_bill()

Retrieves only available and unlocked AccountModels for a specific EntityModel, specifically for the creation and management of Bills. Roles within the ‘GROUP_BILL’ context include: ASSET_CA_CASH, ASSET_CA_PREPAID, and LIABILITY_CL_ACC_PAYABLE.

Returns:

A QuerySet of the requested EntityModel’s chart of accounts.

Return type:

AccountModelQuerySet

for_invoice()

Retrieves available and unlocked AccountModels for a specific EntityModel, specifically for the creation and management of Invoices.

This method ensures that only relevant accounts are pulled, as defined under the roles in GROUP_INVOICE. These roles include: ASSET_CA_CASH, ASSET_CA_RECEIVABLES, and LIABILITY_CL_DEFERRED_REVENUE.

Returns:

A QuerySet containing the AccountModels relevant for the specified EntityModel and the roles defined in GROUP_INVOICE.

Return type:

AccountModelQuerySet

gb_bs_role()

Groups accounts by Balance Sheet Bucket and then further groups them by role.

Returns:

A list where each element is a tuple. The first element of the tuple is the BS bucket, and the second element is a list of tuples where each sub-tuple contains a role display and a list of accounts that fall into that role within the BS bucket.

Return type:

List[Tuple]

inactive()

Filters and returns queryset entries where the active field is set to False.

Returns:

A queryset containing entries with active=False.

Return type:

AccountModelQuerySet

is_coa_root()

Retrieves the Chart of Accounts (CoA) root node queryset.

A Chart of Accounts Root is a foundational element indicating the primary node in the account hierarchy. This method filters the queryset to include only the Chart of Accounts (CoA) root node.

Return type:

AccountModelQuerySet

is_role_default()

Filter the queryset to include only entries where role_default is set to True, excluding entries marked as ‘coa_root’.

Returns:

Filtered queryset with role_default set to True and excluding ‘coa_root’ entries.

Return type:

AccountModelQuerySet

locked()

Filters the queryset to include only locked AccountModels.

Returns:

A queryset containing only the objects with locked set to True.

Return type:

AccountModelQuerySet

not_coa_root()

Exclude AccountModels with ROOT_GROUP role from the QuerySet.

Returns:

A QuerySet excluding users with role in ROOT_GROUP.

Return type:

AccountModelQuerySet

unlocked()

Returns a filtered list of items where the ‘locked’ attribute is set to False.

Returns:

A queryset of items with ‘locked’ attribute set to False

Return type:

AccountModelQuerySet

with_roles(roles: List | str)

Filter the accounts based on the specified roles. This method helps to retrieve accounts associated with a particular role or a list of roles.

For example, to get all accounts categorized under the role “asset_ppe_build” (which might include fixed assets like Buildings), you can utilize this method.

Parameters:

roles (Union[List[str], str]) – The role or a list of roles to filter the accounts by. If a single string is provided, it is converted into a list containing that role.

Returns:

A QuerySet of accounts filtered by the provided roles.

Return type:

AccountModelQuerySet

exception django_ledger.models.accounts.AccountModelValidationError(message, code=None, params=None)
django_ledger.models.accounts.CREDIT = 'credit'

A constant, identifying a CREDIT Account or CREDIT transaction in the respective database fields

django_ledger.models.accounts.DEBIT = 'debit'

A constant, identifying a DEBIT Account or DEBIT transaction in the respective database fields

Ledger Model

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

The LedgerModel is the heart of Django Ledger. It is a self-contained unit of accounting that implements a double-entry accounting system capable of creating and managing transactions into the ledger and producing any financial statements. In essence, an EntityModel is made of a collection of LedgerModels that drive the whole bookkeeping process. Each LedgerModel is independent and they can operate as an individual or as a group.

Each LedgerModel encapsulates a collection of JournalEntryModels, which in turn hold a collection of TransactionModels. LedgerModels can be used to represent any part of the EntityModel and can be extended to add additional functionality and custom logic that drives how transactions are recorded into the books. One example of this is the LedgerWrapperMixIn (see django_ledger.models.mixins.LedgerWrapperMixIn), which is the foundation of LedgerModel abstractions such as the BillModel, InvoiceModel, PurchaseOrderModel and EstimateModel. Extending the LedgerModel can add additional functionality necessary to implement industry-specific functionality to almost anything you can think of. Examples: Farming Equipment, Real Estate, Investment Portfolio, etc.

Also, the LedgerModel inherits functionality from the all mighty IOMixIn (see django_ledger.io.io_mixin.IOMixIn), which is the class responsible for making accounting queries to the Database in an efficient and performing way. The digest() method executes all necessary aggregations and optimizations in order to push as much work to the Database layer as possible in order to minimize the amount of data being pulled for analysis into the Python memory.

The Django Ledger core model follows the following structure: EntityModel -< LedgerModel -< JournalEntryModel -< TransactionModel

class django_ledger.models.ledger.LedgerModel(*args, **kwargs)

Base LedgerModel from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.ledger.LedgerModelAbstract(*args, **kwargs)

Base implementation of the LedgerModel.

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

name

Human-readable name of the LedgerModel. Maximum 150 characters.

Type:

str

ledger_xid

A unique user-defined identifier for the LedgerModel. Unique for the Entity Model.

Type:

str

entity

The EntityModel associated with the LedgerModel instance.

Type:

EntityModel

posted

Determines if the LedgerModel is posted. Defaults to False. Mandatory.

Type:

bool

locked

Determines if the LedgerModel is locked. Defaults to False. Mandatory.

Type:

bool

hidden

Determines if the LedgerModel is hidden. Defaults to False. Mandatory.

Type:

bool

can_hide() bool

Determines if the LedgerModel can be hidden.

Returns:

True if can be hidden, else False.

Return type:

bool

can_lock() bool

Determines if the LedgerModel can be locked.

Returns:

True if can be locked, else False.

Return type:

bool

can_post() bool

Determines if the LedgerModel can be marked as posted.

Returns:

True if can be posted, else False.

Return type:

bool

can_unhide() bool

Determines if the LedgerModel can be un-hidden.

Returns:

True if can be un-hidden, else False.

Return type:

bool

can_unlock() bool

Determines if the LedgerModel can be un-locked.

Returns:

True if can be un-locked, else False.

Return type:

bool

can_unpost() bool

Determines if the LedgerModel can be un-posted.

Returns:

True if can be un-posted, else False.

Return type:

bool

get_absolute_url() str

Determines the absolute URL of the LedgerModel instance. Results in additional Database query if entity field is not selected in QuerySet.

Returns:

URL as a string.

Return type:

str

get_create_url() str

Determines the update URL of the LedgerModel instance. Results in additional Database query if entity field is not selected in QuerySet.

Returns:

URL as a string.

Return type:

str

get_list_url() str

Determines the list URL of the LedgerModel instances. Results in additional Database query if entity field is not selected in QuerySet.

Returns:

URL as a string.

Return type:

str

get_update_url() str

Determines the update URL of the LedgerModel instance. Results in additional Database query if entity field is not selected in QuerySet.

Returns:

URL as a string.

Return type:

str

is_hidden() bool

Determines if the LedgerModel instance is hidden.

Returns:

True if hidden, else False.

Return type:

bool

is_locked() bool

Determines if the LedgerModel instance is locked.

Returns:

True if locked, else False.

Return type:

bool

is_posted() bool

Determines if the LedgerModel instance is posted.

Returns:

True if posted, else False.

Return type:

bool

lock(commit: bool = False, raise_exception: bool = True, **kwargs)

Locks the LedgerModel.

Parameters:
  • commit (bool) – If True, saves the LedgerModel instance instantly. Defaults to False.

  • raise_exception (bool) – Raises LedgerModelValidationError if locking not allowed.

post(commit: bool = False, raise_exception: bool = True, **kwargs)

Posts the LedgerModel.

Parameters:
  • commit (bool) – If True, saves the LedgerModel instance instantly. Defaults to False.

  • raise_exception (bool) – Raises LedgerModelValidationError if posting not allowed.

unlock(commit: bool = False, raise_exception: bool = True, **kwargs)

Un-locks the LedgerModel.

Parameters:

commit (bool) – If True, saves the LedgerModel instance instantly. Defaults to False.

unpost(commit: bool = False, raise_exception: bool = True, **kwargs)

Un-posts the LedgerModel.

Parameters:
  • commit (bool) – If True, saves the LedgerModel instance instantly. Defaults to False.

  • raise_exception (bool) – Raises LedgerModelValidationError if un-posting not allowed.

class django_ledger.models.ledger.LedgerModelManager(*args, **kwargs)

A custom-defined LedgerModelManager that implements custom QuerySet methods related to the LedgerModel.

for_entity(entity_slug, user_model)

Returns a QuerySet of LedgerModels associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered LedgerModelQuerySet.

Return type:

LedgerModelQuerySet

get_queryset()

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class django_ledger.models.ledger.LedgerModelQuerySet(model=None, query=None, using=None, hints=None)

Custom defined LedgerModel QuerySet.

locked()

Filters the QuerySet to only locked LedgerModel.

Returns:

A QuerySet with applied filters.

Return type:

LedgerModelQuerySet

posted()

Filters the QuerySet to only posted LedgerModel.

Returns:

A QuerySet with applied filters.

Return type:

LedgerModelQuerySet

unlocked()

Filters the QuerySet to only un-locked LedgerModel.

Returns:

A QuerySet with applied filters.

Return type:

LedgerModelQuerySet

unposted()

Filters the QuerySet to only un-posted LedgerModel.

Returns:

A QuerySet with applied filters.

Return type:

LedgerModelQuerySet

exception django_ledger.models.ledger.LedgerModelValidationError(message, code=None, params=None)

Transaction Model

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

The TransactionModel serves as the foundational accounting entity where all financial transactions are recorded. Every transaction must be associated with a JournalEntryModel, which represents a collection of related transactions. This strict association ensures that standalone TransactionModels—or orphan transactions—do not exist, a constraint enforced at the database level.

Each transaction performs either a CREDIT or a DEBIT operation on the designated AccountModel, upholding standard accounting principles. The TransactionModel API integrates the IOMixIn, a critical component for generating financial statements. This mixin facilitates efficient querying and aggregation directly at the database level, eliminating the need to load all TransactionModels into memory. This database-driven approach significantly improves performance and simplifies the process of generating accurate financial reports.

The TransactionModel, together with the IOMixIn, is essential for ensuring seamless, efficient, and reliable financial statement production in the Django Ledger framework.

class django_ledger.models.transactions.TransactionModel(*args, **kwargs)

Base Transaction Model From Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.transactions.TransactionModelAbstract(*args, **kwargs)

Abstract model for representing a financial transaction in the ledger system.

This model defines the core structure and behavior that every transaction record is expected to have, including fields like transaction type, associated account, amount, and additional metadata used for validation and functionality.

Attributes:

Constants: - CREDIT: Constant representing a credit transaction. - DEBIT: Constant representing a debit transaction. - TX_TYPE: A list of choices providing options for transaction types, including CREDIT and DEBIT.

Fields: - uuid (UUIDField): The unique identifier for the transaction. Automatically generated, non-editable, and primary key. - tx_type (CharField): Specifies the transaction type (CREDIT or DEBIT). Choices are based on the TX_TYPE constant. Maximum length is 10 characters. - journal_entry (ForeignKey): References the related journal entry from the django_ledger.JournalEntryModel.

This field is not editable and is essential for linking transactions to journal entries.

  • account (ForeignKey): References the associated account from django_ledger.AccountModel. Protected from being deleted.

  • amount (DecimalField): Represents the transaction amount, up to 20 digits and 2 decimal places. The default value is 0.00, and it enforces a minimum value of 0.

  • description (CharField): Optional field for a brief description of the transaction. The maximum length is 100 characters.

  • cleared (BooleanField): Indicates whether the transaction has been cleared. Defaults to False.

  • reconciled (BooleanField): Indicates whether the transaction has been reconciled. Defaults to False.

  • objects (TransactionModelManager): Custom model manager providing advanced helper methods for querying and filtering transactions.

property coa_id

Fetch the Chart of Accounts (CoA) ID associated with the transaction’s account. Returns None if the account is not set.

class django_ledger.models.transactions.TransactionModelManager(*args, **kwargs)

A custom manager for TransactionModel designed to add helper methods for querying and filtering TransactionModel objects efficiently based on use cases like user permissions, associated entities, ledgers, journal entries, and more.

This manager leverages TransactionModelQuerySet for complex query construction and integrates advanced filtering options based on user roles, entities, and other relationships.

for_entity(entity_slug: EntityModel | str | UUID, user_model: User | None = None) TransactionModelQuerySet

Filters transactions for a specific entity, optionally scoped to a specific user.

Parameters:
  • entity_slug (Union[EntityModel, str, UUID]) – Identifier for the entity. This can be an EntityModel object, a slug (str), or a UUID.

  • user_model (Optional[UserModel], optional) – The user for whom transactions should be filtered. If provided, applies user-specific filtering. Defaults to None.

Returns:

A queryset containing transactions associated with the specified entity.

Return type:

TransactionModelQuerySet

Notes

  • If user_model is provided, only transactions accessible by the user are included.

  • Supports flexible filtering by accepting different forms of entity_slug.

for_user(user_model) TransactionModelQuerySet

Filters transactions accessible to a specific user based on their permissions.

Parameters:

user_model (UserModel) – The user object for which the transactions should be filtered.

Returns:

  • TransactionModelQuerySet – A queryset containing transactions filtered by the user’s access level.

  • Description

  • ———–

    • Returns all TransactionModel objects for superusers.

  • - For regular users, it filters transactions where

    • The user is an admin of the entity associated with the ledger in the transaction.

    • The user is a manager of the entity associated with the ledger in the transaction.

get_queryset() TransactionModelQuerySet

Retrieves the base queryset for TransactionModel, annotated and pre-loaded with commonly used related fields.

Returns:

A custom queryset with essential annotations and relationships preloaded.

Return type:

TransactionModelQuerySet

class django_ledger.models.transactions.TransactionModelQuerySet(model=None, query=None, using=None, hints=None)

A custom QuerySet class tailored for TransactionModel objects. It includes a collection of methods to efficiently and safely retrieve and filter transactions from the database based on common use cases.

for_accounts(account_list: List[str])

Filters transactions based on the accounts they are associated with.

Parameters:

account_list (list of str or AccountModel) – A list containing account codes (strings) or AccountModel instances. Transactions will be filtered to match these accounts.

Returns:

A QuerySet filtered for transactions associated with the specified accounts.

Return type:

TransactionModelQuerySet

for_activity(activity_list: str | List[str] | Set[str])

Filters transactions based on their associated activity or activities.

Parameters:

activity_list (str or list of str) – A single activity or a list of activities to filter transactions by.

Returns:

A QuerySet filtered for transactions linked to the specified activity or activities.

Return type:

TransactionModelQuerySet

for_bill(bill_model: BillModel | str | UUID)

Filters transactions for a specific bill under a given entity.

Parameters:

bill_model (Union[BillModel, str, UUID]) – The bill model or its UUID to filter by.

Returns:

A queryset containing transactions related to the specified bill.

Return type:

TransactionModelQuerySet

for_invoice(invoice_model: InvoiceModel | str | UUID)

Filters transactions for a specific invoice under a given entity.

Parameters:

invoice_model (Union[InvoiceModel, str, UUID]) – The invoice model or its UUID to filter by.

Returns:

A queryset containing transactions related to the specified invoice.

Return type:

TransactionModelQuerySet

for_journal_entry(je_model)

Filters transactions for a specific journal entry under a given ledger and entity.

Parameters:

je_model (Union[JournalEntryModel, UUID]) – The journal entry model or its UUID to filter by.

Returns:

A queryset containing transactions associated with the given journal entry.

Return type:

TransactionModelQuerySet

for_ledger(ledger_model: LedgerModel | UUID | str)

Filters transactions for a specific ledger under a given entity.

Parameters:

ledger_model (Union[LedgerModel, UUID]) – The ledger model or its UUID to filter by.

Returns:

A queryset containing transactions associated with the given ledger and entity.

Return type:

TransactionModelQuerySet

for_roles(role_list: str | List[str] | Set[str])

Fetches a QuerySet of TransactionModels which AccountModel has a specific role.

Parameters:

role_list (str or list) – A string or list of strings representing the roles to be used as filter.

Returns:

Returns a TransactionModelQuerySet with applied filters.

Return type:

TransactionModelQuerySet

for_unit(unit_slug: str | EntityUnitModel)

Filters transactions based on their associated entity unit.

Parameters:

unit_slug (str or EntityUnitModel) – A string representing the slug of the entity unit or an EntityUnitModel instance.

Returns:

A QuerySet filtered for transactions linked to the specified unit.

Return type:

TransactionModelQuerySet

from_date(from_date: str | date | datetime)

Filters transactions occurring on or after a specific date or timestamp.

If from_date is a naive datetime (no timezone), it is assumed to be in local time based on Django settings.

Parameters:

from_date (str, date, or datetime) – The minimum date or timestamp for filtering. When using a date (not datetime), the filter is inclusive (e.g., “2022-12-20” includes all transactions from that day).

Returns:

A QuerySet filtered to include transactions from the specified date or timestamp onwards.

Return type:

TransactionModelQuerySet

is_closing_entry()

Filters transactions that are part of a closing journal entry.

Returns:

A QuerySet with transactions where the journal_entry__is_closing_entry field is True.

Return type:

TransactionModelQuerySet

not_closing_entry()

Filters transactions that are not part of a closing journal entry.

Returns:

A QuerySet with transactions where the journal_entry__is_closing_entry field is False.

Return type:

TransactionModelQuerySet

posted() QuerySet

Retrieves transactions that are part of a posted journal entry and ledger.

A transaction is considered “posted” if: - It belongs to a journal entry marked as posted. - Its associated journal entry is part of a ledger marked as posted.

Returns:

A QuerySet containing only transactions that meet the “posted” criteria.

Return type:

TransactionModelQuerySet

to_date(to_date: str | date | datetime)

Filters transactions occurring on or before a specific date or timestamp.

If to_date is a naive datetime (no timezone), it is assumed to be in local time based on Django settings.

Parameters:

to_date (str, date, or datetime) – The maximum date or timestamp for filtering. When using a date (not datetime), the filter is inclusive (e.g., “2022-12-20” includes all transactions from that day).

Returns:

A QuerySet filtered to include transactions up to the specified date or timestamp.

Return type:

TransactionModelQuerySet

exception django_ledger.models.transactions.TransactionModelValidationError(message, code=None, params=None)
django_ledger.models.transactions.transactionmodel_presave(instance: TransactionModel, **kwargs)

Pre-save validation for the TransactionModel instance.

This function is executed before saving a TransactionModel instance, ensuring that certain conditions are met to maintain data integrity.

Parameters:
  • instance (TransactionModel) – The TransactionModel instance that is about to be saved.

  • kwargs (dict) – Additional keyword arguments, such as the optional bypass_account_state.

  • Validations

  • -----------

  • validations (The function performs the following)

  • Transactionality (1. Account) – If the bypass_account_state flag is not provided or set to False, it verifies whether the associated account can process transactions by calling instance.account.can_transact(). If the account cannot process transactions, the save operation is interrupted to prevent invalid data.

  • Lock (2. Journal Entry) – If the associated journal entry (instance.journal_entry) is locked, the transaction cannot be modified. The save process is halted if the journal entry is marked as locked.

Raises:

TransactionModelValidationError – Raised in the following scenarios: - Account Transactionality Failure: When bypass_account_state is False or not provided, and the associated account (instance.account) cannot process transactions. The exception contains a message identifying the account. - Locked Journal Entry: When the associated journal entry (instance.journal_entry) is locked, preventing modification of any related transactions. The error message describes the locked journal entry constraint.

Example

```python instance = TransactionModel(…) try:

transactionmodel_presave(instance) instance.save() # Save proceeds if no validation error occurs

except TransactionModelValidationError as e:

handle_error(str(e)) # Handle validation exception

```

Journal Entry Model

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

A Journal Entry (JE) is the foundation of all double entry accounting and financial data of any EntityModel. A JE encapsulates a collection of TransactionModel, which must contain two transactions at a minimum. Each transaction must perform a DEBIT or a CREDIT to an AccountModel. The JE Model performs additional validation to make sure that the sum of all DEBITs and the sum of all CREDITs are equal to keep the books balanced.

A JE by default will be un-posted, which means that simply creating a JE will have no effect on the EntityModel books. This behavior allows for constant refinement and persistence of JEs in the database without any impact on the books. Only Journal Entries contained within a POSTED LedgerModel (see LedgerModel for documentation) will have an impact in the EntityModel finances.

The JournalEntryModel also carries an optional EntityUnitModel, which are logical user-defined labels which help segregate the different financial statements into different business operations (see EntityUnitModel for documentation). Examples of EntityModelUnits are offices, departments, divisions, etc. The user may request financial statements by unit.

All JEs automatically generate a sequential Journal Entry Number, which takes into consideration the Fiscal Year of the JournalEntryModel instance. This functionality enables a human-readable tracking mechanism which helps with audits. It is also searchable and indexed to support quick searches and queries.

The JournalEntryModel is also responsible for validating the Financial Activity involved in the operations of the business. Whenever an account with ASSET_CA_CASH role is involved in a Journal Entry (see roles for more details), the JE is responsible for programmatically determine the kind of operation for the JE (Operating, Financing, Investing).

class django_ledger.models.journal_entry.ActivityEnum(*values)

Represents the database prefixes used for different types of accounting activities.

OPERATING

Prefix for a Journal Entry categorized as an Operating Activity.

Type:

str

INVESTING

Prefix for a Journal Entry categorized as an Investing Activity.

Type:

str

FINANCING

Prefix for a Journal Entry categorized as a Financing Activity.

Type:

str

class django_ledger.models.journal_entry.JournalEntryModel(*args, **kwargs)

Journal Entry Model Base Class From Abstract

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.journal_entry.JournalEntryModelAbstract(*args, **kwargs)

Abstract base model for handling journal entries in the bookkeeping system.

uuid

A unique identifier (primary key) for the journal entry, generated using uuid4().

Type:

UUID

je_number

A human-readable, unique, alphanumeric identifier for the journal entry (e.g., Voucher or Document Number). Includes the fiscal year as a prefix for organizational purposes.

Type:

str

timestamp

The date of the journal entry, used for financial statements. This timestamp applies to associated transactions.

Type:

datetime

description

An optional user-defined description for the journal entry.

Type:

str

entity_unit

A reference to a logical and self-contained structure within the EntityModel. Provides context for the journal entry. See EntityUnitModel documentation for details.

Type:

EntityUnitModel

activity

Indicates the nature of the activity associated with the journal entry. Must be one of the predefined ACTIVITIES (e.g., Operating, Financing, Investing) and is programmatically determined.

Type:

str

origin

Describes the origin or trigger for the journal entry (e.g., reconciliations, migrations, auto-generated). Max length: 30 characters.

Type:

str

posted

Determines whether the journal entry has been posted (affecting the books). Defaults to False.

Type:

bool

locked

Indicates whether the journal entry is locked, preventing further modifications. Defaults to False.

Type:

bool

ledger

A reference to the LedgerModel associated with this journal entry. This field is mandatory.

Type:

LedgerModel

is_closing_entry

Indicates if the journal entry is a closing entry. Defaults to False.

Type:

bool

can_delete() bool

Checks if the journal entry can be deleted.

can_edit() bool

Checks if the journal entry is editable.

can_generate_je_number() bool

Checks if a Journal Entry Number can be generated.

Returns:

True if the Journal Entry can generate a JE number, otherwise False.

Return type:

bool

can_lock() bool

Determines if the journal entry can be locked.

can_post(ignore_verify: bool = True) bool

Determines if the journal entry can be posted.

can_unlock() bool

Checks if the journal entry can be unlocked.

can_unpost() bool

Checks if the journal entry can be un-posted.

clean(verify: bool = False, raise_exception: bool = True, txs_qs: TransactionModelQuerySet | None = None) Tuple[TransactionModelQuerySet, bool]

Cleans the JournalEntryModel instance, optionally verifying it and generating a Journal Entry (JE) number if required.

Parameters:
  • verify (bool, optional) – If True, attempts to verify the JournalEntryModel during the cleaning process. Default is False.

  • raise_exception (bool, optional) – If True, raises an exception when the instance fails verification. Default is True.

  • txs_qs (TransactionModelQuerySet, optional) – A pre-fetched TransactionModelQuerySet. If provided, avoids additional database queries. The provided queryset is validated against the JournalEntryModel instance.

Returns:

A tuple containing: - The validated TransactionModelQuerySet for the JournalEntryModel instance. - A boolean indicating whether the instance passed verification.

Return type:

Tuple[TransactionModelQuerySet, bool]

Raises:

JournalEntryValidationError – If the instance has a timestamp in the future and is posted, or if verification fails and raise_exception is True.

delete(**kwargs)

Deletes the JournalEntryModel instance, ensuring it is allowed to be deleted.

Parameters:

**kwargs (dict) – Additional arguments passed to the parent delete method.

Raises:

JournalEntryValidationError – If the instance is not eligible for deletion.

property entity_last_closing_date: date | None

Retrieves the last closing date for an entity, if available.

This property returns the date of the most recent closing event associated with the entity. If no closing date exists, the result will be None.

Returns:

The date of the last closing event, or None if no closing date is available.

Return type:

Optional[date]

property entity_model: EntityModel

Provides access to the EntityModel related to the JournalEntryModel.

Returns:

The EntityModel instance linked to the instance LedgerModel.

Return type:

EntityModel

property entity_slug

Retrieves the unique slug associated with the entity.

The property first attempts to return the value stored in the _entity_slug attribute if it exists. If _entity_slug is not set, it falls back to the ledger.entity.slug attribute.

Returns:

The slug value from _entity_slug if available, or ledger.entity.slug otherwise.

Return type:

str

generate_activity(txs_qs: TransactionModelQuerySet | None = None, raise_exception: bool = True, force_update: bool = False) str | None

Generates the activity for the Journal Entry model based on its transactions.

Parameters:
  • txs_qs (Optional[TransactionModelQuerySet], default None) – Queryset of TransactionModel instances for validation. If None, transactions are queried.

  • raise_exception (bool, default True) – Determines whether exceptions are raised during processing.

  • force_update (bool, default False) – Forces the regeneration of activity even if it exists.

Returns:

Generated activity or None if not applicable.

Return type:

Optional[str]

generate_je_number(commit: bool = False) str

Generates the Journal Entry number in an atomic transaction.

Parameters:

commit (bool, default False) – Saves the generated JE number in the database.

Returns:

The generated or existing JE number.

Return type:

str

get_absolute_url() str

Generates the URL to view the details of the journal entry.

Returns:

The absolute URL for the journal entry details.

Return type:

str

get_action_lock_url() str

Generates the URL used to mark the journal entry as locked.

Returns:

The generated URL for marking the journal entry as locked.

Return type:

str

get_action_post_url() str

Generates the URL used to mark the journal entry as posted.

Returns:

The generated URL for marking the journal entry as posted.

Return type:

str

get_action_unlock_url() str

Generates the URL used to mark the journal entry as unlocked.

Returns:

The generated URL for marking the journal entry as unlocked.

Return type:

str

get_action_unpost_url() str

Generates the URL used to mark the journal entry as unposted.

Returns:

The generated URL for marking the journal entry as unposted.

Return type:

str

classmethod get_activity_from_roles(role_set: List[str] | Set[str], validate: bool = False, raise_exception: bool = True) str | None

Determines the financial activity type (e.g., operating, investing, financing) based on a set of account roles.

Parameters:
  • role_set (Union[List[str], Set[str]]) – The set of roles to analyze.

  • validate (bool, optional) – If True, validates the roles before analysis. Defaults to False.

  • raise_exception (bool, optional) – If True, raises an exception if multiple activities are detected. Defaults to True.

Returns:

The detected activity name, or None if no activity type is matched.

Return type:

Optional[str]

Raises:

JournalEntryValidationError – If multiple activities are detected and raise_exception is True.

get_activity_name() str | None

Gets the name of the activity associated with this journal entry.

The activity indicates its categorization based on GAAP (e.g., operating, investing, financing).

Returns:

The activity name if defined, otherwise None.

Return type:

Optional[str]

get_delete_message() str

Generates a confirmation message for deleting the JournalEntryModel instance.

Returns:

A confirmation message including the Journal Entry number and Ledger name.

Return type:

str

get_detail_txs_url() str

Generates the URL to view transaction details of the journal entry.

Returns:

The URL for transaction details of the journal entry.

Return type:

str

get_detail_url() str

Generates the detail URL for the journal entry.

Returns:

The URL for updating or viewing journal entry details.

Return type:

str

get_entity_last_closing_date() date | None

Retrieves the last closing date for the entity associated with the Journal Entry.

Returns:

The last closing date if one exists, otherwise None.

Return type:

Optional[date]

get_entity_unit_name(no_unit_name: str = '') str

Retrieves the name of the entity unit associated with the Journal Entry.

Parameters:

no_unit_name (str) – The fallback name to return if no unit is associated.

Returns:

The name of the entity unit, or the fallback provided.

Return type:

str

get_journal_entry_create_url() str

Constructs the URL to create a new journal entry associated with a specific ledger and entity.

Returns:

The URL to create a journal entry.

Return type:

str

get_journal_entry_list_url() str

Constructs the URL to access the list of journal entries associated with a specific ledger and entity.

Returns:

The URL for the journal entry list.

Return type:

str

get_lock_url() str

Generates the URL to mark the journal entry as locked.

Returns:

The URL for locking the journal entry.

Return type:

str

get_post_url() str

Generates the URL to mark the journal entry as posted.

Returns:

The URL for posting the journal entry.

Return type:

str

get_transaction_queryset(select_accounts: bool = True) TransactionModelQuerySet

Retrieves the TransactionModelQuerySet associated with this JournalEntryModel instance.

Parameters:

select_accounts (bool, optional) – If True, prefetches the related AccountModel for each transaction. Defaults to True.

Returns:

A queryset containing transactions related to this journal entry. If select_accounts is True, the accounts are included in the query as well.

Return type:

TransactionModelQuerySet

get_txs_balances(txs_qs: TransactionModelQuerySet | None = None, as_dict: bool = False) TransactionModelQuerySet | Dict[str, Decimal]

Calculates the total CREDIT and DEBIT balances for the journal entry.

This method performs an aggregate database query to compute the sum of CREDITs and DEBITs across the transactions related to this journal entry. Optionally, a pre-fetched TransactionModelQuerySet can be supplied for efficiency. Validation is performed to ensure that all transactions belong to this journal entry.

Parameters:
  • txs_qs (TransactionModelQuerySet, optional) – A pre-fetched queryset of transactions. If None, the queryset is fetched automatically.

  • as_dict (bool, optional) – If True, returns the results as a dictionary with keys “credit” and “debit”. Defaults to False.

Returns:

If as_dict is False, returns a queryset of aggregated balances. If as_dict is True, returns a dictionary containing the CREDIT and DEBIT totals.

Return type:

Union[TransactionModelQuerySet, Dict[str, Decimal]]

Raises:

JournalEntryValidationError – If the provided queryset is invalid or does not belong to this journal entry.

get_txs_roles(txs_qs: TransactionModelQuerySet | None = None, exclude_cash_role: bool = False) Set[str]

Retrieves the set of account roles involved in the journal entry’s transactions.

This method extracts the roles associated with the accounts linked to each transaction. Optionally, the CASH role can be excluded from the results.

Parameters:
  • txs_qs (TransactionModelQuerySet, optional) – A pre-fetched queryset of transactions. If None, the queryset is fetched automatically.

  • exclude_cash_role (bool, optional) – If True, excludes the CASH role from the result. Defaults to False.

Returns:

A set of account roles associated with this journal entry’s transactions.

Return type:

Set[str]

get_unlock_url() str

Generates the URL to mark the journal entry as unlocked.

Returns:

The URL for unlocking the journal entry.

Return type:

str

get_unpost_url() str

Generates the URL to mark the journal entry as unposted.

Returns:

The URL for unposting the journal entry.

Return type:

str

has_activity() bool

Checks if the journal entry has an associated activity.

Returns:

True if an activity is defined for the journal entry, otherwise False.

Return type:

bool

is_balance_valid(txs_qs: TransactionModelQuerySet, raise_exception: bool = True) bool

Validates whether the DEBITs and CREDITs of the transactions balance correctly.

Parameters:
  • txs_qs (TransactionModelQuerySet) – A QuerySet containing transactions to validate.

  • raise_exception (bool) – Whether to raise a JournalEntryValidationError if the validation fails.

Returns:

True if the transactions are balanced, otherwise False.

Return type:

bool

Raises:

JournalEntryValidationError – If the transactions are not balanced and raise_exception is True.

is_cash_involved(txs_qs: TransactionModelQuerySet | None = None) bool

Checks if the transactions involve cash assets.

Parameters:

txs_qs (Optional[TransactionModelQuerySet]) – Transactions to evaluate. If None, defaults to class behavior.

Returns:

True if cash assets are involved, otherwise False.

Return type:

bool

is_financing() bool

Checks if the Journal Entry is categorized as a financing activity.

Returns:

True if the activity is financing, otherwise False.

Return type:

bool

is_in_locked_period(new_timestamp: datetime | date | None = None) bool

Checks if the current Journal Entry falls within a locked period.

Parameters:

new_timestamp (Optional[Union[date, datetime]])) – An optional date or timestamp to be checked instead of the current timestamp.

Returns:

bool

Return type:

True if the Journal Entry is in a locked period, otherwise False.

is_investing() bool

Checks if the Journal Entry is categorized as an investing activity.

Returns:

True if the activity is investing, otherwise False.

Return type:

bool

is_locked() bool

Determines if the Journal Entry is locked.

A Journal Entry is considered locked if it is posted, explicitly marked as locked, falls within a locked period, or the associated ledger is locked.

Returns:

True if the Journal Entry is locked, otherwise False.

Return type:

bool

is_operating() bool

Checks if the Journal Entry is categorized as an operating activity.

Returns:

True if the activity is operating, otherwise False.

Return type:

bool

is_posted() bool

Returns whether the journal entry has been posted.

is_txs_qs_coa_valid(txs_qs: TransactionModelQuerySet, raise_exception: bool = True) bool

Validates that all transactions in the QuerySet are associated with the same Chart of Accounts (COA).

Parameters:

txs_qs (TransactionModelQuerySet) – A QuerySet containing transactions to validate.

Returns:

True if all transactions have the same Chart of Accounts, otherwise False.

Return type:

bool

is_txs_qs_valid(txs_qs: TransactionModelQuerySet, raise_exception: bool = True) bool

Validates whether the given Transaction QuerySet belongs to the current Journal Entry.

Parameters:
  • txs_qs (TransactionModelQuerySet) – A QuerySet containing transactions to validate.

  • raise_exception (bool) – Whether to raise a JournalEntryValidationError if the validation fails.

Returns:

True if all transactions belong to the Journal Entry, otherwise False.

Return type:

bool

Raises:

JournalEntryValidationError – If validation fails and raise_exception is True.

is_verified() bool

Checks if the Journal Entry is verified.

Returns:

True if the Journal Entry is verified, otherwise False.

Return type:

bool

ledger_is_locked()

Determines whether the ledger is locked.

This method checks the current state of the ledger to determine if it is locked and unavailable for further operations. It looks for an annotated attribute _ledger_is_locked and returns its value if found. If the attribute is not set, it delegates the check to the actual is_locked method of the ledger object.

Returns:

A boolean value indicating whether the ledger is locked.

Return type:

bool

lock(**kwargs)

Proxy function for mark_as_locked method.

mark_as_locked(commit: bool = False, raise_exception: bool = False, **kwargs)

Locked JournalEntryModels do not allow transactions to be edited.

Parameters:
  • commit (bool) – Commits changes into the Database, Defaults to False.

  • raise_exception (bool) – Raises JournalEntryValidationError if cannot lock. Defaults to False.

  • kwargs (dict) – Additional keyword arguments.

mark_as_posted(commit: bool = False, verify: bool = True, force_lock: bool = False, raise_exception: bool = False, **kwargs)

Posted transactions show on the EntityModel ledger and financial statements. :param commit: Commits changes into the Database, Defaults to False. :type commit: bool :param verify: Verifies JournalEntryModel before marking as posted. Defaults to False. :type verify: bool :param force_lock: Forces to lock the JournalEntry before is posted. :type force_lock: bool :param raise_exception: Raises JournalEntryValidationError if cannot post. Defaults to False. :type raise_exception: bool :param kwargs: Additional keyword arguments. :type kwargs: dict

mark_as_unlocked(commit: bool = False, raise_exception: bool = False, **kwargs)

Unlocked JournalEntryModels allow transactions to be edited.

Parameters:
  • commit (bool) – Commits changes into the Database, Defaults to False.

  • raise_exception (bool) – Raises JournalEntryValidationError if cannot lock. Defaults to False.

  • kwargs (dict) – Additional keyword arguments.

mark_as_unposted(commit: bool = False, raise_exception: bool = False, **kwargs)

Un-posted JournalEntryModels do not show on the EntityModel ledger and financial statements.

Parameters:
  • commit (bool) – Commits changes into the Database, Defaults to False.

  • raise_exception (bool) – Raises JournalEntryValidationError if cannot post. Defaults to False.

  • kwargs (dict) – Additional keyword arguments.

post(**kwargs)

Proxy function for mark_as_posted method.

save(verify: bool = True, post_on_verify: bool = False, *args, **kwargs)

Saves the JournalEntryModel instance, with optional verification and posting prior to saving.

Parameters:
  • verify (bool, optional) – If True, verifies the transactions of the JournalEntryModel before saving. Default is True.

  • post_on_verify (bool, optional) – If True, posts the JournalEntryModel if verification is successful and can_post() is True. Default is False.

Returns:

The saved JournalEntryModel instance.

Return type:

JournalEntryModel

Raises:

JournalEntryValidationError – If the instance fails verification or encounters an issue during save.

unlock(**kwargs)

Proxy function for mark_as_unlocked method.

unpost(**kwargs)

Proxy function for mark_as_unposted method.

validate_for_entity(entity_model: EntityModel | str | UUID, raise_exception: bool = True) bool

Validates whether the given entity_model owns thr Journal Entry instance.

This method checks if the provided entity_model owns the Journal Entry model instance. The entity_model can be of type EntityModel, str, or UUID. The method performs type-specific checks to ensure proper validation and returns the validation result.

Parameters:

entity_model (Union[EntityModel, str, UUID]) – The entity to validate against. It can either be an instance of the EntityModel, a string representation of a UUID, or a UUID object.

Returns:

A boolean value. True if the given entity_model corresponds to the current entity’s UUID, otherwise False.

Return type:

bool

verify(txs_qs: TransactionModelQuerySet | None = None, force_verify: bool = False, raise_exception: bool = True, **kwargs) Tuple[TransactionModelQuerySet, bool]

Verifies the validity of the Journal Entry model instance.

Parameters:
  • txs_qs (Optional[TransactionModelQuerySet], default None) – Queryset of TransactionModel instances to validate. If None, transactions are queried.

  • force_verify (bool, default False) – Forces re-verification even if already verified.

  • raise_exception (bool, default True) – Determines if exceptions are raised on validation failure.

  • kwargs (dict) – Additional options.

Returns:

  • The TransactionModelQuerySet associated with the JournalEntryModel.

  • A boolean indicating whether verification was successful.

Return type:

Tuple[TransactionModelQuerySet, bool]

class django_ledger.models.journal_entry.JournalEntryModelManager(*args, **kwargs)

A custom manager for the JournalEntryModel that extends Django’s default Manager with additional query features. It allows complex query handling based on relationships to the EntityModel and the authenticated UserModel.

This manager provides utility methods for generating filtered querysets (e.g., entries associated with specific users or entities), as well as annotations for convenience in query results.

for_entity(entity_slug: str | EntityModel, user_model) JournalEntryModelQuerySet

Filters the JournalEntryModel queryset for a specific entity and user.

This method provides a way to fetch journal entries related to a specific EntityModel, identified by its slug or model instance, with additional filtering scoped to the user.

Parameters:
  • entity_slug (str or EntityModel) – The slug of the entity (or an instance of EntityModel) used for filtering.

  • user_model (UserModel) – An authenticated Django user object.

Returns:

A customized queryset containing journal entries associated with the given entity and restricted by the user’s access permissions.

Return type:

JournalEntryModelQuerySet

for_user(user_model) JournalEntryModelQuerySet

Filters the JournalEntryModel queryset for the given user.

  • Superusers will have access to all journal entries.

  • Other authenticated users will only see entries for entities where they are admins or managers.

Parameters:

user_model (UserModel) – An authenticated Django user object.

Returns:

A filtered queryset restricted by the user’s entity relationships.

Return type:

JournalEntryModelQuerySet

get_queryset() JournalEntryModelQuerySet

Returns the default queryset for JournalEntryModel with additional annotations applied.

Annotations: - _entity_slug: The slug of the related EntityModel. - txs_count: The count of transactions (related TransactionModel instances)

for each journal entry.

Returns:

A custom queryset enhanced with annotations.

Return type:

JournalEntryModelQuerySet

class django_ledger.models.journal_entry.JournalEntryModelQuerySet(model=None, query=None, using=None, hints=None)

A custom QuerySet for working with Journal Entry models, providing additional convenience methods and validations for specific use cases.

This class enhances Django’s default QuerySet by adding tailored methods to manage and filter Journal Entries, such as handling posted, unposted, locked entries, and querying entries associated with specific ledgers.

create(verify_on_save: bool = False, force_create: bool = False, **kwargs)

Creates a new Journal Entry while enforcing business logic validations.

This method overrides Django’s default create() to ensure that Journal Entries cannot be created in a “posted” state unless explicitly overridden. Additionally, it offers optional pre-save verification.

Parameters:
  • verify_on_save (bool) – If True, performs a verification step before saving. This avoids additional database queries for validation when creating new entries. Should be used when the Journal Entry needs no transactional validation.

  • force_create (bool) – If True, allows the creation of a Journal Entry even in a “posted” state. Use with caution and only if you are certain of the consequences.

  • **kwargs (dict) – Additional keyword arguments passed to instantiate the Journal Entry model.

Returns:

The newly created Journal Entry.

Return type:

JournalEntryModel

Raises:

FieldError – Raised if attempting to create a “posted” Journal Entry without setting force_create=True.

for_ledger(ledger_pk: str | UUID | LedgerModel)

Filters the QuerySet to include Journal Entries associated with a specific Ledger.

Parameters:

ledger_pk (str, UUID, or LedgerModel) – The LedgerModel instance, its UUID, or a string representation of the UUID to identify the Ledger.

Returns:

A filtered QuerySet of Journal Entries associated with the specified Ledger.

Return type:

JournalEntryModelQuerySet

locked()

Filters the QuerySet to include only “locked” Journal Entries.

Returns:

A filtered QuerySet containing only locked Journal Entries.

Return type:

JournalEntryModelQuerySet

posted()

Filters the QuerySet to include only “posted” Journal Entries.

Returns:

A filtered QuerySet containing only posted Journal Entries.

Return type:

JournalEntryModelQuerySet

unlocked()

Filters the QuerySet to include only “unlocked” Journal Entries.

Returns:

A filtered QuerySet containing only unlocked Journal Entries.

Return type:

JournalEntryModelQuerySet

unposted()

Filters the QuerySet to include only “unposted” Journal Entries.

Returns:

A filtered QuerySet containing only unposted Journal Entries.

Return type:

JournalEntryModelQuerySet

exception django_ledger.models.journal_entry.JournalEntryValidationError(message, code=None, params=None)

Bank Account Model

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

A Bank Account refers to the financial institution which holds financial assets for the EntityModel. A bank account usually holds cash, which is a Current Asset. Transactions may be imported using the open financial format specification OFX into a staging area for final disposition into the EntityModel ledger.

class django_ledger.models.bank_account.BankAccountModel(*args, **kwargs)

Base Bank Account Model Implementation

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.bank_account.BankAccountModelAbstract(*args, **kwargs)

This is the main abstract class which the BankAccountModel database will inherit from. The BankAccountModel inherits functionality from the following MixIns:

  1. BankAccountInfoMixIn

  2. CreateUpdateMixIn

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

name

A user defined name for the bank account as a String.

Type:

str

entity_model

The EntityModel associated with the BankAccountModel instance.

Type:

EntityModel

account_model

The AccountModel associated with the BankAccountModel instance. Must be an account with role ASSET_CA_CASH.

Type:

AccountModel

active

Determines whether the BackAccountModel instance bank account is active. Defaults to True.

Type:

bool

hidden

Determines whether the BackAccountModel instance bank account is hidden. Defaults to False.

Type:

bool

class django_ledger.models.bank_account.BankAccountModelManager(*args, **kwargs)

Custom defined Model Manager for the BankAccountModel.

for_entity(entity_slug, user_model) BankAccountModelQuerySet

Allows only the authorized user to query the BankAccountModel for a given EntityModel. This is the recommended initial QuerySet.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

get_queryset() BankAccountModelQuerySet

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class django_ledger.models.bank_account.BankAccountModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined QuerySet for the BankAccountModel.

active() QuerySet

Active bank accounts which can be used to create new transactions.

Returns:

A filtered BankAccountModelQuerySet of active accounts.

Return type:

BankAccountModelQuerySet

hidden() QuerySet

Hidden bank accounts which can be used to create new transactions. but will not show in drop down menus in the UI.

Returns:

A filtered BankAccountModelQuerySet of active accounts.

Return type:

BankAccountModelQuerySet

exception django_ledger.models.bank_account.BankAccountValidationError(message, code=None, params=None)

Chart of Accounts Model

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

Chart Of Accounts

A Chart of Accounts (CoA) is a fundamental component of financial management in Django Ledger. It serves as the backbone of financial statements and is organized within a ChartOfAccountModel.

### Key Features

  • Account Roles: The CoA includes various account types such as: - Cash - Accounts Receivable - Expenses - Liabilities - Income

  • Hierarchical Structure: Accounts are logically grouped to form financial statements. For example, the Balance

Sheet may have a structure like this:
  • Fixed Assets - Tangible Assets

    • Building

    • Plant & Equipment

    • Machinery

    • Intangible Assets

  • Financial Statement Preparation: Individual account balances are aggregated based on the CoA and AccountModel

roles to create comprehensive financial statements.

### Usage in EntityModel

  • Every EntityModel must have a default CoA to create any type of transaction.

  • If no explicit CoA is specified, the EntityModel’s default CoA is used.

  • Only ONE Chart of Accounts can be used when creating Journal Entries.

  • Commingling between different CoAs is not allowed to maintain the integrity of Journal Entries.

This structure ensures a clear and organized approach to financial management within Django Ledger, facilitating accurate record-keeping and reporting.

class django_ledger.models.chart_of_accounts.ChartOfAccountModel(*args, **kwargs)

Base ChartOfAccounts Model

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.chart_of_accounts.ChartOfAccountModelAbstract(*args, **kwargs)

Abstract base class for the Chart of Account model.

uuid

UUID field for the chart of account model (primary key).

Type:

UUIDField

entity

ForeignKey to the EntityModel.

Type:

ForeignKey

active

BooleanField indicating whether the chart of account is active or not.

Type:

BooleanField

description

TextField storing the description of the chart of account.

Type:

TextField

objects

Manager for the ChartOfAccountModel.

Type:

ChartOfAccountModelManager

can_activate() bool

Check if the ChartOffAccountModel instance can be activated.

Return type:

True if the object can be activated, False otherwise.

can_deactivate() bool

Check if the ChartOffAccountModel instance can be deactivated.

Return type:

True if the object can be deactivated, False otherwise.

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

configure(raise_exception: bool = True)

A method that properly configures the ChartOfAccounts model and creates the appropriate hierarchy boilerplate to support the insertion of new accounts into the chart of account model tree. This method must be called every time the ChartOfAccounts model is created.

Parameters:

raise_exception (bool, optional) – Whether to raise an exception if root nodes already exist in the Chart of Accounts (default is True). This indicates that the ChartOfAccountModel instance is already configured.

create_account(code: str, role: str, name: str, balance_type: str, active: bool, root_account_qs: AccountModelQuerySet | None = None)

Proper method for inserting a new Account Model into a CoA. Use this in liu of the direct instantiation of the AccountModel of using the django related manager.

Parameters:
  • code (str) – The code of the account to be created.

  • role (str) – The role of the account. This can be a user-defined value.

  • name (str) – The name of the account.

  • balance_type (str) – The balance type of the account. This can be a user-defined value.

  • active (bool) – Specifies whether the account is active or not.

  • root_account_qs (Optional[AccountModelQuerySet], optional) – The query set of root accounts to which the created account should be linked. Defaults to None.

Returns:

The created account model instance.

Return type:

AccountModel

generate_slug(commit: bool = False, raise_exception: bool = False) str

Generates and assigns a slug based on the ChartOfAccounts model instance EntityModel information.

Parameters:

raise_exception (bool, optional) – If set to True, it will raise a ChartOfAccountsModelValidationError if the self.slug is already set.

Returns:

The generated slug for the Chart of Accounts.

Return type:

str

Raises:

ChartOfAccountsModelValidationError – If raise_exception is set to True and self.slug is already set.

get_account_root_node(account_model: AccountModel, root_account_qs: AccountModelQuerySet | None = None, as_queryset: bool = False) AccountModel

Fetches the root node of the ChartOfAccountModel instance. The root node is the highest level of the CoA hierarchy. It can be used to traverse the hierarchy of the CoA structure downstream.

Parameters:
  • account_model (AccountModel) – The account model for which to find the root node.

  • root_account_qs (Optional[AccountModelQuerySet], optional) – The queryset of root accounts. If not provided, it will be retrieved using get_coa_root_accounts_qs method.

  • as_queryset (bool, optional) – If True, return the root account queryset instead of a single root account. Default is False.

Returns:

If as_queryset is True, returns the root account queryset. Otherwise, returns a single root account.

Return type:

Union[AccountModelQuerySet, AccountModel]

Raises:

ChartOfAccountsModelValidationError – If the account model is not part of the chart of accounts.

get_coa_account_tree() Dict

Performs a bulk dump of the ChartOfAccounts model instance accounts to a dictionary. The method invokes the`dump_bulk` method on the ChartOfAccount model instance root node. See Django Tree Beard documentation for more information.

Returns:

A dictionary containing all accounts from the chart of accounts in a nested structure.

Return type:

Dict

get_coa_accounts(active_only: bool = True) AccountModelQuerySet

Returns the AccountModelQuerySet associated with the ChartOfAccounts model instance.

Parameters:

active_only (bool, optional) – Flag to indicate whether to retrieve only active accounts or all accounts. Default is True.

Returns:

A queryset containing accounts from the chart of accounts.

Return type:

AccountModelQuerySet

get_coa_root_accounts_qs() AccountModelQuerySet

Retrieves the root accounts in the chart of accounts.

Returns:

A queryset containing the root accounts in the chart of accounts.

Return type:

AccountModelQuerySet

get_coa_root_node() AccountModel

Retrieves the root node of the chart of accounts.

Returns:

The root node of the chart of accounts.

Return type:

AccountModel

get_non_root_coa_accounts_qs() AccountModelQuerySet

Returns a query set of non-root accounts in the chart of accounts.

Returns:

A query set of non-root accounts in the chart of accounts.

Return type:

AccountModelQuerySet

insert_account(account_model: AccountModel, root_account_qs: AccountModelQuerySet | None = None)

This method inserts the given account model into the chart of accounts (COA) instance. It first verifies if the account model’s COA model ID matches the COA’s UUID. If not, it raises a ChartOfAccountsModelValidationError. If the root_account_qs is not provided, it retrieves the root account query set using the get_coa_root_accounts_qs method. Providing a pre-fetched root_account_qs avoids unnecessary retrieval of the root account query set every an account model is inserted into the CoA.

Next, it validates the provided root_account_qs if it is not None. Then, it obtains the root node for the account model using the get_account_root_node method and assigns it to account_root_node.

Finally, it adds the account model as a child to the account_root_node and retrieves the updated COA accounts query set using the get_non_root_coa_accounts_qs method. It returns the inserted account model found in the COA accounts query set.

Parameters:
  • account_model (AccountModel) – The account model to be inserted into the chart of accounts.

  • root_account_qs (Optional[AccountModelQuerySet], default=None) – The root account query set. If not provided, it will be obtained using the get_coa_root_accounts_qs method.

Returns:

The inserted account model.

Return type:

AccountModel

Raises:

ChartOfAccountsModelValidationError – If the provided account model has an invalid COA model ID for the current COA.

is_active() bool

Check if the ChartOfAccountModel instance is active.

Returns:

True if the ChartOfAccountModel instance is active, False otherwise.

Return type:

bool

is_default() bool

Check if the ChartOfAccountModel instance is set as the default for the EntityModel.

Returns:

True if the ChartOfAccountModel instance is set as the default for the EntityModel. Else, False.

Return type:

bool

mark_as_active(commit: bool = False, raise_exception: bool = False, **kwargs)

Marks the current Chart of Accounts as Active.

Parameters:
  • commit (bool) – Commit the action into the Database. Default is False.

  • raise_exception (bool) – Raises exception if Chart of Account model instance is already active. Default is False.

mark_as_active_url() str

Returns the URL to mark the current Chart of Accounts instances as active.

Returns:

The URL as a String.

Return type:

str

mark_as_default(commit: bool = False, raise_exception: bool = False, **kwargs)

Marks the current Chart of Accounts instances as default for the EntityModel.

Parameters:
  • commit (bool) – Commit the action into the Database. Default is False.

  • raise_exception (bool) – Raises exception if Chart of Account model instance is already marked as default.

mark_as_default_url() str

Returns the URL to mark the current Chart of Accounts instances as Default for the EntityModel.

Returns:

The URL as a String.

Return type:

str

mark_as_inactive(commit: bool = False, raise_exception: bool = False, **kwargs)

Marks the current Chart of Accounts as Active.

Parameters:
  • commit (bool) – Commit the action into the Database. Default is False.

  • raise_exception (bool) – Raises exception if Chart of Account model instance is already active. Default is False.

mark_as_inactive_url() str

Returns the URL to mark the current Chart of Accounts instances as inactive.

Returns:

The URL as a String.

Return type:

str

validate_account_model_qs(account_model_qs: AccountModelQuerySet)

Validates the given AccountModelQuerySet for the ChartOfAccountsModel.

Parameters:

account_model_qs (AccountModelQuerySet) – The AccountModelQuerySet to validate.

Raises:

ChartOfAccountsModelValidationError – If the account_model_qs is not an instance of AccountModelQuerySet or if it contains an account model with a different coa_model_id than the current CoA model.

class django_ledger.models.chart_of_accounts.ChartOfAccountModelManager(*args, **kwargs)

A custom defined ChartOfAccountModelManager that will act as an interface to handling the initial DB queries to the ChartOfAccountModel.

for_entity(entity_model, user_model) ChartOfAccountModelQuerySet

Fetches a QuerySet of ChartOfAccountsModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Returns:

Returns a ChartOfAccountQuerySet with applied filters.

Return type:

ChartOfAccountQuerySet

for_user(user_model) ChartOfAccountModelQuerySet

Fetches a QuerySet of ChartOfAccountModel that the UserModel as access to. May include ChartOfAccountModel from multiple Entities. The user has access to bills if: 1. Is listed as Manager of Entity. 2. Is the Admin of the Entity.

Parameters:

user_model – Logged in and authenticated django UserModel instance.

Returns:

Returns a ChartOfAccountQuerySet with applied filters.

Return type:

ChartOfAccountQuerySet

get_queryset()

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class django_ledger.models.chart_of_accounts.ChartOfAccountModelQuerySet(model=None, query=None, using=None, hints=None)
active()

QuerySet method to retrieve active items.

exception django_ledger.models.chart_of_accounts.ChartOfAccountsModelValidationError(message, code=None, params=None)

Default Chart of Accounts

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

This is the base Chart of Accounts that has all the possible accounts that are useful for the preparation of the Financial Statements. A user may choose to use the default CoA at the creation of each EntityModel but it is not required. The default CoA is intended to provide a QuickStart solution for most use cases.

The Chart of Accounts is broadly bifurcated into 5 different Sections:
  1. Assets:

  2. Liabilities

  3. Shareholder’s Equity

  4. Income

  5. COGS

  6. Expenses

The Django Ledger Default Chart of Accounts must include the following fields:
  • Code - String

  • Role - A choice from any of the possible account roles (see django_ledger.roles module).

  • Balance Type - A CREDIT or DEBIT balance account setting.

  • Name - A human readable name.

  • Parent - The parent account of the AccountModel instance.

If the DEFAULT_CHART_OF_ACCOUNTS setting is present, the default CoA will be replace by such setting.

Default Chart of Accounts Table

code

role

balance_type

name

parent

root_group

1910

asset_adjustment

debit

Securities Unrealized Gains/Losses

root_assets

1920

asset_adjustment

debit

PPE Unrealized Gains/Losses

root_assets

1010

asset_ca_cash

debit

Cash

root_assets

1050

asset_ca_mkt_sec

debit

Short Term Investments

root_assets

1200

asset_ca_inv

debit

Inventory

root_assets

1300

asset_ca_prepaid

debit

Prepaid Expenses

root_assets

1100

asset_ca_recv

debit

Accounts Receivable

root_assets

1110

asset_ca_uncoll

credit

Uncollectibles

root_assets

1810

asset_ia

debit

Goodwill

root_assets

1820

asset_ia

debit

Intellectual Property

root_assets

1830

asset_ia_accum_amort

credit

Less: Intangible Assets Accumulated Amortization

root_assets

1520

asset_lti_land

debit

Land

root_assets

1510

asset_lti_notes

debit

Notes Receivable

root_assets

1530

asset_lti_sec

debit

Securities

root_assets

1610

asset_ppe_build

debit

Buildings

root_assets

1611

asset_ppe_build_accum_depr

credit

Less: Buildings Accumulated Depreciation

root_assets

1630

asset_ppe_equip

debit

Equipment

root_assets

1631

asset_ppe_equip_accum_depr

credit

Less: Equipment Accumulated Depreciation

root_assets

1620

asset_ppe_plant

debit

Plant

root_assets

1640

asset_ppe_plant

debit

Vehicles

root_assets

1650

asset_ppe_plant

debit

Furniture & Fixtures

root_assets

1621

asset_ppe_plant_depr

credit

Less: Plant Accumulated Depreciation

root_assets

1641

asset_ppe_plant_depr

credit

Less: Vehicles Accumulated Depreciation

root_assets

1651

asset_ppe_plant_depr

credit

Less: Furniture & Fixtures Accumulated Depreciation

root_assets

3910

eq_adjustment

credit

Available for Sale

root_capital

3920

eq_adjustment

credit

PPE Unrealized Gains/Losses

root_capital

3010

eq_capital

credit

Capital Account 1

root_capital

3020

eq_capital

credit

Capital Account 2

root_capital

3030

eq_capital

credit

Capital Account 3

root_capital

3930

eq_dividends

debit

Dividends & Distributions

root_capital

3110

eq_stock_common

credit

Common Stock

root_capital

3120

eq_stock_preferred

credit

Preferred Stock

root_capital

5010

cogs_regular

debit

Cost of Goods Sold

root_cogs

6075

ex_amortization

debit

Amortization Expense

root_expenses

6070

ex_depreciation

debit

Depreciation Expense

root_expenses

6130

ex_interest

debit

Interest Expense

root_expenses

6500

ex_other

debit

Misc. Expense

root_expenses

6010

ex_regular

debit

Advertising

root_expenses

6020

ex_regular

debit

Amortization

root_expenses

6030

ex_regular

debit

Auto Expense

root_expenses

6040

ex_regular

debit

Bad Debt

root_expenses

6050

ex_regular

debit

Bank Charges

root_expenses

6060

ex_regular

debit

Commission Expense

root_expenses

6080

ex_regular

debit

Employee Benefits

root_expenses

6081

ex_regular

debit

Employee Wages

root_expenses

6090

ex_regular

debit

Freight

root_expenses

6110

ex_regular

debit

Gifts

root_expenses

6120

ex_regular

debit

Insurance

root_expenses

6140

ex_regular

debit

Professional Fees

root_expenses

6150

ex_regular

debit

License Expense

root_expenses

6170

ex_regular

debit

Maintenance Expense

root_expenses

6180

ex_regular

debit

Meals & Entertainment

root_expenses

6190

ex_regular

debit

Office Expense

root_expenses

6220

ex_regular

debit

Printing

root_expenses

6230

ex_regular

debit

Postage

root_expenses

6240

ex_regular

debit

Rent

root_expenses

6250

ex_regular

debit

Maintenance & Repairs

root_expenses

6251

ex_regular

debit

Maintenance

root_expenses

6252

ex_regular

debit

Repairs

root_expenses

6253

ex_regular

debit

HOA

root_expenses

6254

ex_regular

debit

Snow Removal

root_expenses

6255

ex_regular

debit

Lawn Care

root_expenses

6260

ex_regular

debit

Salaries

root_expenses

6270

ex_regular

debit

Supplies

root_expenses

6290

ex_regular

debit

Utilities

root_expenses

6292

ex_regular

debit

Sewer

root_expenses

6293

ex_regular

debit

Gas

root_expenses

6294

ex_regular

debit

Garbage

root_expenses

6295

ex_regular

debit

Electricity

root_expenses

6300

ex_regular

debit

Property Management

root_expenses

6400

ex_regular

debit

Vacancy

root_expenses

6210

ex_taxes

debit

Payroll Taxes

root_expenses

6280

ex_taxes

debit

Taxes

root_expenses

4040

in_gain_loss

credit

Capital Gain/Loss Income

root_income

4030

in_interest

credit

Interest Income

root_income

4010

in_operational

credit

Sales Income

root_income

4050

in_other

credit

Other Income

root_income

4020

in_passive

credit

Investing Income

root_income

2010

lia_cl_acc_payable

credit

Accounts Payable

root_liabilities

2060

lia_cl_def_rev

credit

Deferred Revenues

root_liabilities

2030

lia_cl_int_payable

credit

Interest Payable

root_liabilities

2050

lia_cl_ltd_mat

credit

Current Maturities LT Debt

root_liabilities

2070

lia_cl_other

credit

Other Payables

root_liabilities

2040

lia_cl_st_notes_payable

credit

Short-Term Notes Payable

root_liabilities

2020

lia_cl_wages_payable

credit

Wages Payable

root_liabilities

2120

lia_ltl_bonds

credit

Bonds Payable

root_liabilities

2130

lia_ltl_mortgage

credit

Mortgage Payable

root_liabilities

2110

lia_ltl_notes

credit

Long Term Notes Payable

root_liabilities

django_ledger.models.coa_default.get_default_coa_rst(default_coa: Dict | None = None) str

Converts the provided Chart of Account into restructuredText format. :param default_coa: A dictionary of chart of accounts. Must follow the same keys as CHART_OF_ACCOUNTS.

Returns:

The table in RestructuredText format.

Return type:

str

django_ledger.models.coa_default.verify_unique_code()

A function that verifies that there are no duplicate code in the Default CoA during the development and launch.

Item Model

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

The Items refer to the additional detail provided to Bills, Invoices, Purchase Orders and Estimates for the purposes of documenting a breakdown of materials, labor, equipment, and other resources used for the purposes of the business operations.

The items associated with any of the aforementioned models are responsible for calculating the different amounts that ultimately drive the behavior of Journal Entries onto the company books.

Each item must be assigned a UnitOfMeasureModel which is the way or method used to quantify such resource. Examples are Pounds, Gallons, Man Hours, etc used to measure how resources are quantified when associated with a specific ItemTransactionModel. If many unit of measures are used for the same item, it would constitute a different item hence a new record must be created.

ItemsTransactionModels constitute the way multiple items and used resources are associated with Bills, Invoices, Purchase Orders and Estimates. Each transaction will record the unit of measure and quantity of each resource. Totals will be calculated and associated with the containing model at the time of update.

class django_ledger.models.items.ItemModel(*args, **kwargs)

Base ItemModel from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.items.ItemModelAbstract(*args, **kwargs)

Base implementation of the ItemModel.

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

name

Human readable name of the ItemModel instance. Maximum of 100 characters.

Type:

str

item_role

A choice of ITEM_ROLE_CHOICES that determines whether the ItemModel should be treated as an expense, inventory, service or product.

Type:

str

item_type

A choice of ITEM_TYPE_CHOICES that determines whether the ItemModel should be treated as labor, material, equipment, lump sum or other.

Type:

str

uom

The assigned UnitOfMeasureModel of the ItemModel instance. Mandatory.

Type:

UnitOfMeasureModel

sku

The SKU number associated with the ItemModel instance. Maximum 50 characters.

Type:

str

upc

The UPC number associated with the ItemModel instance. Maximum 50 characters.

Type:

str

item_id

EntityModel specific id associated with the ItemModel instance. Maximum 50 characters.

Type:

str

item_number

Auto generated human-readable item number.

Type:

str

is_active

Determines if the ItemModel instance is considered active. Defaults to True.

Type:

bool

default_amount

The default, prepopulated monetary amount of the ItemModel instance .

Type:

Decimal

for_inventory

Legacy field used to determine if the ItemModel instance is considered an inventory item. Mandatory. Superseded by item_role field. Will be deprecated.

Type:

bool

is_product_or_service

Legacy field used to determine if the ItemModel instance is considered a product or service item. Mandatory. Superseded by item_role field. Will be deprecated.

Type:

bool

sold_as_unit

Determines if only whole numbers can be used when specifying the quantity on ItemTransactionModels.

Type:

bool

inventory_account

Inventory account associated with the ItemModel instance. Enforced if ItemModel instance is_inventory() is True.

Type:

AccountModel

inventory_received

Holds the total quantity of the inventory received for the whole EntityModel instance.

Type:

Decimal

inventory_received_value

Holds the total monetary value of the inventory received for the whole EntityModel instance.

Type:

Decimal

cogs_account

COGS account associated with the ItemModel instance. Enforced if ItemModel instance is_inventory() is True.

Type:

AccountModel

earnings_account
Earnings account associated with the ItemModel instance. Enforced if ItemModel instance is_product() or

is_service() is True.

Type:

AccountModel

expense_account

Expense account associated with the ItemModel instance. Enforced if ItemModel instance is_expense() is True.

Type:

AccountModel

additional_info

Additional user defined information stored as JSON document in the Database.

Type:

dict

entity

The EntityModel associated with the ItemModel instance.

Type:

EntityModel

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

generate_item_number(commit: bool = False) str

Atomic Transaction. Generates the next Vendor Number available. @param commit: Commit transaction into VendorModel. @return: A String, representing the current InvoiceModel instance Document Number.

save(**kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

class django_ledger.models.items.ItemModelManager(*args, **kwargs)

A custom defined ItemModelManager that implement custom QuerySet methods related to the ItemModel

for_bill(entity_slug, user_model)

Returns a QuerySet of ItemModels that can only be used for BillModels for a specific EntityModel & UserModel. These types of items qualify as expenses or inventory purchases. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

for_entity(entity_slug, user_model)

Returns a QuerySet of ItemModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

for_entity_active(entity_slug, user_model)

Returns a QuerySet of Active ItemModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

for_estimate(entity_slug: str, user_model)

Returns a QuerySet of ItemModels that can only be used for EstimateModels for a specific EntityModel & UserModel. These types of items qualify as products. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

for_invoice(entity_slug, user_model)

Returns a QuerySet of ItemModels that can only be used for InvoiceModels for a specific EntityModel & UserModel. These types of items qualify as products or services sold. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

for_po(entity_slug, user_model)

Returns a QuerySet of ItemModels that can only be used for PurchaseOrders for a specific EntityModel & UserModel. These types of items qualify as inventory purchases. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

class django_ledger.models.items.ItemModelQuerySet(model=None, query=None, using=None, hints=None)

A custom-defined ItemModelQuerySet that implements custom QuerySet methods related to the ItemModel.

active()

Filters the QuerySet to only active Item Models.

Returns:

A QuerySet with applied filters.

Return type:

ItemModelQuerySet

bills()

Filters the QuerySet to ItemModels that are eligible only for bills..

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

expenses()

Filters the QuerySet to ItemModels that only qualify as expenses.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

inventory_all()

Filters the QuerySet to ItemModels that only qualify as inventory. These types of items may be finished or unfinished.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

inventory_wip()

Filters the QuerySet to ItemModels that only qualify as inventory. These types of items cannot be sold as they are not considered a finished product.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

products()

Filters the QuerySet to ItemModels that only qualify as products.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

services()

Filters the QuerySet to ItemModels that only qualify as services.

Returns:

A Filtered ItemModelQuerySet.

Return type:

ItemModelQuerySet

exception django_ledger.models.items.ItemModelValidationError(message, code=None, params=None)
class django_ledger.models.items.ItemTransactionModel(*args, **kwargs)

Base ItemTransactionModel from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.items.ItemTransactionModelAbstract(*args, **kwargs)
can_create_bill() bool

Determines if the ItemModel instance can be associated with a BillModel. :returns: True, if instance can be associated with a BillModel, else False. :rtype: bool

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

get_status_css_class() str

Determines the CSS Class used to represent the ItemModel instance in the UI based on its status.

Returns:

The CSS class as a String.

Return type:

str

has_bill()

Determines if the ItemModel instance is associated with a BillModel.

Returns:

True if associated with an BillModel, else False.

Return type:

bool

has_estimate() bool

Determines if the ItemModel instance is associated with an EstimateModel.

Returns:

True if associated with an EstimateModel, else False.

Return type:

bool

has_invoice()

Determines if the ItemModel instance is associated with a InvoiceModel.

Returns:

True if associated with an InvoiceModel, else False.

Return type:

bool

has_po() bool

Determines if the ItemModel instance is associated with a PurchaseOrderModel.

Returns:

True if associated with an PurchaseOrderModel, else False.

Return type:

bool

html_id() str

Unique ItemModel instance HTML ID.

Returns:

HTML ID as a String.

Return type:

str

html_id_quantity() str

Unique ItemModel instance quantity field HTML ID.

Returns:

HTML ID as a String.

Return type:

str

html_id_unit_cost() str

Unique ItemModel instance unit cost field HTML ID.

Returns:

HTML ID as a String.

Return type:

str

is_canceled()

Determines if the ItemModel instance is canceled. ItemModel status is only relevant for ItemModels associated with PurchaseOrderModels.

Returns:

True if canceled, else False.

Return type:

bool

is_ordered() bool

Determines if the ItemModel instance is ordered. ItemModel status is only relevant for ItemModels associated with PurchaseOrderModels.

Returns:

True if received, else False.

Return type:

bool

is_received() bool

Determines if the ItemModel instance is received. ItemModel status is only relevant for ItemModels associated with PurchaseOrderModels.

Returns:

True if received, else False.

Return type:

bool

update_cost_estimate()

Hook that updates and checks the ItemModel instance cost estimate fields according to its associations. Calculates and updates ce_cost_estimate accordingly. Called on every clean() call.

update_po_total_amount()

Hook that updates and checks the ItemModel instance purchase order fields according to its associations. Calculates and updates po_total_amount accordingly. Called on every clean() call.

update_revenue_estimate()

Hook that updates and checks the ItemModel instance revenue estimate fields according to its associations. Calculates and updates ce_revenue_estimate accordingly. Called on every clean() call.

update_total_amount()

Hook that updates and checks the ItemModel instance fields according to its associations. Calculates and updates total_amount accordingly. Called on every clean() call.

class django_ledger.models.items.ItemTransactionModelQuerySet(model=None, query=None, using=None, hints=None)
class django_ledger.models.items.UnitOfMeasureModel(*args, **kwargs)

Base UnitOfMeasureModel from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.items.UnitOfMeasureModelAbstract(*args, **kwargs)

Base implementation of a Unit of Measure assigned to each Item Transaction.

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

name

The name of the unit of measure. Maximum of 50 characters.

Type:

str

unit_abbr

An abbreviation of the unit of measure used as an identifier or slug for URLs and queries.

Type:

str

is_active

A boolean representing of the UnitOfMeasureModel instance is active to be used on new transactions.

Type:

bool

entity

The EntityModel associated with the UnitOfMeasureModel instance.

Type:

EntityModel

class django_ledger.models.items.UnitOfMeasureModelManager(*args, **kwargs)

A custom defined QuerySet Manager for the UnitOfMeasureModel.

for_entity(entity_slug: str, user_model) QuerySet

Fetches the UnitOfMeasureModels associated with the provided EntityModel and UserModel.

Parameters:
  • entity_slug (str or EntityModel) – The EntityModel slug or EntityModel used to filter the QuerySet.

  • user_model (UserModel) – The Django UserModel to check permissions.

Returns:

A QuerySet with applied filters.

Return type:

QuerySet

for_entity_active(entity_slug: str, user_model)

Fetches the Active UnitOfMeasureModels associated with the provided EntityModel and UserModel.

Parameters:
  • entity_slug (str or EntityModel) – The EntityModel slug or EntityModel used to filter the QuerySet.

  • user_model (UserModel) – The Django UserModel to check permissions.

Returns:

A QuerySet with applied filters.

Return type:

QuerySet

class django_ledger.models.items.UnitOfMeasureModelQuerySet(model=None, query=None, using=None, hints=None)

Bill Model

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

This module implements the BillModel, which represents an Invoice received from a Supplier/Vendor, on which the Vendor states the amount owed by the recipient for the purposes of supplying goods and/or services. In addition to tracking the bill amount, it tracks the paid and due amount.

Examples

>>> user_model = request.user  # django UserModel
>>> entity_slug = kwargs['entity_slug'] # may come from view kwargs
>>> bill_model = BillModel()
>>> ledger_model, bill_model = bill_model.configure(entity_slug=entity_slug, user_model=user_model)
>>> bill_model.save()
class django_ledger.models.bill.BillModel(*args, **kwargs)

Base BillModel from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.bill.BillModelAbstract(*args, **kwargs)

This is the main abstract class which the BillModel database will inherit from. The BillModel inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

bill_number

Auto assigned number at creation by generate_bill_number() function. Prefix be customized with DJANGO_LEDGER_BILL_NUMBER_PREFIX setting. Includes a reference to the Fiscal Year and a sequence number. Max Length is 20.

Type:

str

bill_status

Current status of the BillModel. Must be one of the choices as mentioned under “BILL_STATUS”. By default , the status will be “Draft”. Options are: Draft, In Review, Approved, Paid, Void or Canceled.

Type:

str

xref

This is the filed for capturing of any External reference number like the PO number of the buyer. Any other reference number like the Vendor code in buyer books may also be captured.

Type:

str

vendor

This is the foreign key reference to the VendorModel from whom the purchase has been made.

Type:

VendorModel

additional_info

Any additional metadata about the BillModel may be stored here as a dictionary object. The data is serialized and stored as a JSON document in the Database.

Type:

dict

bill_items

A foreign key reference to the list of ItemTransactionModel that make the bill amount.

ce_model

A foreign key to the BillModel associated EstimateModel for overall Job/Contract tracking.

Type:

EstimateModel

date_draft

The draft date represents the date when the BillModel was first created. Defaults to localdate.

Type:

date

date_in_review

The in review date represents the date when the BillModel was marked as In Review status. Will be null if BillModel is canceled during draft status. Defaults to localdate.

Type:

date

date_approved

The approved date represents the date when the BillModel was approved. Will be null if BillModel is canceled. Defaults to localdate.

Type:

date

date_paid

The paid date represents the date when the BillModel was paid and amount_due equals amount_paid. Will be null if BillModel is canceled. Defaults to localdate.

Type:

date

date_void

The void date represents the date when the BillModel was void, if applicable. Will be null unless BillModel is void. Defaults to localdate.

Type:

date

date_canceled

The canceled date represents the date when the BillModel was canceled, if applicable. Will be null unless BillModel is canceled. Defaults to localdate.

Type:

date

BILL_STATUS = [('draft', 'Draft'), ('in_review', 'In Review'), ('approved', 'Approved'), ('paid', 'Paid'), ('canceled', 'Canceled'), ('void', 'Void')]

The different bill status options and their representation in the Database.

bind_estimate(estimate_model, commit: bool = False, raise_exception: bool = True)

Binds BillModel to a given EstimateModel. Raises ValueError if EstimateModel cannot be bound.

Parameters:
  • estimate_model (EstimateModel) – EstimateModel to bind.

  • raise_exception (bool) – Raises BillModelValidationError if unable to bind EstimateModel.

  • commit (bool) – Commits transaction into current BillModel.

can_approve() bool

Checks if the BillModel can be marked as Approved.

Returns:

True if BillModel can be marked as approved, else False.

Return type:

bool

can_bind_estimate(estimate_model, raise_exception: bool = False) bool

Checks if the BillModel can be bound to a given EstimateModel.

Parameters:
  • estimate_model (EstimateModel) – EstimateModel to check against.

  • raise_exception (bool) – If True, raises BillModelValidationError if unable to bind. Else, returns False.

Returns:

True if can bind provided EstimateModel, else False.

Return type:

bool

can_bind_po(po_model, raise_exception: bool = False) bool

Checks if the BillModel can be bound to a given PurchaseOrderModel.

Parameters:
  • po_model (PurchaseOrderModel) – The PurchaseOrderModel to check against.

  • raise_exception (bool) – If True, raises BillModelValidationError if unable to bind, else False.

Returns:

True if can bind provided PurchaseOderModel, else False.

Return type:

bool

can_cancel() bool

Checks if the BillModel can be marked as Canceled status.

Returns:

True if BillModel can be marked as canceled, else False.

Return type:

bool

can_delete() bool

Checks if the BillModel can be deleted.

Returns:

True if BillModel can be deleted, else False.

Return type:

bool

can_draft() bool

Checks if the BillModel can be marked as Draft.

Returns:

True if BillModel can be marked as draft, else False.

Return type:

bool

can_edit_items() bool

Checks if the BillModel item transactions can be edited.

Returns:

True if BillModel items can be edited, else False.

Return type:

bool

can_generate_bill_number() bool

Checks if BillModel can generate its Document Number.

Returns:

True if BillModel can generate its bill_number, else False.

Return type:

bool

can_make_payment() bool

Checks if the BillModel can accept a payment.

Returns:

True if can bind provided PurchaseOderModel, else False.

Return type:

bool

can_migrate() bool

Checks if the BillModel can be migrated.

Returns:

True if BillModel can be migrated, else False.

Return type:

bool

can_migrate_itemtxs() bool

Checks if item transaction list can be migrated.

Return type:

bool

can_pay() bool

Checks if the BillModel can be marked as Paid.

Returns:

True if BillModel can be marked as paid, else False.

Return type:

bool

can_review() bool

Checks if the BillModel can be marked as In Review.

Returns:

True if BillModel can be marked as in review, else False.

Return type:

bool

can_void() bool

Checks if the BillModel can be marked as Void status.

Returns:

True if BillModel can be marked as void, else False.

Return type:

bool

clean(commit: bool = True)

Clean method for BillModel. Results in a DB query if bill number has not been generated and the BillModel is eligible to generate a bill_number.

Parameters:

commit (bool) – If True, commits into DB the generated BillModel number if generated.

configure(entity_slug: str | EntityModel, user_model: User | None = None, date_draft: datetime | date | None = None, ledger_posted: bool = False, ledger_name: str = None, commit: bool = False, commit_ledger: bool = False)

A configuration hook which executes all initial BillModel setup on to the LedgerModel and all initial values of the BillModel. Can only call this method once in the lifetime of a BillModel.

Parameters:
  • date_draft (date) – Optional date to use as Draft Date. Defaults to localdate() if None.

  • entity_slug (str or EntityModel) – The entity slug or EntityModel to associate the Bill with.

  • user_model (UserModel) – The UserModel making the request to check for QuerySet permissions.

  • ledger_posted (bool) – An option to mark the BillModel Ledger as posted at the time of configuration. Defaults to False.

  • ledger_name (str) – Optional additional InvoiceModel ledger name or description.

  • commit (bool) – Saves the current BillModel after being configured.

  • commit_ledger (bool) – Saves the BillModel’s LedgerModel while being configured.

Return type:

A tuple of LedgerModel, BillModel

generate_bill_number(commit: bool = False) str

Atomic Transaction. Generates the next BillModel document number available. The operation will result in two additional queries if the BillModel & LedgerModel is not cached in QuerySet via select_related(‘ledger’).

Parameters:

commit (bool) – Commits transaction into BillModel.

Returns:

A String, representing the generated BillModel instance Document Number.

Return type:

str

get_document_id() str | None

Human-readable document number. Defaults to bill_number.

Returns:

Document Number as a String.

Return type:

str

get_html_amount_due_id() str

Unique amount due HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_html_amount_paid_id() str

Unique amount paid HTML ID

Returns:

HTML ID as a String.

Return type:

str

get_html_form_id() str

Unique BillModel Form HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_html_id() str

Unique BillNumber HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_item_model_qs() ItemModelQuerySet

Fetches the ItemModelQuerySet eligible to itemize.

Return type:

ItemModelQuerySet

get_itemtxs_data(queryset: ItemTransactionModelQuerySet | None = None, aggregate_on_db: bool = False, lazy_agg: bool = False) Tuple[ItemTransactionModelQuerySet, Dict]

Fetches the BillModel Items and aggregates the QuerySet.

Parameters:
  • queryset – Optional pre-fetched ItemModelQueryset to use. Avoids additional DB query if provided.

  • aggregate_on_db (bool) – If True, performs aggregation of ItemsTransactions in the DB resulting in one additional DB query.

Returns:

A tuple

Return type:

ItemTransactionModelQuerySet, dict

get_mark_as_approved_html_id() str

BillModel Mark as Approved HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_approved_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Approved BillModel confirmation message as a String.

Return type:

str

get_mark_as_approved_url(entity_slug: str | None = None) str

BillModel Mark-as-Approved action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

BillModel mark-as-approved action URL.

Return type:

str

get_mark_as_canceled_html_id() str

BillModel Mark as Canceled HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_canceled_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Canceled BillModel confirmation message as a String.

Return type:

str

get_mark_as_canceled_url(entity_slug: str | None = None) str

BillModel Mark-as-Canceled action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

BillModel mark-as-canceled action URL.

Return type:

str

get_mark_as_draft_html_id() str

BillModel Mark as Draft HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_draft_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Draft BillModel confirmation message as a String.

Return type:

str

get_mark_as_draft_url(entity_slug: str | None = None) str

BillModel Mark-as-Draft action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_paid_html_id() str

BillModel Mark as Paid HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_paid_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Paid BillModel confirmation message as a String.

Return type:

str

get_mark_as_paid_url(entity_slug: str | None = None) str

BillModel Mark-as-Paid action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

BillModel mark-as-paid action URL.

Return type:

str

get_mark_as_review_html_id() str

BillModel Mark as In Review HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_review_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Review BillModel confirmation message as a String.

Return type:

str

get_mark_as_review_url(entity_slug: str | None = None) str

BillModel Mark-as-Review action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

BillModel mark-as-review action URL.

Return type:

str

get_mark_as_void_html_id() str

BillModel Mark as Void HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_void_message() str

Internationalized confirmation message with Bill Number.

Returns:

Mark-as-Void BillModel confirmation message as a String.

Return type:

str

get_mark_as_void_url(entity_slug: str | None = None) str

BillModel Mark-as-Void action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Return type:

BillModel mark-as-void action URL.

get_migrate_state_desc() str

Description used when migrating transactions into the LedgerModel.

Returns:

Description as a string.

Return type:

str

get_migration_data(queryset: ItemTransactionModelQuerySet | None = None) ItemTransactionModelQuerySet

Fetches necessary item transaction data to perform a migration into the LedgerModel.

Parameters:

queryset (ItemTransactionModelQuerySet) – Optional pre-fetched ItemModelTransactionQueryset to use. Avoids additional DB query if provided.

get_status_action_date() date

Current status action date.

Returns:

A date. i.e. If status is Approved, return date_approved. If Paid, return date_paid.

Return type:

date

get_terms_start_date() date | None

Date where BillModel term start to apply.

Returns:

A date which represents the start of BillModel terms.

Return type:

date

get_transaction_queryset(annotated: bool = False)

Fetches the TransactionModelQuerySet associated with the BillModel instance.

is_active()

Checks if the BillModel has the potential to impact the books and produce financial statements status.

Returns:

True if BillModel is Active, else False.

Return type:

bool

is_approved() bool

Checks if the BillModel is in Approved status.

Returns:

True if BillModel is Approved, else False.

Return type:

bool

is_canceled() bool

Checks if the BillModel is in Canceled status.

Returns:

True if BillModel is Canceled, else False.

Return type:

bool

is_configured() bool

Determines if the accruable financial instrument is properly configured.

Returns:

True if configured, else False.

Return type:

bool

is_draft() bool

Checks if the BillModel is in Draft status.

Returns:

True if BillModel is Draft, else False.

Return type:

bool

is_paid() bool

Checks if the BillModel is in Paid status.

Returns:

True if BillModel is Paid, else False.

Return type:

bool

is_past_due() bool

Checks if the BillModel is past due.

Returns:

True if BillModel is past due, else False.

Return type:

bool

is_review() bool

Checks if the BillModel is In Review status.

Returns:

True if BillModel is in Review, else False.

Return type:

bool

is_void() bool

Checks if the BillModel is in Void status.

Returns:

True if BillModel is Void, else False.

Return type:

bool

make_payment(payment_amount: Decimal | float | int, payment_date: datetime | date | None = None, commit: bool = False, raise_exception: bool = True)

Makes a payment to the BillModel.

Parameters:
  • payment_amount (Decimal ot float) – The payment amount to process.

  • payment_date (datetime or date.) – Date or timestamp of the payment being applied.

  • commit (bool) – If True, commits the transaction into the DB. Defaults to False.

  • raise_exception (bool) – If True, raises BillModelValidationError if payment exceeds amount due, else False.

Returns:

True if can make payment, else False.

Return type:

bool

mark_as_approved(user_model, entity_slug: str | None = None, date_approved: datetime | date | None = None, commit: bool = False, force_migrate: bool = False, raise_exception: bool = True, **kwargs)

Marks BillModel as Approved.

Parameters:
  • entity_slug – Entity slug associated with the BillModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_approved (date) – BillModel approved date. Defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

  • force_migrate (bool) – Forces migration. True if Accounting Method is Accrual.

mark_as_canceled(date_canceled: date | None = None, commit: bool = False, **kwargs)

Mark BillModel as Canceled.

Parameters:
  • date_canceled (date) – BillModel canceled date. Defaults to localdate() if None.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_draft(date_draft: date | None = None, commit: bool = False, **kwargs)

Marks BillModel as Draft.

Parameters:
  • date_draft (date) – Draft date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_paid(user_model, entity_slug: str | None = None, date_paid: datetime | date | None = None, itemtxs_qs: ItemTransactionModelQuerySet | None = None, commit: bool = False, **kwargs)

Marks BillModel as Paid.

Parameters:
  • entity_slug (str) – Entity slug associated with the BillModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_paid (date) – BillModel paid date. Defaults to localdate() if None.

  • itemtxs_qs (ItemTransactionModelQuerySet) – Pre-fetched ItemTransactionModelQuerySet. Avoids additional DB query. Validated if passed.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_review(commit: bool = False, itemtxs_qs: ItemTransactionModelQuerySet = None, date_in_review: date | None = None, raise_exception: bool = True, **kwargs)

Marks BillModel as In Review.

Parameters:
  • date_in_review (date) – BillModel in review date. Defaults to localdate() if None.

  • itemtxs_qs (ItemTransactionModelQuerySet) – Pre fetched ItemTransactionModelQuerySet to use. Avoids additional DB Query if previously fetched.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

  • raise_exception (bool) – Raises BillModelValidationError if BillModel cannot be marked as in review. Defaults to True.

mark_as_void(user_model, entity_slug: str | None = None, date_void: date | None = None, commit: bool = False, **kwargs)

Marks BillModel as Void. When mark as void, all transactions associated with BillModel are reversed as of the void date.

Parameters:
  • entity_slug (str) – Entity slug associated with the BillModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_void (date) – BillModel void date. Defaults to localdate() if None.

  • commit (bool) – Commits transaction into DB. Defaults to False.

migrate_itemtxs(itemtxs: Dict, operation: str, commit: bool = False)

Migrates a predefined item transaction list.

Parameters:
  • itemtxs (dict) – A dictionary where keys are the document number (invoice/bill number, etc) and values are a dictionary:

  • operation (str) – A choice of ITEMIZE_REPLACE, ITEMIZE_APPEND, ITEMIZE_UPDATE

  • commit (bool) – If True, commits transaction into the DB. Default to False

Returns:

A list of ItemTransactionModel appended or created.

Return type:

list

update_amount_due(itemtxs_qs: ItemTransactionModelQuerySet | List[ItemTransactionModel] | None = None) ItemTransactionModelQuerySet

Updates the BillModel amount due.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet or list of ItemTransactionModel) – Optional pre-fetched ItemTransactionModelQuerySet. Avoids additional DB if provided. Queryset is validated if provided.

Returns:

Newly fetched of previously fetched ItemTransactionModelQuerySet if provided.

Return type:

ItemTransactionModelQuerySet

validate_itemtxs_qs(queryset: ItemTransactionModelQuerySet | List[ItemTransactionModel])

Validates that the entire ItemTransactionModelQuerySet is bound to the BillModel.

Parameters:

queryset (ItemTransactionModelQuerySet or list of ItemTransactionModel.) – ItemTransactionModelQuerySet to validate.

class django_ledger.models.bill.BillModelManager(*args, **kwargs)

A custom defined BillModelManager that will act as an interface to handling the initial DB queries to the BillModel. The default “get_queryset” has been overridden to refer the custom defined “BillModelQuerySet”.

for_entity(entity_slug, user_model) BillModelQuerySet

Fetches a QuerySet of BillModels associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> bill_model_qs = BillModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns:

Returns a BillModelQuerySet with applied filters.

Return type:

BillModelQuerySet

for_user(user_model) BillModelQuerySet

Fetches a QuerySet of BillModels that the UserModel as access to. May include BillModels from multiple Entities.

The user has access to bills if:
  1. Is listed as Manager of Entity.

  2. Is the Admin of the Entity.

Parameters:

user_model – Logged in and authenticated django UserModel instance.

Examples

>>> request_user = request.user
>>> bill_model_qs = BillModel.objects.for_user(user_model=request_user)
Returns:

Returns a BillModelQuerySet with applied filters.

Return type:

BillModelQuerySet

get_queryset()

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class django_ledger.models.bill.BillModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined QuerySet for the BillModel. This implements multiple methods or queries needed to get a filtered QuerySet based on the BillModel status. For example, we might want to have list of bills which are paid, unpaid, due ,overdue, approved or in draft stage. All these separate functions will assist in making such queries and building customized reports.

active()

Active bills are those that are approved or paid, which have impacted or have the potential to impact the Entity’s Ledgers.

Returns:

Returns a QuerySet of active bills only.

Return type:

BillModelQuerySet

approved()

Approved bills are those that have been reviewed and are expected to be paid before the due date.

Returns:

Returns a QuerySet of approved bills only.

Return type:

BillModelQuerySet

canceled()

Canceled bills are those that are discarded during the draft or in review status. These bills never had an impact on the books.

Returns:

Returns a QuerySet of canceled bills only.

Return type:

BillModelQuerySet

draft()

Default status of any bill that is created. Draft bills do not impact the Ledger.

Returns:

Returns a QuerySet of draft bills only.

Return type:

BillModelQuerySet

in_review()

In review bills are those that need additional review or approvals before being approved. In review bills do not impact the Ledger.

Returns:

Returns a QuerySet of bills in review only.

Return type:

BillModelQuerySet

overdue()

Overdue bills are those which due date is in the past.

Returns:

Returns a QuerySet of overdue bills only.

Return type:

BillModelQuerySet

paid()

Paid bills are those that have received 100% of the amount due.

Returns:

Returns a QuerySet of paid bills only.

Return type:

BillModelQuerySet

unpaid()

Unpaid bills are those that are approved but have not received 100% of the amount due. Equivalent to approved().

Returns:

Returns a QuerySet of paid bills only.

Return type:

BillModelQuerySet

void()

Void bills are those that where rolled back after being approved. Void bills rollback all transactions by creating a new set of transactions posted on the date_void.

Returns:

Returns a QuerySet of void bills only.

Return type:

BillModelQuerySet

exception django_ledger.models.bill.BillModelValidationError(message, code=None, params=None)

Estimate Model

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

The EstimateModel provides the means to estimate customer requests, jobs or quotes that may ultimately be considered contracts, if approved. The EstimateModels will estimate revenues and costs associated with a specific scope of work which is documented using ItemTransactionModels.

Once approved, the user may initiate purchase orders, bills and invoices that will be associated with the EstimateModel for tracking purposes. It is however not required to always have an EstimateModel, but recommended in order to be able to produce more specific financial reports associated with a specific scope of work.

class django_ledger.models.estimate.EstimateModel(*args, **kwargs)

Base EstimateModel Class.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.estimate.EstimateModelAbstract(*args, **kwargs)

This is the main abstract class which the EstimateModel database will inherit from. The EstimateModel inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

estimate_number

Auto assigned number at creation by generate_estimate_number() function. Prefix be customized with DJANGO_LEDGER_ESTIMATE_NUMBER_PREFIX setting. Includes a reference to the Fiscal Year and a sequence number. Max Length is 20.

Type:

str

entity

The EntityModel associated with te EntityModel instance.

Type:

EntityModel

customer

The CustomerModel associated with the EstimateModel instance.

Type:

CustomerModel

title

A string representing the name or title of the EstimateModel instance.

Type:

str

status

The status of the EstimateModel instance. Must be one of Draft, In Review, Approved, Completed Void or Canceled.

Type:

str

terms

The contract terms that will be associated with this EstimateModel instance. Choices are Fixed Price, Target Price, Time & Materials and Other.

Type:

str

date_draft

The draft date represents the date when the EstimateModel was first created. Defaults to localdate.

Type:

date

date_in_review

The in review date represents the date when the EstimateModel was marked as In Review status. Will be null if EstimateModel is canceled during draft status. Defaults to localdate.

Type:

date

date_approved

The approved date represents the date when the EstimateModel was approved. Will be null if EstimateModel is canceled. Defaults to localdate.

Type:

date

date_completed

The paid date represents the date when the EstimateModel was completed and fulfilled. Will be null if EstimateModel is canceled. Defaults to localdate.

Type:

date

date_void

The void date represents the date when the EstimateModel was void, if applicable. Will be null unless EstimateModel is void. Defaults to localdate.

Type:

date

date_canceled

The canceled date represents the date when the EstimateModel was canceled, if applicable. Will be null unless EstimateModel is canceled. Defaults to localdate.

Type:

date

revenue_estimate

The total estimated revenue of the EstimateModel instance.

Type:

Decimal

labor_estimate

The total labor costs estimate of the EstimateModel instance.

Type:

Decimal

material_estimate

The total material costs estimate of the EstimateModel instance.

Type:

Decimal

equipment_estimate

The total equipment costs estimate of the EstimateModel instance.

Type:

Decimal

other_estimate

the total miscellaneous costs estimate of the EstimateModel instance.

Type:

Decimal

can_approve()

Determines if the EstimateModel can be marked as approved.

Returns:

True if EstimateModel can be marked as approved, else False.

Return type:

bool

can_bind()

Determines if the EstimateModel can be bound to a set of POs, Bills or Invoices.

Returns:

True if EstimateModel can be bound, else False.

Return type:

bool

can_cancel()

Determines if the EstimateModel can be marked as canceled.

Returns:

True if EstimateModel can be marked as canceled, else False.

Return type:

bool

can_complete()

Determines if the EstimateModel can be marked as completed.

Returns:

True if EstimateModel can be marked as completed, else False.

Return type:

bool

can_draft() bool

Determines if the EstimateModel can be marked as Draft.

Returns:

True if EstimateModel can be marked as draft, else False.

Return type:

bool

can_generate_estimate_number()

Determines if the EstimateModel can generate its own estimate number..

Returns:

True if EstimateModel can generate the estimate number, else False.

Return type:

bool

can_migrate_itemtxs() bool

Checks if item transaction list can be migrated.

Return type:

bool

can_review()

Determines if the EstimateModel can be marked as In Review.

Returns:

True if EstimateModel can be marked as In Review, else False.

Return type:

bool

can_update_items()

Determines if the EstimateModel item transactions can be edited or changed.

Returns:

True if EstimateModel item transactions can be edited or changed, else False.

Return type:

bool

can_void()

Determines if the EstimateModel can be marked as void.

Returns:

True if EstimateModel can be marked as void, else False.

Return type:

bool

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

configure(entity_slug: EntityModel | UUID | str, customer_model: CustomerModel, user_model: User | None = None, date_draft: date | None = None, estimate_title: str | None = None, commit: bool = False, raise_exception: bool = True)

A configuration hook which executes all initial EstimateModel setup. Can only call this method once in the lifetime of a EstimateModel.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel to associate the Bill with.

  • user_model – The UserModel making the request to check for QuerySet permissions.

  • date_draft (date) – The draft date to use. If None defaults to localdate().

  • customer_model (CustomerModel) – The CustomerModel to be associated with this EstimateModel instance.

  • commit (bool) – Saves the current EstimateModel after being configured.

  • estimate_title (str) – Optional EstimateModel title.

  • raise_exception (bool) – If True, raises EstimateModelValidationError when model is already configured.

Returns:

The configured EstimateModel instance.

Return type:

EstimateModel

generate_estimate_number(commit: bool = False) str

Atomic Transaction. Generates the next EstimateModel document number available. The operation will result in two additional queries if the EntityModel is not cached in QuerySet via select_related(‘entity’).

Parameters:

commit (bool) – Commits transaction into BillModel.

Returns:

A String, representing the generated BillModel instance Document Number.

Return type:

str

get_contract_summary(po_qs: PurchaseOrderModelQuerySet | None = None, bill_qs: BillModelQuerySet | None = None, invoice_qs: InvoiceModelQuerySet | None = None) dict

Computes an aggregate of all related ItemTransactionModels summarizing original contract amounts, amounts authorized, amounts billed and amount invoiced.

Parameters:
Returns:

A dictionary of aggregated values.

Return type:

dict

get_cost_estimate(as_float: bool = False) float | Decimal

Calculates the total EstimateModel cost by summing all individual cost components: Labor, Material, Equipment & Other costs.

Parameters:

as_float (bool) – If True, will return value as float, else as Decimal.

Returns:

The total EstimateModel cost.

Return type:

Decimal or float

get_gross_margin_estimate(as_percent: bool = False, raise_exception: bool = False) float

Computes the EstimateModel gross margin.

Parameters:
  • as_percent (bool) – If True, computes gross margin as percent.

  • raise_exception (bool)

Returns:

The EstimateModel gross margin.

Return type:

float

get_item_model_qs() ItemModelQuerySet

Fetches the ItemModelQuerySet eligible to itemize.

Return type:

ItemModelQuerySet

get_itemtxs_annotation(itemtxs_qs: ItemTransactionModelQuerySet | None = None)

Gets an annotated ItemTransactionModelQuerySet with additional average unit cost & revenue.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet) – Prefetched ItemTransactionModelQuerySet if any. If None a new queryset will be evaluated. Will be validated if provided.

Returns:

The original ItemTransactionModelQuerySet and the annotated ItemTransactionModelQuerySet.

Return type:

tuple

get_itemtxs_data(queryset: ItemTransactionModelQuerySet | List[ItemTransactionModel] | None = None, aggregate_on_db: bool = False, lazy_agg: bool = False)

Returns all ItemTransactionModels associated with the EstimateModel and a total aggregate.

Parameters:

queryset (ItemTransactionModelQuerySet) – ItemTransactionModelQuerySet to use. Avoids additional DB query if provided. Validated if provided.

Return type:

ItemTransactionModelQuerySet

get_mark_as_approved_html_id()

EstimateModel Mark as Approved HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_approved_message()

EstimateModel Mark as Approved Message.

Returns:

Message as a String

Return type:

str

get_mark_as_approved_url()

EstimateModel Mark as Approved URL.

Returns:

URL as a String

Return type:

str

get_mark_as_canceled_html_id()

EstimateModel Mark as Canceled HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_canceled_message()

EstimateModel Mark as Canceled Message.

Returns:

Message as a String

Return type:

str

get_mark_as_canceled_url()

EstimateModel Mark as Canceled URL.

Returns:

URL as a String

Return type:

str

get_mark_as_completed_html_id()

EstimateModel Mark as Complete HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_completed_message()

EstimateModel Mark as Completed Message.

Returns:

Message as a String

Return type:

str

get_mark_as_completed_url()

EstimateModel Mark as Completed URL.

Returns:

URL as a String

Return type:

str

get_mark_as_draft_html_id()

EstimateModel Mark as Draft HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_draft_message()

EstimateModel Mark as Draft Message.

Returns:

Message as a String

Return type:

str

get_mark_as_draft_url()

EstimateModel Mark as Draft URL.

Returns:

URL as a String

Return type:

str

get_mark_as_review_html_id()

EstimateModel Mark as Review HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_review_message()

EstimateModel Mark as In Review Message.

Returns:

Message as a String

Return type:

str

get_mark_as_review_url()

EstimateModel Mark as In Review URL.

Returns:

URL as a String

Return type:

str

get_mark_as_void_html_id()

EstimateModel Mark as Void HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_void_message()

EstimateModel Mark as Void message.

Returns:

Message as a String

Return type:

str

get_mark_as_void_url()

EstimateModel Mark as Void URL.

Returns:

URL as a String

Return type:

str

get_profit_estimate(as_float: bool = False)

Calculates the total EstimateModel profit estimate.

Parameters:

as_float (bool) – If True, will return value as float, else as Decimal.

Returns:

The total EstimateModel profit.

Return type:

Decimal or float

get_revenue_estimate(as_float: bool = False)

Calculates the total EstimateModel revenue.

Parameters:

as_float (bool) – If True, will return value as float, else as Decimal.

Returns:

The total EstimateModel revenue.

Return type:

Decimal or float

get_status_action_date() date

The date when the latest status took place.

Examples

If EstimateModel is Draft, will return date_draft. If EstimateModel is In Review, will return date_in_review. If EstimateModel is Approved, will return date_approved.

Returns:

The latest action date.

Return type:

date

is_approved() bool

Determines if the EstimateModel is in Approved status.

Returns:

True if EstimateModel is in Approved status, else False.

Return type:

bool

is_canceled() bool

Determines if the EstimateModel is in Canceled status.

Returns:

True if EstimateModel is in Canceled status, else False.

Return type:

bool

is_completed() bool

Determines if the EstimateModel is in Completed status.

Returns:

True if EstimateModel is in Completed status, else False.

Return type:

bool

is_configured() bool

Determines if the EstimateModel is configured.

Returns:

True if EstimateModel is configured, else False.

Return type:

bool

is_contract()

Determines if the EstimateModel is considered a Contract.

Returns:

True if EstimateModel is a Contract, else False.

Return type:

bool

is_draft() bool

Determines if the EstimateModel is in Draft status.

Returns:

True if EstimateModel is in Draft status, else False.

Return type:

bool

is_review() bool

Determines if the EstimateModel is In Review status.

Returns:

True if EstimateModel is In Review status, else False.

Return type:

bool

is_void()

Determines if the EstimateModel is in Void status.

Returns:

True if EstimateModel is in Void status, else False.

Return type:

bool

mark_as_approved(commit=False, date_approved: date | None = None, raise_exception: bool = True, **kwargs)

Marks the current EstimateModel instance as Approved.

Parameters:
  • commit (bool) – Commits transaction into current EstimateModel instance.

  • date_approved (date) – Optional date when EstimateModel instance is Approved. Defaults to localdate().

mark_as_canceled(commit: bool = False, date_canceled: date | None = None, raise_exception: bool = True, **kwargs)

Marks the current EstimateModel instance as Canceled.

Parameters:
  • commit (bool) – Commits transaction into current EstimateModel instance.

  • date_canceled (date) – Optional date when EstimateModel instance is canceled. Defaults to localdate().

mark_as_completed(commit=False, date_completed: date | None = None, raise_exception: bool = True, **kwargs)

Marks the current EstimateModel instance as Completed.

Parameters:
  • commit (bool) – Commits transaction into current EstimateModel instance.

  • date_completed (date) – Optional date when EstimateModel instance is completed. Defaults to localdate().

mark_as_draft(commit: bool = False, raise_exception: bool = True, **kwargs)

Marks the current EstimateModel instance as Draft.

Parameters:

commit (bool) – Commits transaction into current EstimateModel instance.

mark_as_review(itemtxs_qs: ItemTransactionModelQuerySet | None = None, date_in_review: date | None = None, raise_exception: bool = True, commit: bool = True, **kwargs)

Marks the current EstimateModel instance as In Review.

Parameters:
  • commit (bool) – Commits transaction into current EstimateModel instance.

  • itemtxs_qs (ItemTransactionModelQuerySet) – Optional, pre-fetched ItemTransactionModelQuerySet. Avoids additional DB query. Validated if provided.

  • date_in_review (date) – Optional date when EstimateModel instance is In Review. Defaults to localdate().

mark_as_void(commit: bool = False, date_void: date | None = None, raise_exception: bool = True, **kwargs)

Marks the current EstimateModel instance as Void.

Parameters:
  • commit (bool) – Commits transaction into current EstimateModel instance.

  • date_void (date) – Optional date when EstimateModel instance is void. Defaults to localdate().

migrate_itemtxs(itemtxs: Dict, operation: str, commit: bool = False)

Migrates a predefined item transaction list.

Parameters:
  • itemtxs (dict) – A dictionary where keys are the document number (invoice/bill number, etc) and values are a dictionary:

  • operation (str) – A choice of ITEMIZE_REPLACE, ITEMIZE_APPEND, ITEMIZE_UPDATE

  • commit (bool) – If True, commits transaction into the DB. Default to False

Returns:

A list of ItemTransactionModel appended or created.

Return type:

list

save(**kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The ‘force_insert’ and ‘force_update’ parameters can be used to insist that the “save” must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

update_cost_estimate(itemtxs_qs: ItemTransactionModelQuerySet | None = None, commit: bool = False)

Updates the cost estimate of the EstimateModel instance.

Parameters:
  • itemtxs_qs (ItemTransactionModelQuerySet) – Prefetched ItemTransactionModelQuerySet. A new ItemTransactionModelQuerySet will be fetched from DB if not provided. If provided will be validated.

  • commit (bool) – If True, the new revenue estimate will be committed into the DB.

update_revenue_estimate(itemtxs_qs: ItemTransactionModelQuerySet | None = None, commit: bool = False)

Updates the revenue estimate of the EstimateModel instance.

Parameters:
  • itemtxs_qs (ItemTransactionModelQuerySet) – Prefetched ItemTransactionModelQuerySet. A new ItemTransactionModelQuerySet will be fetched from DB if not provided. If provided will be validated.

  • commit (bool) – If True, the new revenue estimate will be committed into the DB.

validate_bill_queryset(bill_qs: BillModelQuerySet) BillModelQuerySet

Validates a prefetched BillModelQuerySet against the EstimateModel instance.

Parameters:

bill_qs (BillModelQuerySet) – The BillModelQuerySet to validate

Returns:

The validated BillModelQuerySet.

Return type:

BillModelQuerySet

validate_invoice_queryset(invoice_qs: InvoiceModelQuerySet) InvoiceModelQuerySet

Validates a prefetched InvoiceModelQuerySet against the EstimateModel instance.

Parameters:

invoice_qs (InvoiceModelQuerySet) – The InvoiceModelQuerySet to validate

Returns:

The validated InvoiceModelQuerySet.

Return type:

InvoiceModelQuerySet

validate_item_transaction_qs(itemtxs_qs: ItemTransactionModelQuerySet | List[ItemTransactionModel])

Validates that the entire ItemTransactionModelQuerySet is bound to the BillModel.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet) – ItemTransactionModelQuerySet to validate.

validate_itemtxs_qs(queryset: ItemTransactionModelQuerySet | List[ItemTransactionModel])

Validates that the entire ItemTransactionModelQuerySet is bound to the EstimateModel.

Parameters:

queryset (ItemTransactionModelQuerySet or list of ItemTransactionModel.) – ItemTransactionModelQuerySet to validate.

validate_po_queryset(po_qs: PurchaseOrderModelQuerySet) PurchaseOrderModelQuerySet

Validates a prefetched PurchaseOrderModelQuerySet against the EstimateModel instance.

Parameters:

po_qs (PurchaseOrderModelQuerySet) – The PurchaseOrderModelQuerySet to validate

Returns:

The validated PurchaseOrderModelQuerySet.

Return type:

PurchaseOrderModelQuerySet

class django_ledger.models.estimate.EstimateModelManager(*args, **kwargs)

A custom defined EstimateModelManager that that implements custom QuerySet methods related to the EstimateModel.

for_entity(entity_slug: EntityModel | str, user_model)

Fetches a QuerySet of EstimateModels associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Returns:

Returns a EstimateModelQuerySet with applied filters.

Return type:

EstimateModelQuerySet

class django_ledger.models.estimate.EstimateModelQuerySet(model=None, query=None, using=None, hints=None)

A custom-defined LedgerModelManager that implements custom QuerySet methods related to the EstimateModel.

approved()

Approved Estimates or Sales Orders are those that have been approved or completed.

Returns:

A EstimateModelQuerySet with applied filters.

Return type:

EstimateModelQuerySet

contracts()

A contract are Estimates or Sales Orders are those that have been approved or completed.

Returns:

A EstimateModelQuerySet with applied filters. Equivalent to approve.

Return type:

EstimateModelQuerySet

estimates()

Estimates or Sales Orders are those that have not been approved or completed.

Returns:

A EstimateModelQuerySet with applied filters. Equivalent to not approved.

Return type:

EstimateModelQuerySet

not_approved()

Not approved Estimates or Sales Orders are those that have not been approved or completed.

Returns:

A EstimateModelQuerySet with applied filters.

Return type:

EstimateModelQuerySet

exception django_ledger.models.estimate.EstimateModelValidationError(message, code=None, params=None)

Purchase Order Model

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

A purchase order is a commercial source document that is issued by a business purchasing department when placing an order with its vendors or suppliers. The document indicates the details on the items that are to be purchased, such as the types of goods, quantity, and price. In simple terms, it is the contract drafted by the buyer when purchasing goods from the seller.

The PurchaseOrderModel is designed to track the status of a Purchase Order and all its items. The PurchaseOrderModel starts in draft model by default and goes through different states including InReview, Approved, Fulfilled, Canceled and Void. The PurchaseOrderModel also keeps track of when these states take place.

class django_ledger.models.purchase_order.PurchaseOrderModel(*args, **kwargs)

Purchase Order Base Model

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.purchase_order.PurchaseOrderModelAbstract(*args, **kwargs)

The base implementation of the PurchaseOrderModel.

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

po_number

A unique human-readable and sequential PO Number identifier. Automatically generated.

Type:

str

po_title

The PurchaseOrderModel instance title.

Type:

str

po_status

One of PO_STATUS values representing the current status of the PurchaseOrderModel instance.

Type:

str

po_amount

The total value of the PurchaseOrderModel instance.

Type:

Decimal

po_amount_received

The PurchaseOrderModel instance total value received to date. Cannot be greater than PO amount.

Type:

Decimal

entity

The EntityModel associated with the PurchaseOrderModel instance.

Type:

EntityModel

date_draft

The draft date represents the date when the PurchaseOrderModel was first created. Defaults to localdate.

Type:

date

date_in_review

The in review date represents the date when the PurchaseOrderModel was marked as In Review status. Will be null if PurchaseOrderModel is canceled during draft status. Defaults to localdate.

Type:

date

date_approved

The approved date represents the date when the PurchaseOrderModel was approved. Will be null if PurchaseOrderModel is canceled. Defaults to localdate.

Type:

date

date_fulfilled

The paid date represents the date when the PurchaseOrderModel was fulfilled and po_amount_received equals po_amount. Will be null if PurchaseOrderModel is canceled. Defaults to localdate.

Type:

date

date_void

The void date represents the date when the PurchaseOrderModel was void, if applicable. Will be null unless PurchaseOrderModel is void. Defaults to localdate.

Type:

date

date_canceled

The canceled date represents the date when the PurchaseOrderModel was canceled, if applicable. Will be null unless PurchaseOrderModel is canceled. Defaults to localdate.

Type:

date

po_items

A foreign key reference to the list of ItemTransactionModel that make the PurchaseOrderModel amount.

ce_model

A foreign key reference to the EstimateModel associated with the PurchaseOrderModel, if any.

Type:

EstimateModel

PO_STATUS_CANCELED = 'canceled'

The different valid PO Status and their representation in the Database

action_bind_estimate(estimate_model, commit: bool = False)

Binds a specific EstimateModel to the PurchaseOrderModel instance.

Parameters:
  • estimate_model (EstimateModel) – The EstimateModel to bind.

  • commit (bool) – Commits the changes in the Database, if True. Defaults to False.

can_approve() bool

Checks if the PurchaseOrderModel can be marked as Approved.

Returns:

True if PurchaseOrderModel can be marked as Approved, else False.

Return type:

bool

can_bind_estimate(estimate_model, raise_exception: bool = False) bool

Checks if the PurchaseOrderModel ican be bound to an EstimateModel.

Returns:

True if PurchaseOrderModel can be bound to an EstimateModel, else False.

Return type:

bool

can_cancel() bool

Checks if the PurchaseOrderModel can be marked as Canceled.

Returns:

True if PurchaseOrderModel can be marked as Canceled, else False.

Return type:

bool

can_delete() bool

Checks if the PurchaseOrderModel can be deleted.

Returns:

True if PurchaseOrderModel can be deleted, else False.

Return type:

bool

can_draft() bool

Checks if the PurchaseOrderModel can be marked as Draft.

Returns:

True if PurchaseOrderModel can be marked as Draft, else False.

Return type:

bool

can_edit_items() bool

Checks if the PurchaseOrderModel items can be edited.

Returns:

True if PurchaseOrderModel items can be edited, else False.

Return type:

bool

can_fulfill() bool

Checks if the PurchaseOrderModel can be marked as Fulfilled.

Returns:

True if PurchaseOrderModel can be marked as Fulfilled, else False.

Return type:

bool

can_generate_po_number()

Checks if PurchaseOrderModel can generate its Document Number.

Returns:

True if PurchaseOrderModel can generate its po_number, else False.

Return type:

bool

can_migrate_itemtxs() bool

Checks if item transaction list can be migrated.

Return type:

bool

can_review() bool

Checks if the PurchaseOrderModel can be marked as In Review.

Returns:

True if PurchaseOrderModel can be marked as In Review, else False.

Return type:

bool

can_void() bool

Checks if the PurchaseOrderModel can be marked as Void.

Returns:

True if PurchaseOrderModel can be marked as Void, else False.

Return type:

bool

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

configure(entity_slug: str | EntityModel, po_title: str | None = None, user_model: User | None = None, draft_date: date | None = None, estimate_model=None, commit: bool = False)

A configuration hook which executes all initial PurchaseOrderModel setup on to the EntityModel and all initial values of the EntityModel. Can only call this method once in the lifetime of a PurchaseOrderModel.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel to associate the Bill with.

  • user_model – The UserModel making the request to check for QuerySet permissions.

  • ledger_posted – An option to mark the BillModel Ledger as posted at the time of configuration. Defaults to False.

  • bill_desc (str) – An optional description appended to the LedgerModel name.

  • commit (bool) – Saves the current BillModel after being configured.

Returns:

The configured PurchaseOrderModel instance.

Return type:

PurchaseOrderModel

generate_po_number(commit: bool = False) str

Atomic Transaction. Generates the next PurchaseOrder document number available.

Parameters:

commit (bool) – Commits transaction into PurchaseOrderModel.

Returns:

A String, representing the generated or current PurchaseOrderModel instance Document Number.

Return type:

str

get_item_model_qs() ItemModelQuerySet

Fetches the ItemModelQuerySet eligible to itemize.

Return type:

ItemModelQuerySet

get_itemtxs_data(queryset: ItemTransactionModelQuerySet | List[ItemTransactionModel] | None = None, aggregate_on_db: bool = False, lazy_agg: bool = False) Tuple

Fetches the PurchaseOrderModel Items and aggregates the QuerySet.

Parameters:
  • queryset (ItemTransactionModelQuerySet) – Optional pre-fetched ItemModelQueryset to use. Avoids additional DB query if provided. Validated if provided.

  • aggregate_on_db (bool) – If True, performs aggregation of ItemsTransactions in the DB resulting in one additional DB query.

Returns:

A tuple

Return type:

ItemTransactionModelQuerySet, dict

get_mark_as_approved_html_id()

PurchaseOrderModel Mark as Approved HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_approved_message()

PurchaseOrderModel Mark as Approved Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_approved_url()

PurchaseOrderModel Mark as Approved URL ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_canceled_html_id()

PurchaseOrderModel Mark as Canceled HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_canceled_message()

PurchaseOrderModel Mark as Canceled Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_canceled_url()

PurchaseOrderModel Mark as Canceled URL ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_draft_html_id()

PurchaseOrderModel Mark as Draft HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_draft_message()

PurchaseOrderModel Mark as Draft Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_draft_url()

PurchaseOrderModel Mark as Draft URL ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_fulfilled_html_id()

PurchaseOrderModel Mark as Fulfilled HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_fulfilled_message()

PurchaseOrderModel Mark as Fulfilled Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_fulfilled_url()

PurchaseOrderModel Mark as Fulfilled URL ID Tag.

Returns:

URL as a String.

Return type:

str

get_mark_as_review_html_id()

PurchaseOrderModel Mark as In Review HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_review_message()

PurchaseOrderModel Mark as Review Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_review_url()

PurchaseOrderModel Mark as In Review URL ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_void_html_id()

PurchaseOrderModel Mark as Void HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_void_message()

PurchaseOrderModel Mark as Void Message.

Returns:

Message as a String.

Return type:

str

get_mark_as_void_url()

PurchaseOrderModel Mark as Void URL ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_po_bill_queryset() BillModelQuerySet

Fetches a BillModelQuerySet of all BillModels associated with the PurchaseOrderModel instance.

Return type:

BillModelQuerySet

get_status_action_date()

Current status action date.

Returns:

A date. i.e. If status is Approved, return date_approved. If In Review, return date_in_review.

Return type:

date

is_approved() bool

Checks if the PurchaseOrderModel is in Approved status.

Returns:

True if PurchaseOrderModel is Approved, else False.

Return type:

bool

is_canceled() bool

Checks if the PurchaseOrderModel is in Canceled status.

Returns:

True if PurchaseOrderModel is in Canceled, else False.

Return type:

bool

is_contract_bound()

Checks if the PurchaseOrderModel is bound to an EstimateModel.

Returns:

True if PurchaseOrderModel is bound to an EstimateModel, else False.

Return type:

bool

is_draft() bool

Checks if the PurchaseOrderModel is in Draft status.

Returns:

True if PurchaseOrderModel is Draft, else False.

Return type:

bool

is_fulfilled() bool

Checks if the PurchaseOrderModel is in Fulfilled status.

Returns:

True if PurchaseOrderModel is in Fulfilled status, else False.

Return type:

bool

is_review() bool

Checks if the PurchaseOrderModel is in Review status.

Returns:

True if PurchaseOrderModel is Review, else False.

Return type:

bool

is_void() bool

Checks if the PurchaseOrderModel is in Void status.

Returns:

True if PurchaseOrderModel is Void, else False.

Return type:

bool

mark_as_approved(date_approved: date | None = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as Approved.

Parameters:
  • date_approved (date) – Approved date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_canceled(date_canceled: date | None = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as Canceled.

Parameters:
  • date_canceled (date) – Canceled date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_draft(date_draft: date | None = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as Draft.

Parameters:
  • date_draft (date) – Draft date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_fulfilled(date_fulfilled: date = None, po_items: ItemTransactionModelQuerySet | List[ItemTransactionModel] = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as Fulfilled.

Parameters:
  • date_fulfilled (date) – Fulfilled date. If None, defaults to localdate().

  • po_items (ItemTransactionModelQuerySet or list of ItemTransactionModel.) – Pre-fetched ItemTransactionModelQuerySet or list of ItemTransactionModel. Validated if provided.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_review(date_in_review: date | None = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as In Review.

Parameters:
  • date_in_review (date) – Draft date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_void(void_date: date | None = None, commit: bool = False, **kwargs)

Marks PurchaseOrderModel as Fulfilled.

Parameters:
  • void_date (date) – Void date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

migrate_itemtxs(itemtxs: Dict, operation: str, commit: bool = False)

Migrates a predefined item transaction list.

Parameters:
  • itemtxs (dict) – A dictionary where keys are the document number (invoice/bill number, etc) and values are a dictionary:

  • operation (str) – A choice of ITEMIZE_REPLACE, ITEMIZE_APPEND, ITEMIZE_UPDATE

  • commit (bool) – If True, commits transaction into the DB. Default to False

Returns:

A list of ItemTransactionModel appended or created.

Return type:

list

update_state(itemtxs_qs: ItemTransactionModelQuerySet | List[ItemTransactionModel] | None = None) Tuple

Updates the state of the PurchaseOrderModel.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet or list of ItemTransactionModel)

Returns:

A tuple of ItemTransactionModels and Aggregation

Return type:

tuple

validate_item_transaction_qs(queryset: ItemTransactionModelQuerySet | List[ItemTransactionModel])

Validates that the entire ItemTransactionModelQuerySet is bound to the PurchaseOrderModel.

Parameters:

queryset (ItemTransactionModelQuerySet or list of ItemTransactionModel.) – ItemTransactionModelQuerySet to validate.

class django_ledger.models.purchase_order.PurchaseOrderModelManager(*args, **kwargs)

A custom defined PurchaseOrderModel Manager.

for_entity(entity_slug, user_model) PurchaseOrderModelQuerySet

Fetches a QuerySet of PurchaseOrderModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Returns:

A PurchaseOrderModelQuerySet with applied filters.

Return type:

PurchaseOrderModelQuerySet

class django_ledger.models.purchase_order.PurchaseOrderModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined PurchaseOrderModel QuerySet.

active()

Filters the QuerySet to include Active PurchaseOrderModels only. Active PurchaseOrderModels are either approved or fulfilled, which are those that may contain associated transactions on the Ledger.

Returns:

A PurchaseOrderModelQuerySet with applied filters.

Return type:

PurchaseOrderModelQuerySet

approved()

Filters the QuerySet to include Approved PurchaseOrderModels only.

Returns:

A PurchaseOrderModelQuerySet with applied filters.

Return type:

PurchaseOrderModelQuerySet

fulfilled()

Filters the QuerySet to include Fulfilled PurchaseOrderModels only.

Returns:

A PurchaseOrderModelQuerySet with applied filters.

Return type:

PurchaseOrderModelQuerySet

exception django_ledger.models.purchase_order.PurchaseOrderModelValidationError(message, code=None, params=None)

Invoice Model

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

This module implements the InvoiceModel, which represents the Sales Invoice/ Sales Invoice/ Tax Invoice/ Proof of Sale which the EntityModel issues to its customers for the supply of goods or services. The model manages all the Sales Invoices which are issued by the EntityModel. In addition to tracking the invoice amount , it tracks the receipt and due amount.

Examples

>>> user_model = request.user  # django UserModel
>>> entity_slug = kwargs['entity_slug'] # may come from view kwargs
>>> invoice_model = InvoiceModel()
>>> ledger_model, invoice_model = invoice_model.configure(entity_slug=entity_slug, user_model=user_model)
>>> invoice_model.save()
class django_ledger.models.invoice.InvoiceModel(*args, **kwargs)

Base Invoice Model from Abstract.

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.invoice.InvoiceModelAbstract(*args, **kwargs)

This is the main abstract class which the InvoiceModel database will inherit from. The InvoiceModel inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

invoice_number

Auto assigned number at creation by generate_invoice_number() function. Prefix be customized with DJANGO_LEDGER_INVOICE_NUMBER_PREFIX setting. Includes a reference to the Fiscal Year, Entity Unit and a sequence number. Max Length is 20.

Type:

str

invoice_status

Current status of the InvoiceModel. Must be one of the choices as mentioned under “INVOICE_STATUS”. By default, the status will be “Draft”.

Type:

str

customer

This is the foreign key reference to the CustomerModel from whom the purchase has been made.

Type:

CustomerModel

additional_info

Any additional metadata about the InvoiceModel may be stored here as a dictionary object. The data is serialized and stored as a JSON document in the Database.

Type:

dict

invoice_items

A foreign key reference to the list of ItemTransactionModel that make the invoice amount.

ce_model

A foreign key to the InvoiceModel associated EstimateModel for overall Job/Contract tracking.

Type:

EstimateModel

date_draft

The draft date represents the date when the InvoiceModel was first created. Defaults to localdate.

Type:

date

date_in_review

The in review date represents the date when the InvoiceModel was marked as In Review status. Will be null if InvoiceModel is canceled during draft status. Defaults to localdate.

Type:

date

date_approved

The approved date represents the date when the InvoiceModel was approved. Will be null if InvoiceModel is canceled. Defaults to localdate.

Type:

date

date_paid

The paid date represents the date when the InvoiceModel was paid and amount_due equals amount_paid. Will be null if InvoiceModel is canceled. Defaults to localdate.

Type:

date

date_void

The void date represents the date when the InvoiceModel was void, if applicable. Will be null unless InvoiceModel is void. Defaults to localdate.

Type:

date

date_canceled

The canceled date represents the date when the InvoiceModel was canceled, if applicable. Will be null unless InvoiceModel is canceled. Defaults to localdate.

Type:

date

INVOICE_STATUS = [('draft', 'Draft'), ('in_review', 'In Review'), ('approved', 'Approved'), ('paid', 'Paid'), ('void', 'Void'), ('canceled', 'Canceled')]

The different invoice status options and their representation in the Database.

bind_estimate(estimate_model, commit: bool = False)

Binds InvoiceModel to a given EstimateModel. Raises ValueError if EstimateModel cannot be bound.

Parameters:
  • estimate_model (EstimateModel) – EstimateModel to bind.

  • raise_exception (bool) – Raises InvoiceModelValidationError if unable to bind EstimateModel.

  • commit (bool) – Commits transaction into current InvoiceModel.

can_approve()

Checks if the InvoiceModel can be marked as Approved.

Returns:

True if InvoiceModel can be marked as approved, else False.

Return type:

bool

can_bind_estimate(estimate_model, raise_exception: bool = False) bool

Checks if the InvoiceModel can be bound to a given EstimateModel.

Parameters:
  • estimate_model (EstimateModel) – EstimateModel to check against.

  • raise_exception (bool) – If True, raises InvoiceModelValidationError if unable to bind. Else, returns False.

Returns:

True if can bind provided EstimateModel, else False.

Return type:

bool

can_cancel()

Checks if the InvoiceModel can be marked as Canceled status.

Returns:

True if InvoiceModel can be marked as canceled, else False.

Return type:

bool

can_delete()

Checks if the InvoiceModel can be deleted.

Returns:

True if InvoiceModel can be deleted, else False.

Return type:

bool

can_draft()

Checks if the InvoiceModel can be marked as Draft.

Returns:

True if InvoiceModel can be marked as draft, else False.

Return type:

bool

can_edit_items()

Checks if the InvoiceModel item transactions can be edited.

Returns:

True if InvoiceModel items can be edited, else False.

Return type:

bool

can_generate_invoice_number()

Checks if InvoiceModel can generate its Document Number.

Returns:

True if InvoiceModel can generate its invoice_number, else False.

Return type:

bool

can_make_payment() bool

Checks if the BillModel can accept a payment.

Returns:

True if can bind provided PurchaseOderModel, else False.

Return type:

bool

can_migrate()

Checks if the InvoiceModel can be migrated.

Returns:

True if InvoiceModel can be migrated, else False.

Return type:

bool

can_migrate_itemtxs() bool

Checks if item transaction list can be migrated.

Return type:

bool

can_pay()

Checks if the InvoiceModel can be marked as Paid.

Returns:

True if InvoiceModel can be marked as paid, else False.

Return type:

bool

can_review()

Checks if the InvoiceModel can be marked as In Review.

Returns:

True if InvoiceModel can be marked as in review, else False.

Return type:

bool

can_void()

Checks if the InvoiceModel can be marked as Void status.

Returns:

True if InvoiceModel can be marked as void, else False.

Return type:

bool

clean(commit: bool = True)

Clean method for InvoiceModel. Results in a DB query if invoice number has not been generated and the InvoiceModel is eligible to generate an invoice_number.

Parameters:

commit (bool) – If True, commits into DB the generated InvoiceModel number if generated.

configure(entity_slug: EntityModel | str, user_model: User | None = None, date_draft: date | None = None, ledger_posted: bool = False, ledger_name: str | None = None, commit: bool = False, commit_ledger: bool = False)

A configuration hook which executes all initial InvoiceModel setup on to the LedgerModel and all initial values of the InvoiceModel. Can only call this method once in the lifetime of a InvoiceModel.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel to associate the Invoice with.

  • user_model (UserModel) – The UserModel making the request to check for QuerySet permissions.

  • ledger_posted (bool) – An option to mark the InvoiceModel Ledger as posted at the time of configuration. Defaults to False.

  • ledger_name (str) – Optional additional InvoiceModel ledger name or description.

  • invoice_desc (str) – An optional description appended to the LedgerModel name.

  • commit (bool) – Saves the current InvoiceModel after being configured.

  • commit_ledger (bool) – Saves the InvoiceModel’s LedgerModel while being configured.

Return type:

A tuple of LedgerModel, InvoiceModel

generate_invoice_number(commit: bool = False) str

Atomic Transaction. Generates the next InvoiceModel document number available. The operation will result in two additional queries if the InvoiceModel & LedgerModel is not cached in QuerySet via select_related(‘ledger’).

Parameters:

commit (bool) – Commits transaction into InvoiceModel.

Returns:

A String, representing the generated InvoiceModel instance Document Number.

Return type:

str

get_document_id()

Human-readable document number. Defaults to invoice_number.

Returns:

Document Number as a String.

Return type:

str

get_html_amount_due_id()

Unique amount due HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_html_amount_paid_id()

Unique amount paid HTML ID

Returns:

HTML ID as a String.

Return type:

str

get_html_form_id()

Unique InvoiceModel Form HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_html_id()

Unique InvoiceNumber HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_item_model_qs() ItemModelQuerySet

Fetches the ItemModelQuerySet eligible to itemize.

Return type:

ItemModelQuerySet

get_itemtxs_data(queryset: ItemTransactionModelQuerySet = None, aggregate_on_db: bool = False, lazy_agg: bool = False) Tuple[ItemTransactionModelQuerySet, Dict]

Fetches the InvoiceModel Items and aggregates the QuerySet.

Parameters:

queryset – Optional pre-fetched ItemModelQueryset to use. Avoids additional DB query if provided.

Returns:

A tuple

Return type:

ItemTransactionModelQuerySet, dict

get_mark_as_approved_html_id()

InvoiceModel Mark as Approved HTML ID.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_approved_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Approved InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_approved_url()

InvoiceModel Mark-as-Approved action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

InvoiceModel mark-as-approved action URL.

Return type:

str

get_mark_as_canceled_html_id()

InvoiceModel Mark as Canceled HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_canceled_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Canceled InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_canceled_url()

InvoiceModel Mark-as-Canceled action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

InvoiceModel mark-as-canceled action URL.

Return type:

str

get_mark_as_draft_html_id()

InvoiceModel Mark as Draft HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_draft_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Draft InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_draft_url()

InvoiceModel Mark-as-Draft action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_paid_html_id()

InvoiceModel Mark as Paid HTML ID Tag.

Returns:

HTML ID as a String

Return type:

str

get_mark_as_paid_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Paid InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_paid_url(entity_slug: str = None)

InvoiceModel Mark-as-Paid action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

InvoiceModel mark-as-paid action URL.

Return type:

str

get_mark_as_review_html_id()

InvoiceModel Mark as In Review HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_review_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Review InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_review_url()

InvoiceModel Mark-as-Review action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Returns:

InvoiceModel mark-as-review action URL.

Return type:

str

get_mark_as_void_html_id()

InvoiceModel Mark as Void HTML ID Tag.

Returns:

HTML ID as a String.

Return type:

str

get_mark_as_void_message()

Internationalized confirmation message with Invoice Number.

Returns:

Mark-as-Void InvoiceModel confirmation message as a String.

Return type:

str

get_mark_as_void_url()

InvoiceModel Mark-as-Void action URL.

Parameters:

entity_slug (str) – Entity Slug kwarg. If not provided, will result in addition DB query if select_related(‘ledger__entity’) is not cached on QuerySet.

Return type:

InvoiceModel mark-as-void action URL.

get_migrate_state_desc()

Description used when migrating transactions into the LedgerModel.

Returns:

Description as a string.

Return type:

str

get_migration_data(queryset: ItemTransactionModelQuerySet | None = None) ItemTransactionModelQuerySet

Fetches necessary item transaction data to perform a migration into the LedgerModel.

Parameters:

queryset (ItemTransactionModelQuerySet) – Optional pre-fetched ItemModelTransactionQueryset to use. Avoids additional DB query if provided.

get_status_action_date()

Current status action date.

Returns:

A date. i.e. If status is Approved, return date_approved. If Paid, return date_paid.

Return type:

date

get_terms_start_date() date

Date where InvoiceModel term start to apply.

Returns:

A date which represents the start of InvoiceModel terms.

Return type:

date

get_transaction_queryset(annotated: bool = False)

Fetches the TransactionModelQuerySet associated with the InvoiceModel instance.

is_active()

Checks if the InvoiceModel has the potential to impact the books and produce financial statements status.

Returns:

True if InvoiceModel is Active, else False.

Return type:

bool

is_approved() bool

Checks if the InvoiceModel is in Approved status.

Returns:

True if InvoiceModel is Approved, else False.

Return type:

bool

is_canceled() bool

Checks if the InvoiceModel is in Canceled status.

Returns:

True if InvoiceModel is Canceled, else False.

Return type:

bool

is_configured() bool

Determines if the accruable financial instrument is properly configured.

Returns:

True if configured, else False.

Return type:

bool

is_draft() bool

Checks if the InvoiceModel is in Draft status.

Returns:

True if InvoiceModel is Draft, else False.

Return type:

bool

is_paid() bool

Checks if the InvoiceModel is in Paid status.

Returns:

True if InvoiceModel is Paid, else False.

Return type:

bool

is_past_due() bool

Checks if the InvoiceModel is past due.

Returns:

True if InvoiceModel is past due, else False.

Return type:

bool

is_review() bool

Checks if the InvoiceModel is In Review status.

Returns:

True if InvoiceModel is in Review, else False.

Return type:

bool

is_void() bool

Checks if the InvoiceModel is in Void status.

Returns:

True if InvoiceModel is Void, else False.

Return type:

bool

make_payment(payment_amount: Decimal | float | int, payment_date: datetime | date | None = None, commit: bool = False, raise_exception: bool = True)

Makes a payment to the InvoiceModel.

Parameters:
  • payment_amount (Decimal ot float) – The payment amount to process.

  • payment_date (datetime or date.) – Date or timestamp of the payment being applied.

  • commit (bool) – If True, commits the transaction into the DB. Defaults to False.

  • raise_exception (bool) – If True, raises InvoiceModelValidationError if payment exceeds amount due, else False.

Returns:

True if can make payment, else False.

Return type:

bool

mark_as_approved(entity_slug, user_model, date_approved: date = None, commit: bool = False, force_migrate: bool = False, raise_exception: bool = True, **kwargs)

Marks InvoiceModel as Approved.

Parameters:
  • entity_slug – Entity slug associated with the InvoiceModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_approved (date) – InvoiceModel approved date. Defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

  • force_migrate (bool) – Forces migration. True if Accounting Method is Accrual.

mark_as_canceled(date_canceled: date = None, commit: bool = False, **kwargs)

Mark InvoiceModel as Canceled.

Parameters:
  • date_canceled (date) – InvoiceModel canceled date. Defaults to localdate() if None.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_draft(draft_date: date | datetime, commit: bool = False, **kwargs)

Marks InvoiceModel as Draft.

Parameters:
  • date_draft (date) – Draft date. If None, defaults to localdate().

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_paid(entity_slug: str, user_model, date_paid: date = None, commit: bool = False, **kwargs)

Marks InvoiceModel as Paid.

Parameters:
  • entity_slug (str) – Entity slug associated with the InvoiceModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_paid (date) – InvoiceModel paid date. Defaults to localdate() if None.

  • itemtxs_qs (ItemTransactionModelQuerySet) – Pre-fetched ItemTransactionModelQuerySet. Avoids additional DB query. Validated if passed.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

mark_as_review(date_in_review: date = None, itemtxs_qs=None, commit: bool = False, **kwargs)

Marks InvoiceModel as In Review.

Parameters:
  • date_in_review (date) – InvoiceModel in review date. Defaults to localdate() if None.

  • itemtxs_qs (ItemTransactionModelQuerySet) – Pre fetched ItemTransactionModelQuerySet to use. Avoids additional DB Query if previously fetched.

  • commit (bool) – Commits transaction into the Database. Defaults to False.

  • raise_exception (bool) – Raises InvoiceModelValidationError if InvoiceModel cannot be marked as in review. Defaults to True.

mark_as_void(entity_slug: str, user_model, date_void: datetime | date | None = None, commit: bool = False, **kwargs)

Marks InvoiceModel as Void. When mark as void, all transactions associated with InvoiceModel are reversed as of the void date.

Parameters:
  • entity_slug (str) – Entity slug associated with the InvoiceModel. Avoids additional DB query if passed.

  • user_model – UserModel associated with request.

  • date_void (date) – InvoiceModel void date. Defaults to localdate() if None.

  • commit (bool) – Commits transaction into DB. Defaults to False.

migrate_itemtxs(itemtxs: Dict, operation: str, commit: bool = False)

Migrates a predefined item transaction list.

Parameters:
  • itemtxs (dict) – A dictionary where keys are the document number (invoice/bill number, etc) and values are a dictionary:

  • operation (str) – A choice of ITEMIZE_REPLACE, ITEMIZE_APPEND, ITEMIZE_UPDATE

  • commit (bool) – If True, commits transaction into the DB. Default to False

Returns:

A list of ItemTransactionModel appended or created.

Return type:

list

save(**kwargs)

Save method for InvoiceModel. Results in a DB query if invoice number has not been generated and the InvoiceModel is eligible to generate a invoice_number.

update_amount_due(itemtxs_qs: ItemTransactionModelQuerySet | None = None) ItemTransactionModelQuerySet

Updates the InvoiceModel amount due.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet) – Optional pre-fetched ItemTransactionModelQuerySet. Avoids additional DB if provided. Queryset is validated if provided.

Returns:

Newly fetched of previously fetched ItemTransactionModelQuerySet if provided.

Return type:

ItemTransactionModelQuerySet

validate_itemtxs_qs(queryset: ItemTransactionModelQuerySet)

Validates that the entire ItemTransactionModelQuerySet is bound to the InvoiceModel.

Parameters:

queryset (ItemTransactionModelQuerySet) – ItemTransactionModelQuerySet to validate.

class django_ledger.models.invoice.InvoiceModelManager(*args, **kwargs)

A custom defined InvoiceModel Manager that will act as an interface to handling the DB queries to the InvoiceModel. The default “get_queryset” has been overridden to refer the custom defined “InvoiceModelQuerySet”

for_entity(entity_slug, user_model) InvoiceModelQuerySet

Returns a QuerySet of InvoiceModels associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – The request UserModel to check for privileges.

Returns:

A Filtered InvoiceModelQuerySet.

Return type:

InvoiceModelQuerySet

get_queryset()

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class django_ledger.models.invoice.InvoiceModelQuerySet(model=None, query=None, using=None, hints=None)

A custom defined QuerySet for the InvoiceModel. This implements multiple methods or queries that we need to run to get a status of Invoices raised by the entity. For example, We might want to have list of invoices which are paid, unpaid, due , overDue, approved or in draft stage. All these separate functions will assist in making such queries and building customized reports.

active()

Active invoices are those that are approved or paid, which have impacted or have the potential to impact the Entity’s Ledgers.

Returns:

Returns a QuerySet of active invoices only.

Return type:

InvoiceModelQuerySet

approved()

Approved invoices are those that have been reviewed and are expected to be paid before the due date.

Returns:

Returns a QuerySet of approved invoices only.

Return type:

InvoiceModelQuerySet

canceled()

Canceled invoices are those that are discarded during the draft or in review status. These invoices never had an impact on the books.

Returns:

Returns a QuerySet of canceled invoices only.

Return type:

InvoiceModelQuerySet

draft()

Default status of any invoice that is created. Draft invoices do not impact the Ledger.

Returns:

Returns a QuerySet of draft invoices only.

Return type:

InvoiceModelQuerySet

in_review()

In review invoices are those that need additional review or approvals before being approved. Draft invoices do not impact the Ledger.

Returns:

Returns a QuerySet of in review invoices only.

Return type:

InvoiceModelQuerySet

overdue()

Overdue invoices are those which due date is in the past.

Returns:

Returns a QuerySet of overdue invoices only.

Return type:

InvoiceModelQuerySet

paid()

Paid invoices are those that have received 100% of the amount due.

Returns:

Returns a QuerySet of paid invoices only.

Return type:

InvoiceModelQuerySet

unpaid()

Unpaid invoices are those that are approved but have not received 100% of the amount due. Equivalent to approved().

Returns:

Returns a QuerySet of paid invoices only.

Return type:

InvoiceModelQuerySet

void()

Void invoices are those that where rolled back after being approved. Void invoices rollback all transactions by creating a new set of transactions posted on the date_void.

Returns:

Returns a QuerySet of void invoices only.

Return type:

InvoiceModelQuerySet

exception django_ledger.models.invoice.InvoiceModelValidationError(message, code=None, params=None)

Customer Model

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

A Customer refers to the person or entity that buys product and services. When issuing Invoices, a Customer must be created before it can be assigned to the InvoiceModel. Only customers who are active can be assigned to new Invoices.

class django_ledger.models.customer.CustomerModel(*args, **kwargs)

Base Customer Model Implementation

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.customer.CustomerModelAbstract(*args, **kwargs)

This is the main abstract class which the CustomerModel database will inherit from. The CustomerModel inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

entity_model

The EntityModel associated with this Customer.

Type:

EntityModel

customer_name

A string representing the name the customer uses to do business with the EntityModel.

Type:

str

customer_number

A unique, auto-generated human-readable number which identifies the customer within the EntityModel.

Type:

str

description

A text field to capture the description about the customer.

Type:

str

active

We can set any customer code to be active or inactive. Defaults to True.

Type:

bool

hidden

Hidden CustomerModels don’t show on the UI. Defaults to False.

Type:

bool

additional_info

Any additional information about the customer, stored as a JSON object using a JSONField.

Type:

dict

can_generate_customer_number() bool

Determines if the CustomerModel can be issued a Customer Number. CustomerModels have a unique sequential number, which is unique for each EntityMode/CustomerModel.

Returns:

True if customer model can be generated, else False.

Return type:

bool

clean()

Custom defined clean method that fetches the next customer number if not yet fetched. Additional validation may be provided.

generate_customer_number(commit: bool = False) str

Atomic Transaction. Generates the next Customer Number available.

Parameters:

commit (bool) – Commits transaction into CustomerModel. Defaults to False.

Returns:

A String, representing the current CustomerModel instance Document Number.

Return type:

str

save(**kwargs)

Custom-defined save method that automatically fetches the customer number if not present.

Parameters:

kwargs – Keywords passed to the super().save() method of the CustomerModel.

class django_ledger.models.customer.CustomerModelManager(*args, **kwargs)

A custom defined CustomerModelManager that will act as an interface to handling the DB queries to the CustomerModel.

for_entity(entity_slug, user_model) CustomerModelQueryset

Fetches a QuerySet of CustomerModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Returns:

A filtered CustomerModel QuerySet.

Return type:

CustomerModelQueryset

for_user(user_model)

Fetches a QuerySet of BillModels that the UserModel as access to. May include BillModels from multiple Entities.

The user has access to bills if:
  1. Is listed as Manager of Entity.

  2. Is the Admin of the Entity.

Parameters:

user_model – Logged in and authenticated django UserModel instance.

class django_ledger.models.customer.CustomerModelQueryset(model=None, query=None, using=None, hints=None)

A custom defined QuerySet for the CustomerModel. This implements multiple methods or queries needed to get a filtered QuerySet based on the CustomerModel status. For example, we might want to have list of Customers that are active or hidden. All these separate functions will assist in making such queries and building customized reports.

active() QuerySet

Active customers can be assigned to new Invoices and show on dropdown menus and views.

Returns:

A QuerySet of active Customers.

Return type:

CustomerModelQueryset

hidden() QuerySet

Hidden customers do not show on dropdown menus, but may be used via APIs or any other method that does not involve the UI.

Returns:

A QuerySet of hidden Customers.

Return type:

CustomerModelQueryset

inactive() QuerySet

Active customers can be assigned to new Invoices and show on dropdown menus and views. Marking CustomerModels as inactive can help reduce Database load to populate select inputs and also inactivate CustomerModels that are not relevant to the Entity anymore. Also, it makes de UI cleaner by not populating unnecessary choices.

Returns:

A QuerySet of inactive Customers.

Return type:

CustomerModelQueryset

visible() QuerySet

Visible customers show on dropdown menus and views. Visible customers are active and not hidden.

Returns:

A QuerySet of visible Customers.

Return type:

CustomerModelQueryset

Vendor Model

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

A Vendor refers to the person or entity that provides products and services to the business for a fee. Vendors are an integral part of the billing process as they are the providers of goods and services for the business.

Vendors can be flagged as active/inactive or hidden. Vendors who no longer conduct business with the EntityModel, whether temporarily or indefinitely may be flagged as inactive (i.e. active is False). Hidden Vendors will not show up as an option in the UI, but can still be used programmatically (via API).

class django_ledger.models.vendor.VendorModel(*args, **kwargs)

Base Vendor Model Implementation

exception DoesNotExist
exception MultipleObjectsReturned
class django_ledger.models.vendor.VendorModelAbstract(*args, **kwargs)

This is the main abstract class which the VendorModel database will inherit from. The VendorModel inherits functionality from the following MixIns:

uuid

This is a unique primary key generated for the table. The default value of this field is uuid4().

Type:

UUID

entity_model

The EntityModel associated with this Vendor.

Type:

EntityModel

vendor_name

A string representing the name the customer uses to do business with the EntityModel.

Type:

str

vendor_number

A unique, auto-generated human-readable number which identifies the vendor within the EntityModel.

Type:

str

description

A text field to capture the description about the vendor.

Type:

str

active

We can set any vendor to be active or inactive. Defaults to True.

Type:

bool

hidden

Hidden VendorModel don’t show on the UI. Defaults to False.

Type:

bool

additional_info

Any additional information about the vendor, stored as a JSON object using a JSONField.

Type:

dict

can_generate_vendor_number() bool

Determines if the VendorModel can be issued a Vendor Number. VendorModel have a unique sequential number, which is unique for each EntityModel/VendorModel.

Returns:

True if vendor number can be generated, else False.

Return type:

bool

clean()

Custom defined clean method that fetches the next vendor number if not yet fetched. Additional validation may be provided.

generate_vendor_number(commit: bool = False) str

Atomic Transaction. Generates the next Vendor Number available.

Parameters:

commit (bool) – Commits transaction into VendorModel. Defaults to False.

Returns:

A String, representing the current VendorModel instance document number.

Return type:

str

save(**kwargs)

Custom-defined save method that automatically fetches the vendor number if not present.

Parameters:

kwargs – Keywords passed to the super().save() method of the VendorModel.

class django_ledger.models.vendor.VendorModelManager(*args, **kwargs)

Custom defined VendorModel Manager, which defines many methods for initial query of the Database.

for_entity(entity_slug, user_model) VendorModelQuerySet

Fetches a QuerySet of VendorModel associated with a specific EntityModel & UserModel. May pass an instance of EntityModel or a String representing the EntityModel slug.

Parameters:
  • entity_slug (str or EntityModel) – The entity slug or EntityModel used for filtering the QuerySet.

  • user_model – Logged in and authenticated django UserModel instance.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> vendor_model_qs = VendorModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns:

A filtered VendorModel QuerySet.

Return type:

VendorModelQuerySet

class django_ledger.models.vendor.VendorModelQuerySet(model=None, query=None, using=None, hints=None)

Custom defined VendorModel QuerySet.

active() QuerySet

Active vendors can be assigned to new bills and show on dropdown menus and views.

Returns:

A QuerySet of active Vendors.

Return type:

VendorModelQuerySet

hidden() QuerySet

Hidden vendors do not show on dropdown menus, but may be used via APIs or any other method that does not involve the UI.

Returns:

A QuerySet of hidden Vendors.

Return type:

VendorModelQuerySet

inactive() QuerySet

Active vendors can be assigned to new bills and show on dropdown menus and views. Marking VendorModels as inactive can help reduce Database load to populate select inputs and also inactivate VendorModels that are not relevant to the Entity anymore. Also, it makes de UI cleaner by not populating unnecessary choices.

Returns:

A QuerySet of inactive Vendors.

Return type:

VendorModelQuerySet

visible() QuerySet

Visible vendors show on dropdown menus and views. Visible vendors are active and not hidden.

Returns:

A QuerySet of visible Vendors.

Return type:

VendorModelQuerySet

exception django_ledger.models.vendor.VendorModelValidationError(message, code=None, params=None)

MixIns

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

This module implements the different model MixIns used on different Django Ledger Models to implement common functionality.

class django_ledger.models.mixins.AccrualMixIn(*args, **kwargs)

Implements functionality used to track accruable financial instruments to a base Django Model. Examples of this include bills and invoices expenses/income, that depending on the Entity’s accrual method, may be recognized on the Income Statement differently.

amount_due

The total amount due of the financial instrument.

Type:

Decimal

amount_paid

The total amount paid or settled.

Type:

Decimal

amount_receivable

The total amount allocated to Accounts Receivable based on the progress.

Type:

Decimal

amount_unearned

The total amount allocated to Accounts Payable based on the progress.

Type:

Decimal

amount_earned

The total amount that is recognized on the earnings based on progress.

accrue

If True, the financial instrument will follow the Accrual Method of Accounting, otherwise it will follow the Cash Method of Accounting. Defaults to the EntityModel preferred method of accounting.

Type:

bool

progress

A decimal number representing the amount of progress of the financial instrument. Value is between 0.00 and 1.00.

Type:

Decimal

ledger

The LedgerModel associated with the Accruable financial instrument.

Type:

LedgerModel

cash_account

The AccountModel used to track cash payments to the financial instrument. Must be of role ASSET_CA_CASH.

Type:

AccountModel

prepaid_account

The AccountModel used to track receivables to the financial instrument. Must be of role ASSET_CA_PREPAID.

Type:

AccountModel

unearned_account

The AccountModel used to track receivables to the financial instrument. Must be of role LIABILITY_CL_DEFERRED_REVENUE.

Type:

AccountModel

can_migrate() bool

Determines if the Accruable financial instrument can be migrated to the books. Results in additional Database query if ‘ledger’ field is not pre-fetch on QuerySet.

Returns:

True if can migrate, else False.

Return type:

bool

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

get_amount_cash() Decimal | float

Determines the impact to the EntityModel cash balance based on the financial instrument debit or credit configuration. i.e, Invoices are debit financial instrument because payments to invoices increase cash.

Returns:

Financial instrument progress as a percent.

Return type:

float

get_amount_earned() Decimal | float

Determines the impact to the EntityModel earnings based on financial instrument progress.

Returns:

Financial instrument amount earned.

Return type:

float or Decimal

get_amount_open() Decimal | float

Determines the open amount left to be progressed.

Returns:

Financial instrument amount open.

Return type:

float or Decimal

get_amount_prepaid() Decimal | float

Determines the impact to the EntityModel Accounts Receivable based on financial instrument progress.

Returns:

Financial instrument amount prepaid.

Return type:

float or Decimal

get_amount_unearned() Decimal | float

Determines the impact to the EntityModel Accounts Payable based on financial instrument progress.

Returns:

Financial instrument amount unearned.

Return type:

float or Decimal

get_progress() Decimal | float

Determines the progress amount based on amount due, amount paid and accrue field.

Returns:

Financial instrument progress as a Decimal.

Return type:

Decimal

get_progress_percent() float

Determines the progress amount as percent based on amount due, amount paid and accrue field.

Returns:

Financial instrument progress as a percent.

Return type:

float

get_state(commit: bool = False)

Determines the new state of the financial instrument based on progress.

Parameters:

commit (bool) – Commits the new financial instrument state into the model.

Returns:

A dictionary with new amount_paid, amount_receivable, amount_unearned and amount_earned as keys.

Return type:

dict

get_tx_type(acc_bal_type: dict, adjustment_amount: Decimal)

Determines the transaction type associated with an increase/decrease of an account balance of the financial instrument.

Parameters:
  • acc_bal_type – The balance type of the account to be adjusted.

  • adjustment_amount (Decimal) – The adjustment, whether positive or negative.

Returns:

The transaction type of the account adjustment.

Return type:

str

is_configured() bool

Determines if the accruable financial instrument is properly configured.

Returns:

True if configured, else False.

Return type:

bool

is_posted()

Determines if the accruable financial instrument is posted. Results in additional Database query if ‘ledger’ field is not pre-fetch on QuerySet.

Returns:

True if posted, else False.

Return type:

bool

lock_ledger(commit: bool = False, raise_exception: bool = True, **kwargs)

Convenience method to lock the LedgerModel associated with the Accruable financial instrument.

Parameters:
  • commit (bool) – Commits the transaction in the database. Defaults to False.

  • raise_exception (bool) – If True, raises ValidationError if LedgerModel already locked.

migrate_state(user_model, entity_slug: str, itemtxs_qs: QuerySet | None = None, force_migrate: bool = False, commit: bool = True, void: bool = False, je_timestamp: str | datetime | date | None = None, raise_exception: bool = True, **kwargs)

Migrates the current Accruable financial instrument into the books. The main objective of the migrate_state method is to determine the JournalEntry and TransactionModels necessary to accurately reflect the financial instrument state in the books.

Parameters:
  • user_model – The Django User Model.

  • entity_slug (str) – The EntityModel slug.

  • itemtxs_qs (ItemTransactionModelQuerySet) – The pre-fetched ItemTransactionModelQuerySet containing the item information associated with the financial element migration. If provided, will avoid additional database query.

  • force_migrate (bool) – Forces migration of the financial instrument bypassing the can_migrate() check.

  • commit (bool) – If True the migration will be committed in the database. Defaults to True.

  • void (bool) – If True, the migration will perform a VOID actions of the financial instrument.

  • je_timestamp (date) – The JournalEntryModel date to be used for this migration.

  • raise_exception (bool) – Raises ValidationError if migration is not allowed. Defaults to True.

Returns:

A tuple of the ItemTransactionModel and the Digest Result from IOMixIn.

Return type:

tuple

post_ledger(commit: bool = False, raise_exception: bool = True, **kwargs)

Convenience method to post the LedgerModel associated with the Accruable financial instrument.

Parameters:
  • commit (bool) – Commits the transaction in the database. Defaults to False.

  • raise_exception (bool) – If True, raises ValidationError if LedgerModel already locked.

classmethod split_amount(amount: Decimal | float, unit_split: Dict, account_uuid: UUID, account_balance_type: str) Dict

Splits an amount into different proportions representing the unit splits. Makes sure that 100% of the amount is numerically allocated taking into consideration decimal points.

Parameters:
  • amount (Decimal or float) – The amount to be split.

  • unit_split (dict) – A dictionary with information related to each unit split and proportions.

  • account_uuid (UUID) – The AccountModel UUID associated with the splits.

  • account_balance_type (str) – The AccountModel balance type to determine whether to perform a credit or a debit.

Returns:

A dictionary with the split information.

Return type:

dict

unlock_ledger(commit: bool = False, raise_exception: bool = True, **kwargs)

Convenience method to un-lock the LedgerModel associated with the Accruable financial instrument.

Parameters:
  • commit (bool) – Commits the transaction in the database. Defaults to False.

  • raise_exception (bool) – If True, raises ValidationError if LedgerModel already locked.

unpost_ledger(commit: bool = False, raise_exception: bool = True, **kwargs)

Convenience method to un-lock the LedgerModel associated with the Accruable financial instrument.

Parameters:
  • commit (bool) – Commits the transaction in the database. Defaults to False.

  • raise_exception (bool) – If True, raises ValidationError if LedgerModel already locked.

update_state(state: Dict | None = None)

Updates the state on the financial instrument.

Parameters:

state (dict) – Optional user provided state to use.

void_state(commit: bool = False) Dict

Determines the VOID state of the financial instrument.

Parameters:

commit (bool) – Commits the new financial instrument state into the model.

Returns:

A dictionary with new amount_paid, amount_receivable, amount_unearned and amount_earned as keys.

Return type:

dict

class django_ledger.models.mixins.ContactInfoMixIn(*args, **kwargs)

Implements a common set of fields used to document contact information.

address_1

A string used to document the first line of an address. Mandatory. Max length is 70.

Type:

str

address_2

A string used to document the first line of an address. Optional.

Type:

str

city

A string used to document the city. Optional.

Type:

str

state

A string used to document the State of Province. Optional.

Type:

str

zip_code

A string used to document the ZIP code. Optional

Type:

str

country

A string used to document the country. Optional.

Type:

str

email

A string used to document the contact email. Uses django’s EmailField for validation.

Type:

str

website

A string used to document the contact website. Uses django’s URLField for validation.

Type:

str

phone

A string used to document the contact phone.

Type:

str

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

class django_ledger.models.mixins.CreateUpdateMixIn(*args, **kwargs)

Implements a created and an updated field to a base Django Model.

created

A created timestamp. Defaults to now().

Type:

datetime

updated

An updated timestamp used to identify when models are updated.

Type:

str

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

class django_ledger.models.mixins.FinancialAccountInfoMixin(*args, **kwargs)

Implements functionality used to add bank account details to base Django Models.

account_number

The Bank Account number. Only Digits are allowed. Max 30 digists.

Type:

str

routing_number

Routing number for the concerned bank account. Also called as ‘Routing Transit Number (RTN)’. Max 30 digists.

Type:

str

aba_number

The American Bankers Association Number assigned to each bank.

Type:

str

account_type

A choice of ACCOUNT_TYPES. Each account will have to select from the available choices Checking, Savings.

Type:

str

swift_number

SWIFT electronic communications network number of the bank institution.

Type:

str

exception django_ledger.models.mixins.ItemizeError(message, code=None, params=None)
class django_ledger.models.mixins.ItemizeMixIn(*args, **kwargs)
can_migrate_itemtxs() bool

Checks if item transaction list can be migrated.

Return type:

bool

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

get_item_model_qs()

Fetches the ItemModelQuerySet eligible to itemize.

Return type:

ItemModelQuerySet

get_itemtxs_data(queryset=None, aggregate_on_db: bool = False, lazy_agg: bool = False)

Fetches the ItemTransactionModelQuerySet associated with the model.

Parameters:
  • queryset (ItemTransactionModelQuerySet) – Pre-fetched ItemTransactionModelQuerySet. Validated if provided.

  • aggregate_on_db (bool) – If True, performs aggregation at the DB layer. Defaults to False.

  • lazy_agg (bool) – If True, performs queryset aggregation metrics. Defaults to False.

Returns:

ItemModelQuerySet, dict

Return type:

tuple

migrate_itemtxs(itemtxs: Dict, operation: str, commit: bool = False)

Migrates a predefined item transaction list.

Parameters:
  • itemtxs (dict) – A dictionary where keys are the document number (invoice/bill number, etc) and values are a dictionary:

  • operation (str) – A choice of ITEMIZE_REPLACE, ITEMIZE_APPEND, ITEMIZE_UPDATE

  • commit (bool) – If True, commits transaction into the DB. Default to False

Returns:

A list of ItemTransactionModel appended or created.

Return type:

list

validate_itemtxs(itemtxs)

Validates the provided item transaction list.

Parameters:

itemtxs (dict) – Item transaction list to replace/aggregate.

validate_itemtxs_qs()

Validates that the provided item transaction list is valid.

class django_ledger.models.mixins.LoggingMixIn

Implements functionality used to add logging capabilities to any python class. Useful for production and or testing environments.

class django_ledger.models.mixins.MarkdownNotesMixIn(*args, **kwargs)

Implements functionality used to add a Mark-Down notes to a base Django Model.

markdown_notes

A string of text representing the mark-down document.

Type:

str

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

notes_html()

Compiles the markdown_notes field into html.

Returns:

Compiled HTML document as a string.

Return type:

str

class django_ledger.models.mixins.PaymentTermsMixIn(*args, **kwargs)

Implements functionality used to track dates relate to various payment terms. Examples of this include tracking bills and invoices that are due on receipt, 30, 60 or 90 days after they are approved.

terms

A choice of TERM_CHOICES that determines the payment terms.

Type:

str

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

due_in_days() int | None

Determines how many days until the due date.

Returns:

Days as integer.

Return type:

int

get_terms_net_90_plus() int

Determines the number of days for 90+ days terms of payment.

Returns:

The date when terms of payment starts.

Return type:

date

get_terms_start_date() date

Determines the start date for the terms of payment.

Returns:

The date when terms of payment starts.

Return type:

date

get_terms_timedelta() timedelta

Calculates a timedelta relative to the terms start date.

Returns:

Timedelta relative to terms start date.

Return type:

timedelta

get_terms_timedelta_days() int

Determines the number of days from the terms start date.

Returns:

The number of days as integer.

Return type:

int

net_due_group()

Determines the group where the financial instrument falls based on the number of days until the due date.

Returns:

The terms group as a string.

Return type:

str

class django_ledger.models.mixins.SlugNameMixIn(*args, **kwargs)

Implements a slug field and a name field to a base Django Model.

slug

A unique slug field to use as an index. Validates that the slug is at least 10 characters long.

Type:

str

name

A human-readable name for display purposes. Maximum 150 characters.

Type:

str

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

class django_ledger.models.mixins.TaxCollectionMixIn(*args, **kwargs)

Implements functionality used to add tax collection rates and or withholding to a base Django Model. This field may be used to set a pre-defined withholding rate to a financial instrument, customer, vendor, etc.

sales_tax_rate

The tax rate as a float. A Number between 0.00 and 1.00.

Type:

float

clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

class django_ledger.models.mixins.TaxInfoMixIn(*args, **kwargs)
clean()

Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.

Signals

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

The signals module provide the means to notify listeners about important events or states in the models, such as a ledger model being posted or a bill status changing.