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.

Contributions to this module:

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: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Optional[Union[ChartOfAccountModel, UUID, str]] = 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, cash_account: Optional[AccountModel] = None, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = None, bank_account_model_kwargs: Optional[Dict] = None, commit: bool = True)#

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

Parameters:
  • name (str) – A user defined name for the BankAccountModel.

  • account_type (date) – A choice of BankAccountModel.VALID_ACCOUNT_TYPES.

  • active (bool) – Marks the account as active.

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

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

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

  • bank_account_model_kwargs (Dict) – Additional kwargs for the new BankAccountModel instance.

Returns:

The newly created PurchaseOrderModel in DRAFT state.

Return type:

PurchaseOrderModel

create_bill(vendor_model: Union[VendorModel, UUID, str], terms: str, date_draft: Optional[Union[datetime, date]] = None, xref: Optional[str] = None, cash_account: Optional[AccountModel] = None, prepaid_account: Optional[AccountModel] = None, payable_account: Optional[AccountModel] = None, additional_info: Optional[Dict] = None, ledger_name: Optional[str] = None, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Optional[str] = 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: Union[CustomerModel, UUID, str], date_draft: Optional[date] = 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: Union[VendorModel, UUID, str], terms: str, cash_account: Optional[AccountModel] = None, prepaid_account: Optional[AccountModel] = None, payable_account: Optional[AccountModel] = None, additional_info: Optional[Dict] = None, ledger_name: Optional[str] = None, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = None, date_draft: Optional[date] = 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: Union[UUID, UnitOfMeasureModel], expense_account: Optional[Union[UUID, AccountModel]] = None, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Union[UUID, UnitOfMeasureModel], item_type: str, inventory_account: Optional[Union[UUID, AccountModel]] = None, coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Union[UUID, UnitOfMeasureModel], coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Union[UUID, UnitOfMeasureModel], coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Optional[str] = None, estimate_model=None, date_draft: Optional[date] = 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: Union[str, List[str], Set[str]], coa_model: Optional[Union[ChartOfAccountModel, UUID, str]] = 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: Optional[Tuple[str]] = ('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: Optional[Tuple[str]] = ('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: Optional[Union[ChartOfAccountModel, UUID, str]] = None, active: bool = True, order_by: Optional[Tuple] = ('code',)) 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.

  • 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: Optional[ChartOfAccountModel] = 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) Optional[ChartOfAccountModel]#

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: Optional[Tuple[str]] = ('code',), raise_exception: bool = True) Optional[AccountModelQuerySet]#

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: Optional[ChartOfAccountModel] = 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: Optional[ItemModelQuerySet] = 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.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: Optional[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: Optional[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: Optional[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: Union[date, datetime], as_str: bool = False) Union[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: Optional[int] = 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: Optional[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: Optional[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)#

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.

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.

Contributions to this module:

An EntityUnit is a logical, user-defined grouping which is assigned to JournalEntryModels to help segregate business operations into separate components. Examples of business units may include Departments (i.e. Human Resources, IT, etc.) office locations, a real estate property, or any other label relevant to the business.

An EntityUnit is self contained. Meaning that double entry accounting rules apply to all transactions associated within them. When An Invoice or Bill is updated, the migration process generates the appropriate Journal Entries associated with each unit, if any. This means that an invoice or bill can split items into different units and the migration process will allocate costs to each unit accordingly.

The main advantages of EntityUnits are:
  1. Entity units can generate their own financial statements which can give additional insight to specific operations of the business.

  2. Entity units can be assigned to specific items on Bills and Invoices, providing additional flexibility to track inventory, expenses or income attributable to specific units of the business.

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: Optional[str] = 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.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> bill_model_qs = EntityUnitModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns:

Returns a EntityUnitModelQuerySet with applied filters.

Return type:

EntityUnitModelQuerySet

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.

Contributions to this module:

The AccountModel groups and sorts transactions involving the company’s assets, liabilities and equities. Per accounting principles, an Account must be either a DEBIT-type balance account or a CREDIT-type balance account, depending on its purpose.

The AccountModel plays a major role when creating Journal Entries in a double entry accounting systems where a DEBIT to a DEBIT-type AccountModel will increase its balance, and a CREDIT to a DEBIT-type AccountModel will reduce its balance. Conversely, a CREDIT to a CREDIT-type AccountModel will increase its balance, and a DEBIT to a CREDIT-type AccountModel will reduce its balance.

It is entirely up to the user to adopt the chart of accounts that best suits the EntityModel. The user may choose to use the default Chart of Accounts provided by Django Ledger when creating a new EntityModel.

In Django Ledger, all account models must be assigned a role from ACCOUNT_ROLES. Roles are a way to group accounts to a common namespace, regardless of its user-defined fields. Roles are an integral part to Django Ledger since they are critical when requesting and producing financial statements and financial ratio calculations.

AccountModels may also contain parent/child relationships as implemented by the Django Treebeard functionality.

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

Django Ledger Base Account Model Abstract. This is the main abstract class which the Account Model database will inherit, and it contains the fields/columns/attributes which the said ledger table will have. In addition to the attributes mentioned below, it also has the fields/columns/attributes mentioned in the ParentChileMixin & the CreateUpdateMixIn. Read about these mixin here.

Below are the fields specific to the accounts model.

uuid#

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

Type:

UUID

code#

Each account will have its own alphanumeric code. For example: * Cash Account -> Code 1010. * Inventory -> 1200. * Maximum Length allowed is 10.

Type:

str

name#

This is the user defined name of the Account. the maximum length for Name of the ledger allowed is 100

Type:

str

role#

Each Account needs to be assigned a certain Role. The exhaustive list of ROLES is defined in io.roles.

Type:

str

balance_type#

Each account will have a default Account type i.e. Either Debit or Credit. For example: * Assets like Cash, Inventory, Accounts Receivable or Expenses like Rent, Salary will have balance_type=DEBIT. * Liabilities, Equities and Income like Payables, Loans, Income, Sales, Reserves will have balance_type=CREDIT.

Type:

str

locked#

This determines whether any transactions can be added in the account. Before making any update to the account, the account needs to be unlocked. Default value is set to False i.e. Unlocked.

Type:

bool

active#

Determines whether the concerned account is active. Any Account can be used only when it is unlocked and Active. Default value is set to True.

Type:

bool

coa_model#

Each Accounts must be assigned a ChartOfAccountsModel. By default, one CoA will be created for each entity. However, the creating of a new AccountModel must have an explicit assignment of a ChartOfAccountModel.

Type:

ChartOfAccountsModel

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.

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

Convenience Method to Create a new Account Model. This is the preferred method to create new Accounts in order to properly handle parent/child relationships between models.

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

  • role (str) – Account role.

  • balance_type (str) – Account Balance Type. Must be ‘debit’ or ‘credit’.

  • is_role_default (bool) – If True, assigns account as default for role. Only once default account per role is permitted.

  • locked (bool) – Marks account as Locked. Defaults to False.

  • active (bool) – Marks account as Active. Defaults to True.

Returns:

The newly created AccountModel instance.

Return type:

AccountModel

is_credit()#

Checks if the account has a CREDIT balance. :returns: True if account has a CREDIT balance, else False. :rtype: bool

is_debit() bool#

Checks if the account has a DEBIT balance. :returns: True if account has a DEBIT balance, else False. :rtype: bool

property role_bs: str#

The principal role of the account on the balance sheet. Options are: * 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)#

This Model Manager will be used as interface through which the database query operations can be provided to the Account Model. It uses the custom defined AccountModelQuerySet and hence overrides the normal get_queryset function which return all rows of a model.

coa_roots(user_model, entity_slug, coa_slug) AccountModelQuerySet#

Fetches the Code of Account Root Accounts.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

for_bill(user_model, entity_slug, coa_slug: Optional[str] = None) AccountModelQuerySet#

Convenience method to pull only available and unlocked AccountModels for a specific EntityModel relevant only for creating and management of Bills. See GROUP_BILL.

Roles in GROUP_BILL: ASSET_CA_CASH, ASSET_CA_PREPAID, LIABILITY_CL_ACC_PAYABLE.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

Returns:

A QuerySet of all requested EntityModel Chart of Accounts.

Return type:

AccountModelQuerySet

for_entity(user_model, entity_slug, coa_slug: Optional[str] = None, select_coa_model: bool = True) AccountModelQuerySet#

Ensures that only accounts associated with the given EntityModel are returned.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

  • select_coa_model (bool) – Pre fetches the CoA Model information in the QuerySet. Defaults to True.

Returns:

A QuerySet of all requested EntityModel Chart of Accounts.

Return type:

AccountModelQuerySet

for_entity_available(user_model, entity_slug, coa_slug: Optional[str] = None) AccountModelQuerySet#

Convenience method to pull only available and unlocked AccountModels for a specific EntityModel.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

Returns:

A QuerySet of all requested EntityModel Chart of Accounts.

Return type:

AccountModelQuerySet

for_invoice(user_model, entity_slug: str, coa_slug: Optional[str] = None) AccountModelQuerySet#

Convenience method to pull only available and unlocked AccountModels for a specific EntityModel relevant only for creating and management of Invoices. See GROUP_INVOICE.

Roles in GROUP_INVOICE: ASSET_CA_CASH, ASSET_CA_RECEIVABLES, LIABILITY_CL_DEFERRED_REVENUE.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

Returns:

A QuerySet of all requested EntityModel Chart of Accounts.

Return type:

AccountModelQuerySet

get_queryset() AccountModelQuerySet#

Sets the custom queryset as the default.

with_roles(roles: Union[list, str], entity_slug, user_model) AccountModelQuerySet#

This method is used to make query of accounts with a certain role. For instance, the fixed assets like Buildings have all been assigned the role of “asset_ppe_build” role is basically an aggregation of the accounts under a similar category. So, to query the list of all accounts under the role “asset_ppe_build”, we can use this function.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • user_model – The Django User Model making the request to check for permissions.

  • roles (list or str) – Function accepts a single str instance of a role or a list of roles. For a list of roles , refer io.roles.py

Returns:

Returns a QuerySet filtered by user-provided list of Roles.

Return type:

AccountModelQuerySet

with_roles_available(roles: Union[list, str], entity_slug, user_model, coa_slug: Optional[str]) AccountModelQuerySet#

Convenience method to pull only available and unlocked AccountModels for a specific EntityModel and for a specific list of roles.

Parameters:
  • entity_slug (EntityModel or str) – The EntityModel or EntityModel slug to pull accounts from. If slug is passed and coa_slug is None will result in an additional Database query to determine the default code of accounts.

  • coa_slug (str) – Explicitly specify which chart of accounts to use. If None, will pull default Chart of Accounts. Discussed in detail in the CoA Model CoA slug, basically helps in identifying the complete Chart of Accounts for a particular EntityModel.

  • user_model – The Django User Model making the request to check for permissions.

  • roles (list or str) – Function accepts a single str instance of a role or a list of roles. For a list of roles , refer io.roles.py

Returns:

A QuerySet of all requested EntityModel Chart of Accounts.

Return type:

AccountModelQuerySet

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

A custom defined QuerySet, which inherits from the Materialized Path Tree implementation of Django Treebeard for tree-like model implementation.

active()#

Active accounts which can be used to create new transactions that show on drop-down menus and forms.

Returns:

A filtered AccountModelQuerySet of active accounts.

Return type:

AccountModelQuerySet

inactive()#

Inactive accounts cannot be used to create new transactions and don’t show on drop-down menus and forms.

Returns:

A filtered AccountModelQuerySet of inactive accounts.

Return type:

AccountModelQuerySet

with_roles(roles: Union[List, str])#

This method is used to make query of accounts with a certain role. For instance, the fixed assets like Buildings have all been assigned the role of “asset_ppe_build” role is basically an aggregation of the accounts under a similar category. So, to query the list of all accounts under the role “asset_ppe_build”, we can use this function.

Parameters:

roles (list or str) – Function accepts a single str instance of a role or a list of roles. For a list of roles , refer io.roles.py

Returns:

Returns a QuerySet filtered by user-provided list of 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.

Contributions to this module:

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 implmentation 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, **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.

Contributions to this module:

The TransactionModel is the lowest accounting level where financial information is recorded. Every transaction with a financial implication must be part of a JournalEntryModel, which encapsulates a collection of TransactionModels. Transaction models cannot exist without being part of a validated JournalEntryModel. Orphan TransactionModels are not allowed, and this is enforced by the database.

A transaction must perform a CREDIT or a DEBIT to the underlying AccountModel. The IOMixIn is crucial for the production of financial statements and sets its foundation in the TransactionModel API. It allows for effective querying and aggregating transactions at the Database layer without pulling all TransactionModels into memory. This approach streamlines the production of financial statements. The IOMixIn in the TransactionModel API is essential for efficient and effective financial statement generation.

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

An abstract class that represents a transaction in the ledger system.

- CREDIT
Type:

A constant representing a credit transaction.

- DEBIT
Type:

A constant representing a debit transaction.

- TX_TYPE
Type:

A list of tuples representing the transaction type choices.

- uuid

This field is automatically generated and is not editable.

Type:

A UUIDField representing the unique identifier of the transaction.

- tx_type

It has a maximum length of 10 characters and accepts choices from the TX_TYPE list.

Type:

A CharField representing the type of the transaction.

- journal_entry

It references the ‘django_ledger.JournalEntryModel’ model.

Type:

A ForeignKey representing the journal entry associated with the transaction.

- account

It references the ‘django_ledger.AccountModel’ model.

Type:

A ForeignKey representing the account associated with the transaction.

- amount

It has a maximum of 2 decimal places and a maximum of 20 digits. It defaults to 0.00 and accepts a minimum value of 0.

Type:

A DecimalField representing the amount of the transaction.

- description

It has a maximum length of 100 characters and is optional.

Type:

A CharField representing the description of the transaction.

- objects
Type:

An instance of the TransactionModelAdmin class.

- clean(): Performs validation on the transaction instance.

Raises a TransactionModelValidationError if the account is a root account.

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.transactions.TransactionModelAdmin(*args, **kwargs)#

A manager class for the TransactionModel.

for_bill(user_model, entity_slug: str, bill_model: Union[BillModel, str, UUID])#
Parameters:
  • user_model (Type) – An instance of user model.

  • entity_slug (str) – The slug of the entity.

  • bill_model (Union[BillModel, str, UUID]) – An instance of bill model or a string/UUID representing the UUID of the bill model.

Returns:

A filtered queryset based on the user model, entity slug, and bill model.

Return type:

FilterQuerySet

for_entity(entity_slug: Union[EntityModel, str, UUID], user_model: Optional[User] = None) TransactionModelQuerySet#
Parameters:
  • entity_slug (Union[EntityModel, str, UUID]) – The entity slug or ID for which to retrieve transactions. Can be an instance of EntityModel, a string representing the slug, or a UUID.

  • user_model (Optional[UserModel], optional) – The user model for which to filter transactions. If provided, only transactions associated with the specified user will be returned. Defaults to None.

Returns:

A QuerySet of TransactionModel instances filtered by the provided parameters.

Return type:

TransactionModelQuerySet

for_invoice(user_model, entity_slug: str, invoice_model: Union[InvoiceModel, str, UUID])#
Parameters:
  • user_model ([type]) – The user model used for filtering entities.

  • entity_slug (str) – The slug of the entity used for filtering.

  • invoice_model (Union[InvoiceModel, str, UUID]) – The invoice model or its identifier used for filtering.

Returns:

The filtered queryset based on the specified parameters.

Return type:

QuerySet

for_journal_entry(entity_slug: Union[EntityModel, str], ledger_model: Union[LedgerModel, str, UUID], je_model, user_model: Optional[User] = None)#
Parameters:
  • entity_slug (Union[EntityModel, str]) – The entity slug or instance of EntityModel representing the entity for which the journal entry is requested.

  • ledger_model (Union[LedgerModel, str, UUID]) – The ledger model or its identifier (str or UUID) representing the ledger for which the journal entry is requested.

  • je_model (Type[JournalEntryModel]) – The journal entry model or its identifier (str or UUID) representing the journal entry to filter by.

  • user_model (Optional[UserModel], default=None) – An optional user model instance representing the user for whom the journal entry is requested.

Returns:

The filtered queryset of journal entries.

Return type:

QuerySet

for_ledger(entity_slug: Union[EntityModel, str], ledger_model: Union[LedgerModel, UUID], user_model: Optional[User] = None)#
Parameters:
  • entity_slug (Union[EntityModel, str]) – The slug or instance of the entity for which to filter the ledger.

  • ledger_model (Union[LedgerModel, UUID]) – The ledger model or UUID of the ledger for which to filter the journal entries.

  • user_model (Optional[UserModel], optional) – The user model associated with the entity. Default is None.

Returns:

The filtered QuerySet containing the journal entries for the specified entity and ledger.

Return type:

QuerySet

for_unit(entity_slug: Union[EntityModel, str], unit_slug: str = typing.Union[django_ledger.models.unit.EntityUnitModel, str], user_model: Optional[User] = None)#

Returns the queryset filtered for the specified entity unit.

Parameters:
  • entity_slug (Union[EntityModel, str]) – The entity model or slug used to filter the queryset.

  • unit_slug (Union[EntityUnitModel, str]) – The entity unit model or slug used to filter the queryset.

  • user_model (Optional[UserModel], optional) – The user model to consider for filtering the queryset, by default None.

Returns:

The filtered queryset based on the specified entity unit.

Return type:

QuerySet

Notes

  • If unit_slug is an instance of EntityUnitModel, the queryset is filtered using journal_entry__entity_unit=unit_slug.

  • If unit_slug is a string, the queryset is filtered using journal_entry__entity_unit__slug__exact=unit_slug.

for_user(user_model) TransactionModelQuerySet#
Parameters:

user_model (User model object) – The user model object representing the user for whom to filter the transactions.

Returns:

A queryset of transaction models filtered based on the user’s permissions.

Return type:

TransactionModelQuerySet

Raises:
  • None

  • Description

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

  • This method filters the transactions based on the user's permissions.

  • If the user is a superuser, all transactions are returned. Otherwise, the transactions are filtered based on

  • the user's relationship to the entities associated with the transactions. Specifically, the transactions are

  • filtered to include only those where either the user is an admin of the entity associated with the transaction's

  • ledger or the user is one of the managers of the entity associated with the transaction's ledger.

get_queryset() TransactionModelQuerySet#

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

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

A custom QuerySet class for TransactionModels implementing methods to effectively and safely read TransactionModels from the database.

posted() TransactionModelQuerySet:#

Fetches a QuerySet of posted transactions only.

for_accounts(account_list: List[str or AccountModel]) TransactionModelQuerySet:#

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

for_roles(role_list: Union[str, List[str]]) TransactionModelQuerySet:#

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

for_unit(unit_slug: Union[str, EntityUnitModel]) TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels associated with a specific EntityUnitModel.

for_activity(activity_list: Union[str, List[str]]) TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels associated with a specific activity or list of activities.

to_date(to_date: Union[str, date, datetime]) TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels associated with a maximum date or timestamp filter.

from_date(from_date: Union[str, date, datetime]) TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels associated with a minimum date or timestamp filter.

not_closing_entry() TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels that are not part of a closing entry.

is_closing_entry() TransactionModelQuerySet:#

Fetches a QuerySet of TransactionModels that are part of a closing entry.

for_accounts(account_list: List[str])#

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

Parameters:

account_list (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_activity(activity_list: Union[str, List[str]])#

Fetches a QuerySet of TransactionModels associated with a specific activity or list of activities.

Parameters:

activity_list (str or list) – A string or list of strings representing the activity or activities used to filter the QuerySet.

Returns:

Returns a TransactionModelQuerySet with applied filters.

Return type:

TransactionModelQuerySet

for_roles(role_list: Union[str, List[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: Union[str, EntityUnitModel])#

Fetches a QuerySet of TransactionModels associated with a specific EntityUnitModel.

Parameters:

unit_slug (str or EntityUnitModel) – A string representing the unit slug used to filter the QuerySet.

Returns:

Returns a TransactionModelQuerySet with applied filters.

Return type:

TransactionModelQuerySet

from_date(from_date: Union[str, date, datetime])#

Fetches a QuerySet of TransactionModels associated with a minimum date or timestamp filter. May pass aware or naive date or timestamps. If naive is passed, it is assumed to be in localtime based on Django Settings.

Parameters:

from_date (str or date or datetime) – A string, date or datetime representing the minimum point in time used to filter the QuerySet. If date is used, dates are inclusive. (i.e 12/20/2022 will also include the 20th day).

Returns:

Returns a TransactionModelQuerySet with applied filters.

Return type:

TransactionModelQuerySet

is_closing_entry()#

Filter the Transactions based on whether they are closing entries or not.

Returns:

A filtered QuerySet of entries where the journal_entry__is_closing_entry field is True.

Return type:

QuerySet

not_closing_entry()#

Filter the Transactions based on whether they are closing entries or not.

Returns:

A filtered QuerySet of entries where the journal_entry__is_closing_entry field is False.

Return type:

QuerySet

posted() QuerySet#

Fetches a QuerySet of posted transactions only. Posted transactions are must meet the following criteria:

  • Be bart of a posted JournalEntryModel.

  • The associated JournalEntryModel must be part of a posted LedgerModel.

Returns:

A QuerySet with applied filters.

Return type:

TransactionModelQuerySet

to_date(to_date: Union[str, date, datetime])#

Fetches a QuerySet of TransactionModels associated with a maximum date or timestamp filter. May pass aware or naive date or timestamps. If naive is passed, it is assumed to be in localtime based on Django Settings.

Parameters:

to_date (str or date or datetime) – A string, date or datetime representing the maximum point in time used to filter the QuerySet. If date is used, dates are inclusive. (i.e 12/20/2022 will also include the 20th day).

Returns:

Returns a TransactionModelQuerySet with applied filters.

Return type:

TransactionModelQuerySet

exception django_ledger.models.transactions.TransactionModelValidationError(message, code=None, params=None)#
django_ledger.models.transactions.transactionmodel_presave(instance: TransactionModel, **kwargs)#
Parameters:
  • instance (TransactionModel) – The transaction model instance that is being saved.

  • kwargs (dict) – Additional keyword arguments.

Notes

This method is called before saving a transaction model instance. It performs some checks before allowing the save operation.

Raises:

TransactionModelValidationError – If one of the following conditions is met: - bypass_account_state is False and the can_transact method of the associated account model returns False. - The journal entry associated with the transaction is locked.

Journal Entry Model#

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

Contributions to this module:

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(value)#

The database string representation of each accounting activity prefix in the database.

OPERATING#

The database representation prefix of a Journal Entry that is an Operating Activity.

Type:

str

INVESTING#

The database representation prefix of a Journal Entry that is an Investing Activity.

Type:

str

FINANCING#

The database representation prefix of a Journal Entry that is an 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)#

The base implementation of the JournalEntryModel.

uuid#

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

Type:

UUID

je_number#

A unique, sequential, human-readable alphanumeric Journal Entry Number (a.k.a Voucher or Document Number in other commercial bookkeeping software). Contains the fiscal year under which the JE takes place within the EntityModel as a prefix.

Type:

str

timestamp#

The date of the JournalEntryModel. This date is applied to all TransactionModels contained within the JE, and drives the financial statements of the EntityModel.

Type:

datetime

description#

A user defined description for the JournalEntryModel.

Type:

str

entity_unit#

A logical, self-contained, user defined class or structure defined withing the EntityModel. See EntityUnitModel documentation for more details.

Type:

EntityUnitModel

activity#

Programmatically determined based on the JE transactions and must be a value from ACTIVITIES. Gives additional insight of the nature of the JournalEntryModel in order to produce the Statement of Cash Flows for the EntityModel.

Type:

str

origin#

A string giving additional information behind the origin or trigger of the JournalEntryModel. For example: reconciliations, migrations, auto-generated, etc. Any string value is valid. Max 30 characters.

Type:

str

posted#

Determines if the JournalLedgerModel is posted, which means is affecting the books. Defaults to False.

Type:

bool

locked#

Determines if the JournalEntryModel is locked, which the creation or updates of new transactions are not allowed.

Type:

bool

ledger#

The LedgerModel associated with this JournalEntryModel. Cannot be null.

Type:

LedgerModel

can_generate_je_number() bool#

Checks if the JournalEntryModel instance can generate its own JE number. Conditions are: * The JournalEntryModel must have a LedgerModel instance assigned. * The JournalEntryModel instance must not have a pre-existing JE number.

Returns:

True if JournalEntryModel needs a JE number, otherwise False.

Return type:

bool

can_lock() bool#

Determines if a JournalEntryModel can be locked. Locked JournalEntryModels cannot be modified.

Returns:

True if JournalEntryModel can be locked, otherwise False.

Return type:

bool

can_post(ignore_verify: bool = True) bool#

Determines if a JournalEntryModel can be posted.

Parameters:

ignore_verify (bool) – Skips JournalEntryModel verification if True. Defaults to False.

Returns:

True if JournalEntryModel can be posted, otherwise False.

Return type:

bool

can_unlock() bool#

Determines if a JournalEntryModel can be un-locked. Locked transactions cannot be modified.

Returns:

True if JournalEntryModel can be un-locked, otherwise False.

Return type:

bool

can_unpost() bool#

Determines if a JournalEntryModel can be un-posted.

Returns:

True if JournalEntryModel can be un-posted, otherwise False.

Return type:

bool

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

Customized JournalEntryModel clean method. Generates a JE number if needed. Optional verification hook on clean.

Parameters:
  • raise_exception (bool) – Raises exception if JE could not be verified. Defaults to True.

  • verify (bool) – Attempts to verify the JournalEntryModel during cleaning.

  • txs_qs (TransactionModelQuerySet) – Prefetched TransactionModelQuerySet. If provided avoids additional DB query. Will be verified against JournalEntryModel instance.

Returns:

tuple – The TransactionModelQuerySet of the JournalEntryModel instance, verification result as True/False.

Return type:

TransactionModelQuerySet, bool

generate_je_number(commit: bool = False) str#

Atomic Transaction. Generates the next Journal Entry document number available. The operation will result in two additional queries if the Journal Entry LedgerModel & EntityUnitModel are not cached in QuerySet via select_related(‘ledger’, ‘entity_unit’).

Parameters:

commit (bool) – Commits transaction into JournalEntryModel when function is called.

Returns:

A String, representing the new or current JournalEntryModel instance Document Number.

Return type:

str

get_activity_name() Optional[str]#

Returns a human-readable, GAAP string representing the JournalEntryModel activity.

Returns:

Representing the JournalEntryModel activity in the statement of cash flows.

Return type:

str or None

get_detail_txs_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_detail_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_transaction_queryset(select_accounts: bool = True) TransactionModelQuerySet#

Fetches the TransactionModelQuerySet associated with the JournalEntryModel instance.

Parameters:

select_accounts (bool) – Fetches the associated AccountModel of each transaction. Defaults to True.

Returns:

The TransactionModelQuerySet associated with the current JournalEntryModel instance.

Return type:

TransactionModelQuerySet

get_txs_balances(txs_qs: Optional[TransactionModelQuerySet] = None, as_dict: bool = False) Union[TransactionModelQuerySet, Dict]#

Fetches the sum total of CREDITs and DEBITs associated with the JournalEntryModel instance. This method performs a reduction/aggregation at the database level and fetches exactly two records. Optionally, may pass an existing TransactionModelQuerySet if previously fetched. Additional validation occurs to ensure that all TransactionModels in QuerySet are of the JE instance. Due to JournalEntryModel pre-save validation and basic rules of accounting, CREDITs and DEBITS will always match.

Parameters:
  • txs_qs (TransactionModelQuerySet) – The JE TransactionModelQuerySet to use if previously fetched. Will be validated to make sure all TransactionModel in QuerySet belong to the JournalEntryModel instance.

  • as_dict (bool) – If True, returns the result as a dictionary, with exactly two keys: ‘credit’ and ‘debit’. The values will be the total CREDIT or DEBIT amount as Decimal.

Examples

>>> je_model: JournalEntryModel = je_qs.first() # any existing JournalEntryModel QuerySet...
>>> balances = je_model.get_txs_balances()
>>> balances
Returns exactly two records:
<TransactionModelQuerySet [{'tx_type': 'credit', 'amount__sum': Decimal('2301.5')},
{'tx_type': 'debit', 'amount__sum': Decimal('2301.5')}]>

Examples

>>> balances = je_model.get_txs_balances(as_dict=True)
>>> balances
Returns a dictionary:
{'credit': Decimal('2301.5'), 'debit': Decimal('2301.5')}
Raises:

JournalEntryValidationError – If JE is not valid or TransactionModelQuerySet provided does not belong to JE instance.

Returns:

An aggregated queryset containing exactly two records. The total CREDIT or DEBIT amount as Decimal.

Return type:

TransactionModelQuerySet or dict

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

Determines the list of account roles involved in the JournalEntryModel instance. It reaches into the AccountModel associated with each TransactionModel of the JE to determine a Set of all roles involved in transactions. This method is important in determining the nature of the

Parameters:
  • txs_qs (TransactionModelQuerySet) – Prefetched TransactionModelQuerySet. Will be validated if provided. Avoids additional DB query if provided.

  • exclude_cash_role (bool) – Removes CASH role from the Set if present. Useful in some cases where cash role must be excluded for additional validation.

Returns:

The set of account roles as strings associated with the JournalEntryModel instance.

Return type:

set

is_balance_valid(txs_qs: Optional[TransactionModelQuerySet] = None) bool#

Checks if CREDITs and DEBITs are equal.

Parameters:

txs_qs (TransactionModelQuerySet) – Optional pre-fetched JE instance TransactionModelQuerySet. Will be validated if provided.

Returns:

True if JE balances are valid (i.e. are equal).

Return type:

bool

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

Validates a given TransactionModelQuerySet against the JournalEntryModel instance.

Parameters:
  • txs_qs (TransactionModelQuerySet) – The queryset to validate.

  • raise_exception (bool) – Raises JournalEntryValidationError if TransactionModelQuerySet is not valid.

Raises:

JournalEntryValidationError if JE model is invalid and raise_exception is True.

Returns:

True if valid, otherwise False.

Return type:

bool

is_verified() bool#

Determines if the JournalEntryModel is verified.

Returns:

True if is verified, otherwise False.

Return type:

bool

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.

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

  • verify (bool) – Verifies JournalEntryModel before marking as posted. Defaults to False.

  • force_lock (bool) – Forces to lock the JournalEntry before is posted.

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

  • kwargs (dict) – Additional keyword arguments.

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.

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

Custom JournalEntryModel instance save method. Additional options are added to attempt to verify JournalEntryModel before saving into database.

Parameters:
  • verify (bool) – If True, verifies JournalEntryModel transactions before saving. Defaults to True.

  • post_on_verify (bool) – Posts JournalEntryModel if verification is successful and can_post() is True.

Returns:

The saved instance.

Return type:

JournalEntryModel

verify(txs_qs: Optional[TransactionModelQuerySet] = None, force_verify: bool = False, raise_exception: bool = True, **kwargs) Tuple[TransactionModelQuerySet, bool]#
Verifies the JournalEntryModel. The JE Model is verified when:
  • All TransactionModels associated with the JE instance are in balance (i.e. the sum of CREDITs and DEBITs are equal).

  • If the JournalEntryModel is using cash, a cash flow activity is assigned.

Parameters:
  • txs_qs (TransactionModelQuerySet) – Prefetched TransactionModelQuerySet. If provided avoids additional DB query. Will be verified against JournalEntryModel instance.

  • force_verify (bool) – If True, forces new verification of JournalEntryModel if previously verified. Defaults to False.

  • raise_exception (bool) – If True, will raise JournalEntryValidationError if verification fails.

  • kwargs (dict) – Additional function key-word args.

Raises:

JournalEntryValidationError if JE instance could not be verified.

Returns:

tuple – The TransactionModelQuerySet of the JournalEntryModel instance, verification result as True/False.

Return type:

TransactionModelQuerySet, bool

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

A custom defined Journal Entry Model Manager that supports additional complex initial Queries based on the EntityModel and authenticated UserModel.

for_entity(entity_slug, user_model)#

Fetches a QuerySet of JournalEntryModels 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
>>> journal_entry_qs = JournalEntryModel.objects.for_entity(user_model=request_user, entity_slug=slug)
Returns:

Returns a JournalEntryModelQuerySet with applied filters.

Return type:

JournalEntryModelQuerySet

for_ledger(ledger_pk: Union[str, UUID], entity_slug, user_model)#

Fetches a QuerySet of JournalEntryModels associated with a specific EntityModel & UserModel & LedgerModel. 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.

  • ledger_pk (str or UUID) – The LedgerModel uuid as a string or UUID.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> ledger_pk = kwargs['ledger_pk'] # may come from request kwargs
>>> journal_entry_qs = JournalEntryModel.objects.for_ledger(ledger_pk=ledger_pk, user_model=request_user, entity_slug=slug)
Returns:

Returns a JournalEntryModelQuerySet with applied filters.

Return type:

JournalEntryModelQuerySet

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

Custom defined JournalEntryQuerySet.

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

Overrides the standard Django QuerySet create() method to avoid the creation of POSTED Journal Entries without proper business logic validation. New JEs using the create() method don’t have any transactions to validate. therefore, it is not necessary to query DB to balance TXS

Parameters:
  • verify_on_save (bool) – Executes a Journal Entry verification hook before saving. Avoids additional queries to validate the Journal Entry

  • force_create (bool) – If True, will create return a new JournalEntryModel even if Posted at time of creation. Use only if you know what you are doing.

Returns:

The newly created Journal Entry Model.

Return type:

JournalEntryModel

locked()#

Filters the QuerySet to only locked Journal Entries.

Returns:

A QuerySet with applied filters.

Return type:

JournalEntryModelQuerySet

posted()#

Filters the QuerySet to only posted Journal Entries.

Returns:

A QuerySet with applied filters.

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.

Contributions to this module:

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.BackAccountModelAbstract(*args, **kwargs)#

This is the main abstract class which the BankAccountModel database will inherit from. The BankAccountModel 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#

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

Type:

str

entity_model#

The EntityModel associated with the BankAccountModel instance.

Type:

EntityModel

cash_account#

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.BankAccountModel(*args, **kwargs)#

Base Bank Account Model Implementation

exception DoesNotExist#
exception MultipleObjectsReturned#
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.

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.

Contributions to this module:

Chart Of Accounts#

A Chart of Accounts (CoA) is a crucial collection of logically grouped accounts within a ChartOfAccountModel, forming the backbone of financial statements. The CoA includes various account roles such as cash, accounts receivable, expenses, liabilities, and income. For example, the Balance Sheet may have a Fixed Assets heading consisting of Tangible and Intangible Assets with multiple accounts like Building, Plant &amp; Equipments, and Machinery under tangible assets. Aggregation of individual account balances based on the Chart of Accounts and AccountModel roles is essential for preparing Financial Statements.

All EntityModel must have a default CoA to create any type of transaction. When no explicit CoA is specified, the default behavior is to use the EntityModel default CoA. Only ONE Chart of Accounts can be used when creating Journal Entries. No commingling between CoAs is allowed to preserve the integrity of the Journal Entry.

class django_ledger.models.coa.ChartOfAccountModel(*args, **kwargs)#

Base ChartOfAccounts Model

exception DoesNotExist#
exception MultipleObjectsReturned#
class django_ledger.models.coa.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: Optional[AccountModelQuerySet] = 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(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: Optional[AccountModelQuerySet] = 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: Optional[AccountModelQuerySet] = 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.coa.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_slug, 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

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

QuerySet method to retrieve active items.

exception django_ledger.models.coa.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.

Contributions to this module:

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. Expenses

  5. Revenue

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

1200

asset_ca_inv

debit

Inventory

root_assets

1050

asset_ca_mkt_sec

debit

Short Term Investments

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

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: Optional[Dict] = 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.

Contributions to this module:

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.

Contributions to this module:

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: Union[str, EntityModel], user_model: Optional[User] = None, date_draft: Optional[Union[datetime, date]] = None, ledger_posted: bool = False, ledger_name: Optional[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() Optional[str]#

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: Optional[ItemTransactionModelQuerySet] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[ItemTransactionModelQuerySet] = 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() Optional[date]#

Date where BillModel term start to apply.

Returns:

A date which represents the start of BillModel terms.

Return type:

date

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: Union[Decimal, float, int], payment_date: Optional[Union[datetime, date]] = 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: Optional[str] = None, date_approved: Optional[Union[datetime, date]] = 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: Optional[date] = 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: Optional[date] = 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: Optional[str] = None, date_paid: Optional[Union[datetime, date]] = None, itemtxs_qs: Optional[ItemTransactionModelQuerySet] = 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: Optional[ItemTransactionModelQuerySet] = None, date_in_review: Optional[date] = 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: Optional[str] = None, date_void: Optional[date] = 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: Optional[Union[ItemTransactionModelQuerySet, List[ItemTransactionModel]]] = 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: Union[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.

Contributions to this module:

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: Union[EntityModel, UUID, str], customer_model: CustomerModel, user_model: Optional[User] = None, date_draft: Optional[date] = None, estimate_title: Optional[str] = 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: Optional[PurchaseOrderModelQuerySet] = None, bill_qs: Optional[BillModelQuerySet] = None, invoice_qs: Optional[InvoiceModelQuerySet] = 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) Union[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: Optional[ItemTransactionModelQuerySet] = 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: Optional[Union[ItemTransactionModelQuerySet, List[ItemTransactionModel]]] = 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: Optional[date] = None)#

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: Optional[date] = None)#

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: Optional[date] = None)#

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

Marks the current EstimateModel instance as Draft.

Parameters:

commit (bool) – Commits transaction into current EstimateModel instance.

mark_as_review(itemtxs_qs: Optional[ItemTransactionModelQuerySet] = None, date_in_review: Optional[date] = None, commit: bool = True)#

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: Optional[date] = None)#

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: Optional[ItemTransactionModelQuerySet] = 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: Optional[ItemTransactionModelQuerySet] = 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: Union[ItemTransactionModelQuerySet, List[ItemTransactionModel]])#

Validates that the entire ItemTransactionModelQuerySet is bound to the BillModel.

Parameters:

itemtxs_qs (ItemTransactionModelQuerySet) – ItemTransactionModelQuerySet to validate.

validate_itemtxs_qs(queryset: Union[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: Union[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.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> bill_model_qs = EstimateModel.objects.for_entity(user_model=request_user, entity_slug=slug)
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.

Contributions to this module:

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: Union[str, EntityModel], po_title: Optional[str] = None, user_model: Optional[User] = None, draft_date: Optional[date] = 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: Optional[Union[ItemTransactionModelQuerySet, List[ItemTransactionModel]]] = 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: Optional[date] = 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: Optional[date] = 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: Optional[date] = 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: Optional[date] = None, po_items: Optional[Union[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: Optional[date] = 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: Optional[date] = 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: Optional[Union[ItemTransactionModelQuerySet, List[ItemTransactionModel]]] = 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: Union[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.

Contributions to this module:

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: Union[EntityModel, str], user_model: Optional[User] = None, date_draft: Optional[date] = None, ledger_posted: bool = False, ledger_name: Optional[str] = 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: Optional[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: Optional[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: Optional[ItemTransactionModelQuerySet] = 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

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: Union[Decimal, float, int], payment_date: Optional[Union[datetime, date]] = 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: Optional[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: Optional[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: Union[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: Optional[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: Optional[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: Optional[Union[datetime, date]] = 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: Optional[ItemTransactionModelQuerySet] = 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.

Contributions to this module:

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#

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.

Examples

>>> request_user = request.user
>>> slug = kwargs['entity_slug'] # may come from request kwargs
>>> customer_model_qs = CustomerModel.objects.for_entity(user_model=request_user, entity_slug=slug)
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.

Examples

>>> request_user = request.user
>>> customer_model_qs = CustomerModel.objects.for_user(user_model=request_user)
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.

Contributions to this module:

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.

Contributions to this module:

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() Union[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() Union[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() Union[Decimal, float]#

Determines the open amount left to be progressed.

Returns:

Financial instrument amount open.

Return type:

float or Decimal

get_amount_prepaid() Union[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() Union[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() Union[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: Optional[QuerySet] = None, force_migrate: bool = False, commit: bool = True, void: bool = False, je_timestamp: Optional[Union[date, datetime, str]] = 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: Union[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: Optional[Dict] = 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.BankAccountInfoMixIn(*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

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.

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() Optional[int]#

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.