1336 lines
54 KiB
Python
1336 lines
54 KiB
Python
from django.contrib.auth.models import Group
|
|
from decimal import Decimal
|
|
from django.db.models.signals import post_save, post_delete, pre_delete, pre_save
|
|
from inventory.models import VatRate
|
|
from plans.quota import get_user_quota
|
|
from .utils import to_dict
|
|
from django.dispatch import receiver
|
|
from django.utils.translation import gettext_lazy as _
|
|
from django.contrib.auth import get_user_model
|
|
from django_ledger.io import roles
|
|
from django_ledger.models import (
|
|
EntityModel,
|
|
AccountModel,
|
|
ItemModel,
|
|
ItemModelAbstract,
|
|
UnitOfMeasureModel,
|
|
VendorModel,
|
|
EstimateModel,
|
|
CustomerModel,
|
|
JournalEntryModel,
|
|
TransactionModel,
|
|
LedgerModel,
|
|
BillModel,
|
|
ItemTransactionModel
|
|
)
|
|
from . import models
|
|
from django.utils.timezone import now
|
|
from django.db import transaction
|
|
from django.core.exceptions import ValidationError
|
|
|
|
|
|
User = get_user_model()
|
|
|
|
# @receiver(post_save, sender=models.SaleQuotation)
|
|
# def link_quotation_to_entity(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# # Get the corresponding Django Ledger entity for the dealer
|
|
# entity = EntityModel.objects.get(name=instance.dealer.get_root_dealer.name)
|
|
# instance.entity = entity
|
|
# instance.save()
|
|
# @receiver(pre_delete, sender=models.Dealer)
|
|
# def remove_user_account(sender, instance, **kwargs):
|
|
# user = instance.user
|
|
# if user:
|
|
# user.delete()
|
|
#
|
|
# @receiver(post_save, sender=User)
|
|
# def create_dealer(instance, created, *args, **kwargs):
|
|
# if created:
|
|
# if not instance.dealer:
|
|
#
|
|
# models.Dealer.objects.create(user=instance,name=instance.username,email=instance.email)
|
|
#
|
|
# @receiver(post_save, sender=models.Dealer)
|
|
# def create_user_account(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# if instance.dealer_type != "Owner":
|
|
# user = User.objects.create_user(
|
|
# username=instance.name,
|
|
# email=instance.email,
|
|
# )
|
|
# user.set_password("Tenhal@123")
|
|
# user.save()
|
|
# instance.user = user
|
|
# instance.save()
|
|
|
|
|
|
# check with marwan
|
|
@receiver(post_save, sender=models.Car)
|
|
def create_car_location(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler to create a CarLocation entry when a new Car instance is created.
|
|
The function ensures that the associated Car has a dealer before creating its
|
|
CarLocation. If the dealer is missing, a ValueError is raised, and an error
|
|
message is logged.
|
|
|
|
:param sender: The model class that sends the signal, typically `models.Car`.
|
|
:type sender: Type[models.Model]
|
|
:param instance: The actual instance of the Car model that triggered the signal.
|
|
:param created: A boolean value indicating whether a new record was created.
|
|
:type created: bool
|
|
:param kwargs: Additional keyword arguments provided with the signal.
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
try:
|
|
if created:
|
|
if instance.dealer is None:
|
|
raise ValueError(
|
|
f"Cannot create CarLocation for car {instance.vin}: dealer is missing."
|
|
)
|
|
|
|
models.CarLocation.objects.create(
|
|
car=instance,
|
|
owner=instance.dealer,
|
|
showroom=instance.dealer,
|
|
description=f"Initial location set for car {instance.vin}.",
|
|
)
|
|
except Exception as e:
|
|
print(f"Failed to create CarLocation for car {instance.vin}: {e}")
|
|
|
|
# Create Entity
|
|
@receiver(post_save, sender=models.Dealer)
|
|
def create_ledger_entity(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler for creating ledger entities and initializing accounts for a new Dealer instance upon creation.
|
|
|
|
This signal is triggered when a new Dealer instance is saved to the database. It performs the following actions:
|
|
1. Creates a ledger entity for the Dealer with necessary configurations.
|
|
2. Generates a chart of accounts (COA) for the entity and assigns it as the default.
|
|
3. Creates predefined unit of measures (UOMs) related to the entity.
|
|
4. Initializes and assigns default accounts under various roles (e.g., assets, liabilities) for the entity with their
|
|
respective configurations (e.g., account code, balance type).
|
|
|
|
This function ensures all necessary financial records and accounts are set up when a new Dealer is added, preparing the
|
|
system for future financial transactions and accounting operations.
|
|
|
|
:param sender: The model class that sent the signal (in this case, Dealer).
|
|
:param instance: The instance of the model being saved.
|
|
:param created: A boolean indicating whether a new record was created.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
entity_name = instance.user.dealer.name
|
|
entity = EntityModel.create_entity(
|
|
name=entity_name,
|
|
admin=instance.user,
|
|
use_accrual_method=True,
|
|
fy_start_month=1,
|
|
)
|
|
|
|
if entity:
|
|
instance.entity = entity
|
|
instance.save()
|
|
coa = entity.create_chart_of_accounts(
|
|
assign_as_default=True, commit=True, coa_name=_(f"{entity_name}-COA")
|
|
)
|
|
if coa:
|
|
# Create unit of measures
|
|
entity.create_uom(name="Unit", unit_abbr="unit")
|
|
for u in models.UnitOfMeasure.choices:
|
|
entity.create_uom(name=u[1], unit_abbr=u[0])
|
|
|
|
# Cash Account
|
|
asset_ca_cash = entity.create_account(
|
|
coa_model=coa,
|
|
code="1101",
|
|
role=roles.ASSET_CA_CASH,
|
|
name=_("Cash"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_ca_cash.role_default = True
|
|
asset_ca_cash.save()
|
|
|
|
# Accounts Receivable Account
|
|
asset_ca_receivables = entity.create_account(
|
|
coa_model=coa,
|
|
code="1102",
|
|
role=roles.ASSET_CA_RECEIVABLES,
|
|
name=_("Accounts Receivable"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_ca_receivables.role_default = True
|
|
asset_ca_receivables.save()
|
|
|
|
# Inventory Account
|
|
asset_ca_inventory = entity.create_account(
|
|
coa_model=coa,
|
|
code="1103",
|
|
role=roles.ASSET_CA_INVENTORY,
|
|
name=_("Inventory"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_ca_inventory.role_default = True
|
|
asset_ca_inventory.save()
|
|
|
|
|
|
# Prepaid Expenses Account
|
|
asset_ca_prepaid = entity.create_account(
|
|
coa_model=coa,
|
|
code="1104",
|
|
role=roles.ASSET_CA_PREPAID,
|
|
name=_("Prepaid Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_ca_prepaid.role_default = True
|
|
asset_ca_prepaid.save()
|
|
|
|
# Employee Expenses Account
|
|
asset_ca_prepaid_employee = entity.create_account(
|
|
coa_model=coa,
|
|
code="1105",
|
|
role=roles.ASSET_CA_PREPAID,
|
|
name=_("Employee Advance"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
|
|
# VAT Payable Account
|
|
liability_ltl_vat_receivable = entity.create_account(
|
|
coa_model=coa,
|
|
code="1106",
|
|
role=roles.ASSET_CA_RECEIVABLES,
|
|
name=_("VAT Receivable"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Buildings Accumulated Depreciation Account
|
|
asset_ppe_buildings_accum_depreciation = entity.create_account(
|
|
coa_model=coa,
|
|
code="1201",
|
|
role=roles.ASSET_PPE_BUILDINGS_ACCUM_DEPRECIATION,
|
|
name=_("Buildings - Accum. Depreciation"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
asset_ppe_buildings_accum_depreciation.role_default = True
|
|
asset_ppe_buildings_accum_depreciation.save()
|
|
|
|
# intangible Account
|
|
asset_lti_land_intangable = entity.create_account(
|
|
coa_model=coa,
|
|
code="1202",
|
|
role=roles.ASSET_INTANGIBLE_ASSETS,
|
|
name=_("Intangible Assets"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_lti_land_intangable.role_default = True
|
|
asset_lti_land_intangable.save()
|
|
|
|
# investment property Account
|
|
asset_lti_land_investment = entity.create_account(
|
|
coa_model=coa,
|
|
code="1204",
|
|
role=roles.ASSET_LTI_SECURITIES,
|
|
name=_("Investments"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_lti_land_investment.role_default = True
|
|
asset_lti_land_investment.save()
|
|
|
|
# # Notes Receivable Account
|
|
# asset_lti_notes_receivable = entity.create_account(
|
|
# coa_model=coa,
|
|
# code="1201",
|
|
# role=roles.ASSET_LTI_NOTES_RECEIVABLE,
|
|
# name=_("Notes Receivable"),
|
|
# balance_type="debit",
|
|
# active=True,
|
|
# )
|
|
# asset_lti_notes_receivable.role_default = True
|
|
# asset_lti_notes_receivable.save()
|
|
|
|
# # Land Account
|
|
# asset_lti_land = entity.create_account(
|
|
# coa_model=coa,
|
|
# code="1202",
|
|
# role=roles.ASSET_LTI_LAND,
|
|
# name=_("Land"),
|
|
# balance_type="debit",
|
|
# active=True,
|
|
# )
|
|
# asset_lti_land.role_default = True
|
|
# asset_lti_land.save()
|
|
|
|
|
|
# Buildings Account
|
|
asset_ppe_buildings = entity.create_account(
|
|
coa_model=coa,
|
|
code="1301",
|
|
role=roles.ASSET_PPE_BUILDINGS,
|
|
name=_("Buildings"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
asset_ppe_buildings.role_default = True
|
|
asset_ppe_buildings.save()
|
|
|
|
|
|
|
|
# Accounts Payable Account
|
|
liability_cl_acc_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2101",
|
|
role=roles.LIABILITY_CL_ACC_PAYABLE,
|
|
name=_("Accounts Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
liability_cl_acc_payable.role_default = True
|
|
liability_cl_acc_payable.save()
|
|
|
|
# Deferred Revenue Account
|
|
liability_cl_def_rev = entity.create_account(
|
|
coa_model=coa,
|
|
code="2103",
|
|
role=roles.LIABILITY_CL_DEFERRED_REVENUE,
|
|
name=_("Deferred Revenue"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
liability_cl_def_rev.role_default = True
|
|
liability_cl_def_rev.save()
|
|
|
|
# Wages Payable Account
|
|
liability_cl_wages_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2102",
|
|
role=roles.LIABILITY_CL_WAGES_PAYABLE,
|
|
name=_("Wages Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
liability_cl_wages_payable.role_default = True
|
|
liability_cl_wages_payable.save()
|
|
|
|
# Long-Term Notes Payable Account
|
|
liability_ltl_notes_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2201",
|
|
role=roles.LIABILITY_LTL_NOTES_PAYABLE,
|
|
name=_("Long-Term Notes Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
liability_ltl_notes_payable.role_default = True
|
|
liability_ltl_notes_payable.save()
|
|
|
|
# VAT Payable Account
|
|
liability_ltl_vat_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2106",
|
|
role=roles.LIABILITY_CL_OTHER,
|
|
name=_("VAT Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
|
|
# taxes Payable Account
|
|
liability_ltl_taxes_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2107",
|
|
role=roles.LIABILITY_CL_OTHER,
|
|
name=_("Taxes Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
|
|
# social insurance Payable Account
|
|
liability_ltl_social_insurance_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2108",
|
|
role=roles.LIABILITY_LTL_NOTES_PAYABLE,
|
|
name=_("Social Insurance Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
|
|
# End of Service Benefits
|
|
entity.create_account(coa_model=coa, code="2202", role=roles.LIABILITY_LTL_NOTES_PAYABLE, name=_("End of Service Benefits"), balance_type="credit", active=True)
|
|
|
|
# Mortgage Payable Account
|
|
liability_ltl_mortgage_payable = entity.create_account(
|
|
coa_model=coa,
|
|
code="2203",
|
|
role=roles.LIABILITY_LTL_MORTGAGE_PAYABLE,
|
|
name=_("Mortgage Payable"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
liability_ltl_mortgage_payable.role_default = True
|
|
liability_ltl_mortgage_payable.save()
|
|
|
|
# Capital
|
|
equity_capital = entity.create_account(coa_model=coa, code="3101", role=roles.EQUITY_CAPITAL, name=_("Registered Capital"), balance_type="credit", active=True)
|
|
equity_capital.role_default = True
|
|
equity_capital.save()
|
|
entity.create_account(coa_model=coa, code="3102", role=roles.EQUITY_CAPITAL, name=_("Additional Paid-In Capital"), balance_type="credit", active=True)
|
|
|
|
# Other Equity
|
|
other_equity = entity.create_account(coa_model=coa, code="3201", role=roles.EQUITY_COMMON_STOCK, name=_("Opening Balances"), balance_type="credit", active=True)
|
|
other_equity.role_default = True
|
|
other_equity.save()
|
|
|
|
# Reserves
|
|
reserve = entity.create_account(coa_model=coa, code="3301", role=roles.EQUITY_ADJUSTMENT, name=_("Statutory Reserve"), balance_type="credit", active=True)
|
|
reserve.role_default = True
|
|
reserve.save()
|
|
entity.create_account(coa_model=coa, code="3302", role=roles.EQUITY_ADJUSTMENT, name=_("Foreign Currency Translation Reserve"), balance_type="credit", active=True)
|
|
|
|
# Retained Earnings Account
|
|
equity_retained_earnings = entity.create_account(
|
|
coa_model=coa,
|
|
code="3401",
|
|
role=roles.EQUITY_PREFERRED_STOCK,
|
|
name=_("Operating Profits and Losses"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
equity_retained_earnings.role_default = True
|
|
equity_retained_earnings.save()
|
|
|
|
equity_retained_earnings_losses = entity.create_account(
|
|
coa_model=coa,
|
|
code="3402",
|
|
role=roles.EQUITY_PREFERRED_STOCK,
|
|
name=_("Retained Earnings (or Losses)"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
|
|
# Sales Revenue Account
|
|
income_operational = entity.create_account(
|
|
coa_model=coa,
|
|
code="4101",
|
|
role=roles.INCOME_OPERATIONAL,
|
|
name=_("Sales Revenue"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
income_operational.role_default = True
|
|
income_operational.save()
|
|
|
|
# Interest Income Account
|
|
income_interest = entity.create_account(
|
|
coa_model=coa,
|
|
code="4102",
|
|
role=roles.INCOME_INTEREST,
|
|
name=_("Interest Income"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
income_interest.role_default = True
|
|
income_interest.save()
|
|
|
|
# Uneared Income Account
|
|
income_unearned = entity.create_account(
|
|
coa_model=coa,
|
|
code="4103",
|
|
role=roles.INCOME_OTHER,
|
|
name=_("Unearned Income"),
|
|
balance_type="credit",
|
|
active=True,
|
|
)
|
|
|
|
# Operating Revenues
|
|
entity.create_account(coa_model=coa, code="4104", role=roles.INCOME_OPERATIONAL, name=_("Sales/Service Revenue"), balance_type="credit", active=True)
|
|
|
|
#Non-Operating Revenues
|
|
entity.create_account(coa_model=coa, code="4201", role=roles.INCOME_OTHER, name=_("Non-Operating Revenues"), balance_type="credit", active=True)
|
|
|
|
|
|
# Cost of Goods Sold (COGS) Account
|
|
expense_cogs = entity.create_account(
|
|
coa_model=coa,
|
|
code="5101",
|
|
role=roles.COGS,
|
|
name=_("Cost of Goods Sold"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
expense_cogs.role_default = True
|
|
expense_cogs.save()
|
|
|
|
|
|
# accrued Expenses Account
|
|
expense_cogs = entity.create_account(
|
|
coa_model=coa,
|
|
code="6117",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Accrued Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# accrued salaries Account
|
|
expense_cogs = entity.create_account(
|
|
coa_model=coa,
|
|
code="6118",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Accrued Salaries"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Rent Expense Account
|
|
expense_rent = entity.create_account(
|
|
coa_model=coa,
|
|
code="6102",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Rent Expense"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
# expense_rent.role_default = True
|
|
# expense_rent.save()
|
|
|
|
# Salaries and Administrative Fees
|
|
expense_salaries = entity.create_account(
|
|
coa_model=coa,
|
|
code="6103",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Salaries and Administrative Fees"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Medical Insurance
|
|
expense_medical_insurance = entity.create_account(
|
|
coa_model=coa,
|
|
code="6104",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Medical Insurance"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Marketing and Advertising Expenses
|
|
expense_marketing = entity.create_account(
|
|
coa_model=coa,
|
|
code="6105",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Marketing and Advertising Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Commissions and Incentives
|
|
expense_commissions = entity.create_account(
|
|
coa_model=coa,
|
|
code="6106",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Commissions and Incentives"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Travel Tickets
|
|
expense_travel = entity.create_account(
|
|
coa_model=coa,
|
|
code="6107",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Travel Tickets"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Social Insurance
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6108",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Social Insurance"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Government Fees
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6109",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Government Fees"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Fees and Subscriptions
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6110",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Fees and Subscriptions"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Office Services Expenses
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6111",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Office Services Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Office Supplies and Printing
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6112",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Office Supplies and Printing"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Hospitality Expenses
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6113",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Hospitality Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Bank Commissions
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6114",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Bank Commissions"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Other Expenses
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6115",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Other Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# Transportation Expenses
|
|
expense_other = entity.create_account(
|
|
coa_model=coa,
|
|
code="6116",
|
|
role=roles.EXPENSE_OPERATIONAL,
|
|
name=_("Transportation Expenses"),
|
|
balance_type="debit",
|
|
active=True,
|
|
)
|
|
|
|
# 5.1 Direct Costs
|
|
entity.create_account(coa_model=coa, code="6201", role=roles.EXPENSE_OPERATIONAL, name=_("Cost of Goods Sold"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6202", role=roles.EXPENSE_OPERATIONAL, name=_("Salaries and Wages"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6203", role=roles.EXPENSE_OPERATIONAL, name=_("Sales Commissions"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6204", role=roles.EXPENSE_OPERATIONAL, name=_("Shipping and Customs Clearance"), balance_type="debit", active=True)
|
|
|
|
# 5.3 Non-Operating Expenses
|
|
entity.create_account(coa_model=coa, code="6301", role=roles.EXPENSE_OTHER, name=_("Zakat"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6302", role=roles.EXPENSE_OTHER, name=_("Taxes"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6303", role=roles.EXPENSE_OTHER, name=_("Foreign Currency Translation"), balance_type="debit", active=True)
|
|
entity.create_account(coa_model=coa, code="6304", role=roles.EXPENSE_OTHER, name=_("Interest Expenses"), balance_type="debit", active=True)
|
|
|
|
@receiver(post_save, sender=models.Dealer)
|
|
def create_dealer_groups(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler to create and assign default groups to a Dealer instance when it
|
|
is created. The groups are based on predefined names and assigned specific
|
|
permissions. Uses transaction hooks to ensure groups are created only after
|
|
successful database commit.
|
|
|
|
:param sender: The model class that triggered the signal.
|
|
:type sender: Type[models.Model]
|
|
:param instance: The instance of the model class that caused the signal to fire.
|
|
:param created: Boolean indicating whether an instance was newly created.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:type kwargs: dict
|
|
"""
|
|
group_names = ["Inventory", "Accountant", "Sales"]
|
|
|
|
def create_groups():
|
|
for group_name in group_names:
|
|
group, created = Group.objects.get_or_create(name=f"{instance.pk}_{group_name}")
|
|
group_manager,created = models.CustomGroup.objects.get_or_create(name=group_name, dealer=instance, group=group)
|
|
group_manager.set_default_permissions()
|
|
instance.user.groups.add(group)
|
|
|
|
transaction.on_commit(create_groups)
|
|
# Create Vendor
|
|
@receiver(post_save, sender=models.Vendor)
|
|
def create_ledger_vendor(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal function that listens for the `post_save` event on the Vendor model.
|
|
This function is triggered after a Vendor instance is saved. If the instance
|
|
is newly created (`created` is True), it will create necessary related entities
|
|
such as a Vendor model in the corresponding Entity and an Account for that Vendor.
|
|
|
|
:param sender: The model class that triggered the signal event, which is `models.Vendor`.
|
|
:param instance: The specific instance of the `models.Vendor` that was saved.
|
|
:param created: A boolean indicating whether the instance is newly created (`True`)
|
|
or updated (`False`).
|
|
:param kwargs: Additional keyword arguments passed by the signal dispatcher.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
entity = EntityModel.objects.filter(name=instance.dealer.name).first()
|
|
additionals = to_dict(instance)
|
|
vendor = entity.create_vendor(
|
|
vendor_model_kwargs={
|
|
"vendor_name": instance.name,
|
|
"vendor_number": instance.crn,
|
|
"address_1": instance.address,
|
|
"phone": instance.phone_number,
|
|
"email": instance.email,
|
|
"tax_id_number": instance.vrn,
|
|
"active": True,
|
|
"hidden": False,
|
|
"additional_info": additionals,
|
|
}
|
|
)
|
|
|
|
|
|
coa = entity.get_default_coa()
|
|
last_account = entity.get_all_accounts().filter(role=roles.LIABILITY_CL_ACC_PAYABLE).order_by('-created').first()
|
|
# code = f"{int(last_account.code)}{1:03d}"
|
|
if len(last_account.code) == 4:
|
|
code = f"{int(last_account.code)}{1:03d}"
|
|
elif len(last_account.code) > 4:
|
|
code = f"{int(last_account.code)+1}"
|
|
|
|
account = entity.create_account(
|
|
name=instance.name,
|
|
code=code,
|
|
role=roles.LIABILITY_CL_ACC_PAYABLE,
|
|
coa_model=coa,
|
|
balance_type="credit",
|
|
active=True
|
|
)
|
|
print(f"VendorModel created for Vendor: {instance.name}")
|
|
|
|
@receiver(post_save, sender=models.CustomerModel)
|
|
def create_customer_user(sender, instance, created, **kwargs):
|
|
"""
|
|
Connects to the `post_save` signal of the `CustomerModel` to create a user object
|
|
associated with the customer instance whenever a new `CustomerModel` instance is
|
|
created. Retrieves customer-specific information from `additional_info` to initialize
|
|
and configure the associated user object. Ensures the user object created has
|
|
unusable passwords by default.
|
|
|
|
:param sender: The model class that sends the signal (`CustomerModel`).
|
|
:param instance: The instance of `CustomerModel` that triggered the signal.
|
|
:param created: A boolean indicating whether a new instance was created.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
try:
|
|
first_name = instance.additional_info.get("customer_info").get("first_name")
|
|
last_name = instance.additional_info.get("customer_info").get("last_name")
|
|
user = User.objects.create(
|
|
username=instance.email,
|
|
email=instance.email,
|
|
first_name=first_name if first_name else '',
|
|
last_name=last_name if last_name else '',
|
|
)
|
|
instance.additional_info.update({"user_info": to_dict(user)})
|
|
user.set_unusable_password()
|
|
user.save()
|
|
instance.user = user
|
|
instance.save()
|
|
except Exception as e:
|
|
print(e)
|
|
|
|
# Create Item
|
|
@receiver(post_save, sender=models.Car)
|
|
def create_item_model(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler that triggers upon saving a `Car` model instance. This function is responsible
|
|
for creating or updating an associated product in the related entity's inventory system. The
|
|
new product is created only if it does not already exist, and additional information about the
|
|
car is added to the product's metadata.
|
|
|
|
:param sender: Signal sender, typically the model class triggering the save event.
|
|
:type sender: type
|
|
:param instance: Instance of the `Car` model that was saved.
|
|
:type instance: models.Car
|
|
:param created: Flag indicating whether the model instance was newly created.
|
|
:type created: bool
|
|
:param kwargs: Additional keyword arguments passed by the signal mechanism.
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
entity = instance.dealer.entity
|
|
if created:
|
|
coa = entity.get_default_coa()
|
|
uom = entity.get_uom_all().get(name="Unit")
|
|
|
|
if not entity.get_items_all().filter(name=instance.vin).exists():
|
|
product = entity.create_item_product(
|
|
name=instance.vin,
|
|
item_type=ItemModel.ITEM_TYPE_MATERIAL,
|
|
uom_model=uom,
|
|
coa_model=coa,
|
|
)
|
|
product.additional_info = {}
|
|
product.save()
|
|
|
|
product = entity.get_items_all().filter(name=instance.vin).first()
|
|
product.additional_info.update({'car_info': instance.to_dict()})
|
|
product.save()
|
|
|
|
# # update price - CarFinance
|
|
@receiver(post_save, sender=models.CarFinance)
|
|
def update_item_model_cost(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler for updating an inventory item's cost and additional information
|
|
when a CarFinance instance is saved. This function updates the corresponding
|
|
inventory item of the car dealer's entity associated with the car's VIN by
|
|
modifying its default amount and updating additional data fields.
|
|
|
|
:param sender: The model class that triggered the signal.
|
|
:param instance: The instance of the CarFinance that was saved.
|
|
:param created: A boolean indicating whether the model instance was newly created.
|
|
:param kwargs: Additional keyword arguments passed during the signal invocation.
|
|
:return: None
|
|
"""
|
|
entity = instance.car.dealer.entity
|
|
|
|
product = entity.get_items_all().filter(name=instance.car.vin).first()
|
|
|
|
product.default_amount = instance.selling_price
|
|
if not isinstance(product.additional_info, dict):
|
|
product.additional_info = {}
|
|
product.additional_info.update({"car_finance":instance.to_dict()})
|
|
product.additional_info.update({"additional_services": [service.to_dict() for service in instance.additional_services.all()]})
|
|
product.save()
|
|
print(f"Inventory item updated with CarFinance data for Car: {instance.car}")
|
|
|
|
|
|
# @receiver(pre_save, sender=models.SaleQuotation)
|
|
# def update_quotation_status(sender, instance, **kwargs):
|
|
# if instance.valid_until and timezone.now() > instance.valid_until:
|
|
# instance.status = 'expired'
|
|
# # instance.total_price = instance.calculate_total_price()
|
|
#
|
|
#
|
|
# @receiver(post_save, sender=models.Payment)
|
|
# def update_status_on_payment(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# quotation = instance.sale_quotation
|
|
# total_payments = sum(payment.amount for payment in quotation.payments.all())
|
|
# if total_payments >= quotation.amount:
|
|
# quotation.status = 'completed'
|
|
# # SalesInvoice.objects.create(sales_order=order)
|
|
# elif total_payments > 0:
|
|
# quotation.status = 'partially_paid'
|
|
# else:
|
|
# quotation.status = 'pending'
|
|
# quotation.save()
|
|
|
|
@receiver(post_save, sender=models.CarColors)
|
|
def update_car_when_color_changed(sender, instance, **kwargs):
|
|
"""
|
|
Signal receiver to handle updates to a car instance when its related
|
|
CarColors instance is modified. Triggered by the `post_save` signal
|
|
for the `CarColors` model. Ensures that the associated `Car` instance
|
|
is saved, propagating changes effectively.
|
|
|
|
:param sender: The model class (`CarColors`) that was saved.
|
|
:type sender: Type[models.CarColors]
|
|
:param instance: The specific instance of `CarColors` that was saved.
|
|
:type instance: models.CarColors
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
car = instance.car
|
|
car.save()
|
|
|
|
@receiver(post_save, sender=models.Opportunity)
|
|
def notify_staff_on_deal_stage_change(sender, instance, **kwargs):
|
|
"""
|
|
Notify staff members when the stage of an Opportunity is updated. This function listens to the `post_save`
|
|
signal for the Opportunity model and triggers a notification if the stage attribute of the Opportunity
|
|
instance has been changed.
|
|
|
|
:param sender: The model class that sends the signal.
|
|
:type sender: type[models.Opportunity]
|
|
:param instance: The actual instance being saved in the Django ORM.
|
|
:type instance: models.Opportunity
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
if instance.pk:
|
|
previous = models.Opportunity.objects.get(pk=instance.pk)
|
|
if previous.stage != instance.stage:
|
|
message = f"Opportunity '{instance.pk}' status changed from {previous.stage} to {instance.stage}."
|
|
models.Notification.objects.create(
|
|
staff=instance.created_by, message=message
|
|
)
|
|
|
|
|
|
# @receiver(post_save, sender=models.Opportunity)
|
|
# def log_opportunity_creation(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# models.OpportunityLog.objects.create(
|
|
# opportunity=instance,
|
|
# action="create",
|
|
# user=instance.created_by,
|
|
# details=f"Opportunity '{instance.deal_name}' was created.",
|
|
# )
|
|
|
|
|
|
# @receiver(pre_save, sender=models.Opportunity)
|
|
# def log_opportunity_update(sender, instance, **kwargs):
|
|
# if instance.pk:
|
|
# previous = models.Opportunity.objects.get(pk=instance.pk)
|
|
# if previous.stage != instance.deal_status:
|
|
# models.OpportunityLog.objects.create(
|
|
# opportunity=instance,
|
|
# action="status_change",
|
|
# user=instance.created_by,
|
|
# old_status=previous.deal_status,
|
|
# new_status=instance.deal_status,
|
|
# details=f"Status changed from {previous.deal_status} to {instance.deal_status}.",
|
|
# )
|
|
# else:
|
|
# models.OpportunityLog.objects.create(
|
|
# opportunity=instance,
|
|
# action="update",
|
|
# user=instance.created_by,
|
|
# details=f"Opportunity '{instance.deal_name}' was updated.",
|
|
# )
|
|
|
|
|
|
@receiver(post_save, sender=models.AdditionalServices)
|
|
def create_item_service(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler for creating a service item in the ItemModel when a new
|
|
AdditionalServices instance is created. This function listens to the
|
|
post_save signal of the AdditionalServices model and sets up the related
|
|
ItemModel instance to represent the service.
|
|
|
|
:param sender: The model class that sent the signal.
|
|
:param instance: The instance of the model being saved.
|
|
:param created: Boolean indicating whether a new instance was created.
|
|
:param kwargs: Additional keyword arguments provided by the signal.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
entity = instance.dealer.entity
|
|
uom = entity.get_uom_all().get(unit_abbr=instance.uom)
|
|
cogs = entity.get_all_accounts().get(role=roles.COGS)
|
|
|
|
service_model = ItemModel.objects.create(
|
|
name=instance.name,
|
|
uom=uom,
|
|
default_amount=instance.price,
|
|
entity=entity,
|
|
is_product_or_service=True,
|
|
sold_as_unit=True,
|
|
is_active=True,
|
|
item_role="service",
|
|
for_inventory=False,
|
|
cogs_account=cogs,
|
|
)
|
|
instance.item = service_model
|
|
instance.save()
|
|
|
|
|
|
@receiver(post_save, sender=models.Lead)
|
|
def track_lead_status_change(sender, instance, **kwargs):
|
|
"""
|
|
Tracks changes in the status of a Lead instance and logs the transition into the
|
|
LeadStatusHistory model. This function is triggered after the `post_save` signal
|
|
is emitted for a Lead instance.
|
|
|
|
The function compares the `status` of the updated Lead instance with its previous
|
|
value. If the `status` has changed, it creates a new entry in the LeadStatusHistory
|
|
model, recording the old status, the new status, and the staff responsible for the change.
|
|
|
|
:param sender: The model class that sent the signal.
|
|
:type sender: Type[models.Model]
|
|
:param instance: The actual instance being saved. It represents the Lead instance
|
|
whose status is being tracked.
|
|
:type instance: models.Lead
|
|
:param kwargs: Additional keyword arguments passed by the signal. These can include
|
|
flags such as 'created' to indicate if the instance was newly created or updated.
|
|
|
|
:return: None
|
|
"""
|
|
if instance.pk: # Ensure the instance is being updated, not created
|
|
try:
|
|
old_lead = models.Lead.objects.get(pk=instance.pk)
|
|
if old_lead.status != instance.status: # Check if status has changed
|
|
models.LeadStatusHistory.objects.create(
|
|
lead=instance,
|
|
old_status=old_lead.status,
|
|
new_status=instance.status,
|
|
changed_by=instance.staff # Assuming the assigned staff made the change
|
|
)
|
|
except models.Lead.DoesNotExist:
|
|
pass # Ignore if the lead doesn't exist (e.g., during initial creation)
|
|
|
|
|
|
@receiver(post_save, sender=models.Lead)
|
|
def notify_assigned_staff(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler that sends a notification to the staff member when a new lead is assigned.
|
|
This function is triggered when a Lead instance is saved. If the lead has been assigned
|
|
to a staff member, it creates a Notification object, notifying the staff member of the
|
|
new assignment.
|
|
|
|
:param sender: The model class that sent the signal.
|
|
:param instance: The instance of the model that was saved.
|
|
:param created: A boolean indicating whether a new instance was created.
|
|
:param kwargs: Additional keyword arguments.
|
|
:return: None
|
|
"""
|
|
if instance.staff: # Check if the lead is assigned
|
|
models.Notification.objects.create(
|
|
user=instance.staff.staff_member.user,
|
|
message=f"You have been assigned a new lead: {instance.full_name}."
|
|
)
|
|
|
|
|
|
@receiver(post_save, sender=models.CarReservation)
|
|
def update_car_status_on_reservation_create(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal handler to update the status of a car upon the creation of a car reservation.
|
|
This function is triggered when a new instance of a CarReservation is created and saved
|
|
to the database. It modifies the status of the associated car to reflect the RESERVED status.
|
|
|
|
:param sender: The model class that sends the signal (CarReservation).
|
|
:param instance: The specific instance of the CarReservation that triggered the signal.
|
|
:param created: A boolean indicating whether the CarReservation instance was created.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
car = instance.car
|
|
car.status = models.CarStatusChoices.RESERVED
|
|
car.save()
|
|
|
|
@receiver(post_delete, sender=models.CarReservation)
|
|
def update_car_status_on_reservation_delete(sender, instance, **kwargs):
|
|
"""
|
|
Signal handler that updates the status of a car to available when a car reservation
|
|
is deleted. If there are no active reservations associated with the car, the car's
|
|
status is updated to 'AVAILABLE'. This ensures the car's status accurately reflects
|
|
its reservability.
|
|
|
|
:param sender: The model class that triggers the signal (should always be
|
|
models.CarReservation in this context).
|
|
:type sender: type
|
|
:param instance: The instance of the deleted reservation.
|
|
:type instance: models.CarReservation
|
|
:param kwargs: Additional keyword arguments.
|
|
:type kwargs: dict
|
|
"""
|
|
car = instance.car
|
|
# Check if there are no active reservations for the car
|
|
if not car.reservations.filter(reserved_until__gt=now()).exists():
|
|
car.status = models.CarStatusChoices.AVAILABLE
|
|
car.save()
|
|
|
|
@receiver(post_save, sender=models.CarReservation)
|
|
def update_car_status_on_reservation_update(sender, instance, **kwargs):
|
|
"""
|
|
Handles the post-save signal for CarReservation model, updating the associated
|
|
car's status based on the reservation's activity status. If the reservation is
|
|
active, the car's status is updated to RESERVED. If the reservation is not
|
|
active, the car's status is set to AVAILABLE if there are no other active
|
|
reservations for the car.
|
|
|
|
:param sender: The model class that sent the signal.
|
|
:param instance: The CarReservation instance that triggered the signal.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
car = instance.car
|
|
if instance.is_active:
|
|
car.status = models.CarStatusChoices.RESERVED
|
|
else:
|
|
if not car.reservations.filter(reserved_until__gt=now()).exists():
|
|
car.status = models.CarStatusChoices.AVAILABLE
|
|
car.save()
|
|
|
|
@receiver(post_save, sender=models.Dealer)
|
|
def create_dealer_settings(sender, instance, created, **kwargs):
|
|
"""
|
|
Triggered when a `Dealer` instance is saved. This function creates corresponding
|
|
`DealerSettings` for a newly created `Dealer` instance. The function assigns
|
|
default accounts for invoices and bills based on the role of the accounts
|
|
retrieved from the associated entity of the `Dealer`.
|
|
|
|
:param sender: The model class that triggered the signal, specifically `Dealer`.
|
|
:type sender: Type
|
|
:param instance: The actual instance of the `Dealer` that was saved.
|
|
:type instance: models.Dealer
|
|
:param created: A boolean indicating whether a new instance was created.
|
|
`True` if the instance was newly created; otherwise, `False`.
|
|
:type created: bool
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
if created:
|
|
models.DealerSettings.objects.create(
|
|
dealer=instance,
|
|
invoice_cash_account=instance.entity.get_all_accounts().filter(role=roles.ASSET_CA_CASH).first(),
|
|
invoice_prepaid_account=instance.entity.get_all_accounts().filter(role=roles.ASSET_CA_RECEIVABLES).first(),
|
|
invoice_unearned_account=instance.entity.get_all_accounts().filter(role=roles.LIABILITY_CL_DEFERRED_REVENUE).first(),
|
|
bill_cash_account=instance.entity.get_all_accounts().filter(role=roles.ASSET_CA_CASH).first(),
|
|
bill_prepaid_account=instance.entity.get_all_accounts().filter(role=roles.ASSET_CA_PREPAID).first(),
|
|
bill_unearned_account=instance.entity.get_all_accounts().filter(role=roles.LIABILITY_CL_ACC_PAYABLE).first()
|
|
)
|
|
|
|
# @receiver(post_save, sender=EstimateModel)
|
|
# def update_estimate_status(sender, instance,created, **kwargs):
|
|
|
|
# items = instance.get_itemtxs_data()[0].all()
|
|
# total = sum([Decimal(item.item_model.additional_info['car_finance']["selling_price"]) * Decimal(item.ce_quantity) for item in items])
|
|
|
|
# @receiver(post_save, sender=models.Schedule)
|
|
# def create_activity_on_schedule_creation(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# models.Activity.objects.create(
|
|
# content_object=instance,
|
|
# activity_type='Schedule Created',
|
|
# created_by=instance.scheduled_by,
|
|
# notes=f"New schedule created for {instance.purpose} with {instance.lead.full_name} on {instance.scheduled_at}."
|
|
# )
|
|
|
|
# @receiver(post_save, sender=models.Staff)
|
|
# def check_users_quota(sender, instance, **kwargs):
|
|
# quota_dict = get_user_quota(instance.dealer.user)
|
|
# allowed_users = quota_dict.get("Users")
|
|
# if allowed_users is None:
|
|
# raise ValidationError(_("The user quota for staff members is not defined. Please contact support."))
|
|
# current_staff_count = instance.dealer.staff.count()
|
|
# if current_staff_count > allowed_users:
|
|
# raise ValidationError(_("You have reached the maximum number of staff users allowed for your plan."))
|
|
|
|
|
|
@receiver(post_save, sender=models.Dealer)
|
|
def create_vat(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal receiver that listens to the `post_save` signal for the `Dealer` model
|
|
and handles the creation of a `VatRate` instance if it does not already exist.
|
|
|
|
This function ensures that a default VAT rate is created with a specified rate
|
|
and is marked as active. It is connected to the Django signals framework and
|
|
automatically executes whenever a `Dealer` instance is saved.
|
|
|
|
:param sender: The model class that triggered the signal (in this case, `Dealer`).
|
|
:param instance: The instance of the model being saved.
|
|
:param created: Boolean indicating whether a new instance was created.
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
VatRate.objects.get_or_create(rate=Decimal('0.15'), is_active=True)
|
|
|
|
@receiver(post_save, sender=models.Dealer)
|
|
def create_make_ledger_accounts(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal receiver that creates ledger accounts for car makes associated with a dealer when a new dealer instance
|
|
is created. This function listens to the `post_save` signal of the `Dealer` model and automatically generates
|
|
new ledger accounts for all car makes, associating them with the given dealer's entity.
|
|
|
|
:param sender: The model class (`Dealer`) that triggered the signal.
|
|
:type sender: Type[models.Dealer]
|
|
:param instance: The instance of the `Dealer` model that triggered the signal.
|
|
:param created: A boolean indicating whether a new `Dealer` instance was created.
|
|
:type created: bool
|
|
:param kwargs: Additional keyword arguments passed by the signal.
|
|
:return: None
|
|
"""
|
|
if created:
|
|
entity = instance.entity
|
|
coa = entity.get_default_coa()
|
|
|
|
last_account = entity.get_all_accounts().filter(role=roles.ASSET_CA_RECEIVABLES).order_by('-created').first()
|
|
if len(last_account.code) == 4:
|
|
code = f"{int(last_account.code)}{1:03d}"
|
|
elif len(last_account.code) > 4:
|
|
code = f"{int(last_account.code)+1}"
|
|
|
|
for make in models.CarMake.objects.all():
|
|
entity.create_account(
|
|
name=make.name,
|
|
code=code,
|
|
role=roles.ASSET_CA_RECEIVABLES,
|
|
coa_model=coa,
|
|
balance_type="credit",
|
|
active=True
|
|
)
|
|
|
|
|
|
# @receiver(post_save, sender=VendorModel)
|
|
# def create_vendor_accounts(sender, instance, created, **kwargs):
|
|
# if created:
|
|
# entity = instance.entity_model
|
|
# coa = entity.get_default_coa()
|
|
|
|
# last_account = entity.get_all_accounts().filter(role=roles.LIABILITY_CL_ACC_PAYABLE).order_by('-created').first()
|
|
# if len(last_account.code) == 4:
|
|
# code = f"{int(last_account.path)}{1:03d}"
|
|
# elif len(last_account.code) > 4:
|
|
# code = f"{int(last_account.path)+1}"
|
|
# entity.create_account(
|
|
# name=instance.vendor_name,
|
|
# code=code,
|
|
# role=roles.LIABILITY_CL_ACC_PAYABLE,
|
|
# coa_model=coa,
|
|
# balance_type="credit",
|
|
# active=True
|
|
# )
|
|
|
|
def save_journal(car_finance,ledger,vendor):
|
|
"""
|
|
Saves a journal entry pertaining to a car finance transaction for a specific ledger and vendor.
|
|
|
|
This function ensures that relevant accounts are updated to record financial transactions. It handles
|
|
debiting of the inventory account and crediting of the vendor account to maintain accurate bookkeeping.
|
|
Additionally, it creates vendor accounts dynamically if required and ties the created journal entry to
|
|
the ledger passed as a parameter. All transactions adhere to the ledger's entity-specific Chart of
|
|
Accounts (COA) configuration.
|
|
|
|
:param car_finance: Instance of the car finance object containing details about the financed car
|
|
and its associated costs.
|
|
:type car_finance: `CarFinance` object
|
|
:param ledger: Ledger instance to which the journal entry is tied. This ledger must provide
|
|
entity-specific details, including its COA and related accounts.
|
|
:type ledger: `Ledger` object
|
|
:param vendor: Vendor instance representing the supplier or vendor related to the car finance
|
|
transaction. This vendor is used to derive or create the vendor account in COA.
|
|
:type vendor: `Vendor` object
|
|
|
|
:return: None
|
|
"""
|
|
entity = ledger.entity
|
|
coa = entity.get_default_coa()
|
|
journal = JournalEntryModel.objects.create(
|
|
posted=False,
|
|
description=f"Finances of Car:{car_finance.car.vin} for Vendor:{car_finance.car.vendor.vendor_name}",
|
|
ledger=ledger,
|
|
locked=False,
|
|
origin="Payment",
|
|
)
|
|
ledger.additional_info["je_number"] = journal.je_number
|
|
ledger.save()
|
|
|
|
inventory_account = entity.get_default_coa_accounts().filter(role=roles.ASSET_CA_INVENTORY).first()
|
|
vendor_account = entity.get_default_coa_accounts().filter(name=vendor.vendor_name).first()
|
|
|
|
if not vendor_account:
|
|
last_account = entity.get_all_accounts().filter(role=roles.LIABILITY_CL_ACC_PAYABLE).order_by('-created').first()
|
|
if len(last_account.code) == 4:
|
|
code = f"{int(last_account.code)}{1:03d}"
|
|
elif len(last_account.code) > 4:
|
|
code = f"{int(last_account.code)+1}"
|
|
|
|
vendor_account = entity.create_account(
|
|
name=vendor.vendor_name,
|
|
code=code,
|
|
role=roles.LIABILITY_CL_ACC_PAYABLE,
|
|
coa_model=coa,
|
|
balance_type="credit",
|
|
active=True
|
|
)
|
|
additional_services_account = entity.get_default_coa_accounts().filter(name="Additional Services",role=roles.COGS).first()
|
|
|
|
# Debit Inventory Account
|
|
TransactionModel.objects.create(
|
|
journal_entry=journal,
|
|
account=inventory_account,
|
|
amount=car_finance.cost_price,
|
|
tx_type='debit'
|
|
)
|
|
|
|
# Credit Vendor Account
|
|
TransactionModel.objects.create(
|
|
journal_entry=journal,
|
|
account=vendor_account,
|
|
amount=car_finance.cost_price,
|
|
tx_type='credit',
|
|
|
|
)
|
|
|
|
@receiver(post_save, sender=models.CarFinance)
|
|
def update_finance_cost(sender, instance, created, **kwargs):
|
|
"""
|
|
Signal to handle `post_save` functionality for the `CarFinance` model. This function
|
|
creates or updates financial records related to a car's finance details in the ledger
|
|
associated with the car's vendor and dealer. For newly created instances, a ledger is
|
|
created or retrieved, and the `save_journal` function is executed to log the financial
|
|
transactions.
|
|
|
|
This function also has commented-out logic to handle updates for already created
|
|
instances, including journal updates or adjustments to existing financial transactions.
|
|
|
|
:param sender: Model class that triggered the signal
|
|
:type sender: Model
|
|
:param instance: Instance of the `CarFinance` model passed to the signal
|
|
:type instance: CarFinance
|
|
:param created: Boolean value indicating if the instance was created (`True`) or updated (`False`)
|
|
:type created: bool
|
|
:param kwargs: Arbitrary keyword arguments passed to the signal
|
|
:type kwargs: dict
|
|
:return: None
|
|
"""
|
|
if created:
|
|
entity = instance.car.dealer.entity
|
|
vendor = instance.car.vendor
|
|
name = f"{instance.car.vin}-{instance.car.id_car_make.name}-{instance.car.id_car_model.name}-{instance.car.year}-{vendor.vendor_name}"
|
|
ledger,_ = LedgerModel.objects.get_or_create(name=name, entity=entity)
|
|
save_journal(instance,ledger,vendor)
|
|
|
|
# if not created:
|
|
# if ledger.additional_info.get("je_number"):
|
|
# journal = JournalEntryModel.objects.filter(je_number=ledger.additional_info.get("je_number")).first()
|
|
# journal.description = f"Finances of Car:{instance.car.vin} for Vendor:{instance.car.vendor.vendor_name}"
|
|
# journal.save()
|
|
# debit = journal.get_transaction_queryset().filter(tx_type='debit').first()
|
|
# credit = journal.get_transaction_queryset().filter(tx_type='credit').first()
|
|
# if debit and credit:
|
|
# if journal.is_locked():
|
|
# journal.mark_as_unlocked()
|
|
# journal.save()
|
|
# debit.amount = instance.cost_price
|
|
# credit.amount = instance.cost_price
|
|
# debit.save()
|
|
# credit.save()
|
|
# else:
|
|
# save_journal(instance,ledger,vendor,journal=journal)
|
|
# else:
|
|
# save_journal(instance,ledger,vendor)
|
|
# else:
|
|
# save_journal(instance,ledger,vendor) |