haikal/inventory/hooks.py
2025-09-24 11:07:31 +03:00

91 lines
2.9 KiB
Python

import logging
from inventory.models import Dealer
from .utils import get_accounts_data, create_account
logger = logging.getLogger(__name__)
def check_create_coa_accounts(task):
"""
Hook to verify account creation and handle failures
"""
from .models import Dealer
if task.success:
logger.info("Account creation task completed successfully")
return
logger.warning("Account creation task failed, checking status...")
try:
dealer_id = task.kwargs.get("dealer_id", None)
coa_slug = task.kwargs.get("coa_slug", None)
logger.info(f"Checking accounts for dealer {dealer_id}")
logger.info(f"COA slug: {coa_slug}")
if not dealer_id:
logger.error("No dealer_id in task kwargs")
return
instance = Dealer.objects.get(id=dealer_id)
entity = instance.entity
if not entity:
logger.error(f"No entity for dealer {dealer_id}")
return
if coa_slug:
try:
coa = entity.get_coa_model_qs().get(slug=coa_slug)
except Exception as e:
logger.error(
f"COA with slug {coa_slug} not found for entity {entity.pk}: {e}"
)
else:
coa = entity.get_default_coa()
if not coa:
logger.error(f"No COA for entity {entity.pk}")
return
# Check which accounts are missing and create them
from .utils import get_accounts_data, create_account
missing_accounts = []
for account_data in get_accounts_data():
if (
not entity.get_all_accounts()
.filter(coa_model=coa, code=account_data["code"])
.exists()
):
missing_accounts.append(account_data)
logger.info(f"Missing account: {account_data['code']}")
if missing_accounts:
logger.info(f"Creating {len(missing_accounts)} missing accounts")
for account_data in missing_accounts:
create_account(entity, coa, account_data)
else:
logger.info("All accounts are already created")
except Exception as e:
logger.error(f"Error in check_create_coa_accounts hook: {e}")
# def check_create_coa_accounts(task):
# logger.info("Checking if all accounts are created")
# instance = task.kwargs["dealer"]
# entity = instance.entity
# coa = entity.get_default_coa()
# for account_data in get_accounts_data():
# if entity.get_all_accounts().filter(code=account_data["code"]).exists():
# logger.info(f"Default account already exists: {account_data['code']}")
# continue
# logger.info(f"Default account does not exist: {account_data['code']}")
# create_account(entity, coa, account_data)
def print_results(task):
dealer = task.kwargs["dealer"]
print("HOOK: ", dealer)
print("HOOK: ", dealer.pk)