monkey patched asset categories

This commit is contained in:
Ali 2026-01-10 02:03:55 +04:00
parent 64dd4cc631
commit 0aadaf202d
2 changed files with 60 additions and 82 deletions

View File

@ -68,122 +68,115 @@ def create_asset_categories_for_company(company_name):
Args:
company_name: Название компании
"""
print("=" * 80)
print(f"LOG: create_asset_categories_for_company STARTED for company: {company_name}")
frappe.log_error(
f"create_asset_categories_for_company started for company: {company_name}",
"Asset Categories Creation - START"
f"Function started\nCompany: {company_name}",
"AC Create Start"
)
try:
# Проверяем, что компания существует
print(f"LOG: Checking if company exists: {company_name}")
company_exists = frappe.db.exists("Company", company_name)
print(f"LOG: Company exists: {company_exists}")
if not company_exists:
print(f"LOG: ERROR - Company not found: {company_name}")
frappe.log_error(
f"Company '{company_name}' not found",
"Asset Categories Creation - ERROR"
f"Company not found in database\nSearched for: {company_name}",
"AC Company ERROR"
)
return
frappe.log_error(
f"Company exists in database\nCompany: {company_name}",
"AC Company OK"
)
# Проверка идемпотентности: если категории уже есть, не создаем
system_categories = get_system_asset_categories()
print(f"LOG: System categories count: {len(system_categories)}")
print(f"LOG: System categories: {system_categories}")
existing_categories = frappe.db.count(
"Asset Category",
filters={"asset_category_name": ["in", system_categories]}
)
print(f"LOG: Existing categories count: {existing_categories}")
frappe.log_error(
f"Idempotency check\nSystem categories: {len(system_categories)}\nExisting categories: {existing_categories}\nCategories list: {system_categories}",
"AC Check Existing"
)
if existing_categories > 0:
print(f"LOG: Categories already exist ({existing_categories}), skipping creation")
frappe.log_error(
f"Asset categories already exist ({existing_categories} found). Skipping creation.",
"Asset Categories Creation - SKIP"
f"Categories already exist, skipping creation\nFound: {existing_categories} of {len(system_categories)}",
"AC Already Exist"
)
return
# Создаем категории
print(f"LOG: Starting category creation for company: {company_name}")
_create_categories_for_company(company_name)
print("LOG: Category creation completed")
frappe.log_error(
f"Asset categories creation completed for company: {company_name}",
"Asset Categories Creation - COMPLETED"
f"Starting category creation\nCompany: {company_name}\nCategories to create: {len(system_categories)}",
"AC Creating"
)
_create_categories_for_company(company_name)
frappe.log_error(
f"Asset categories creation completed successfully\nCompany: {company_name}",
"AC Complete"
)
except Exception as e:
# Не пробрасываем исключение - это фоновая задача
print(f"LOG: ERROR during category creation: {str(e)}")
import traceback
print(f"LOG: Traceback: {traceback.format_exc()}")
frappe.log_error(
f"Failed to create asset categories for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - ERROR"
f"Failed to create asset categories\nCompany: {company_name}\nError: {str(e)}\n\nFull traceback:\n{traceback.format_exc()}",
"AC Create ERROR"
)
print("=" * 80)
def _create_categories_for_company(company_name):
"""
Внутренняя функция для создания категорий активов.
Извлечена из create_asset_categories для переиспользования.
"""
print(f"LOG: _create_categories_for_company called for: {company_name}")
asset_categories = get_system_asset_categories()
print(f"LOG: Got {len(asset_categories)} system categories to create")
# Находим нужные счета
print("LOG: Looking for required accounts...")
frappe.log_error(
f"Searching for required accounts\nCompany: {company_name}\nAccounts needed: 3",
"AC Search Accounts"
)
try:
print("LOG: Searching for account: Tikililər üzrə yığılmış amortizasiya")
accumulated_depreciation = get_account_by_name(
"Tikililər üzrə yığılmış amortizasiya",
company_name
)
print(f"LOG: Found accumulated_depreciation: {accumulated_depreciation}")
print("LOG: Searching for account: Amortizasiya xərci")
depreciation_expense = get_account_by_name(
"Amortizasiya xərci",
company_name
)
print(f"LOG: Found depreciation_expense: {depreciation_expense}")
print("LOG: Searching for account: Digər uzunmüddətli aktivlər")
fixed_asset = get_account_by_name(
"Digər uzunmüddətli aktivlər",
company_name
)
print(f"LOG: Found fixed_asset: {fixed_asset}")
print("LOG: All required accounts found successfully!")
frappe.log_error(
f"All required accounts found\nCompany: {company_name}\n\nAccounts:\n1. Accumulated Depreciation: {accumulated_depreciation}\n2. Depreciation Expense: {depreciation_expense}\n3. Fixed Asset: {fixed_asset}",
"AC Accounts OK"
)
except Exception as e:
print(f"LOG: ERROR - Failed to find required accounts: {str(e)}")
import traceback
print(f"LOG: Traceback: {traceback.format_exc()}")
frappe.log_error(
f"Required accounts not found for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - Accounts ERROR"
f"Required accounts not found\nCompany: {company_name}\nError: {str(e)}\n\nRequired accounts:\n- Tikililər üzrə yığılmış amortizasiya\n- Amortizasiya xərci\n- Digər uzunmüddətli aktivlər\n\nFull traceback:\n{traceback.format_exc()}",
"AC Accounts ERROR"
)
return
# Создаем категории
print("LOG: Starting to create categories...")
created_count = 0
skipped_count = 0
errors = []
for idx, category_name in enumerate(asset_categories, 1):
print(f"LOG: Processing category {idx}/{len(asset_categories)}: {category_name}")
try:
if not frappe.db.exists("Asset Category", category_name):
print(f"LOG: Category doesn't exist, creating: {category_name}")
asset_category = frappe.new_doc("Asset Category")
asset_category.asset_category_name = category_name
asset_category.enable_cwip_accounting = 0
@ -198,26 +191,25 @@ def _create_categories_for_company(company_name):
asset_category.insert(ignore_permissions=True)
created_count += 1
print(f"LOG: Successfully created category: {category_name}")
else:
skipped_count += 1
print(f"LOG: Category already exists, skipping: {category_name}")
except Exception as e:
print(f"LOG: ERROR creating category '{category_name}': {str(e)}")
import traceback
print(f"LOG: Traceback: {traceback.format_exc()}")
error_msg = f"Category: {category_name}\nError: {str(e)}"
errors.append(error_msg)
frappe.log_error(
f"Failed to create Asset Category '{category_name}': {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - Category ERROR"
f"Failed to create category\n{error_msg}\n\nFull traceback:\n{traceback.format_exc()}",
f"AC Cat ERROR {idx}"
)
print("LOG: Committing to database...")
frappe.db.commit()
print("LOG: Database commit successful")
message = f"Asset Categories created for {company_name}. Created: {created_count}, Skipped: {skipped_count}"
frappe.log_error(message, "Asset Categories Creation - Success")
print(f"LOG: {message}")
# Финальный отчет
status = "SUCCESS" if created_count > 0 else ("SKIP" if skipped_count > 0 else "ERROR")
frappe.log_error(
f"Category creation finished\nCompany: {company_name}\nCreated: {created_count}\nSkipped: {skipped_count}\nErrors: {len(errors)}\n\nError details:\n{chr(10).join(errors) if errors else 'No errors'}",
f"AC {status}"
)
def prevent_delete_system_asset_categories(doc, method):

View File

@ -12,42 +12,30 @@ def setup_wizard_complete_handler(args):
- country: Выбранная страна
- currency: Валюта по умолчанию
"""
# LOG: Хук вызван
print("=" * 80)
print("LOG: setup_wizard_complete_handler CALLED")
print(f"LOG: Received args: {args}")
frappe.log_error(
f"setup_wizard_complete_handler called with args: {args}",
"Asset Categories Setup - Hook Called"
f"Hook called\nArgs: {args}",
"AC Setup Hook"
)
company_name = args.get("company_name")
print(f"LOG: company_name from args: {company_name}")
if not company_name:
# Fallback: получаем первую компанию
print("LOG: company_name not in args, trying fallback to get first company")
companies = frappe.get_all("Company", limit=1)
print(f"LOG: Found companies: {companies}")
if companies:
company_name = companies[0].name
print(f"LOG: Using first company: {company_name}")
frappe.log_error(
f"Company name not in args, using first company: {company_name}",
"Asset Categories Setup - Fallback"
f"Company name not in args, using fallback\nCompanies found: {companies}\nUsing: {company_name}",
"AC Setup Fallback"
)
else:
print("LOG: ERROR - No companies found!")
frappe.log_error(
"Company name not found in setup wizard args and no companies exist",
"Asset Categories Setup - ERROR"
"Company name not found in setup wizard args and no companies exist in database",
"AC Setup ERROR"
)
return
# LOG: Перед постановкой в очередь
print(f"LOG: Enqueueing task for company: {company_name}")
# Ставим в очередь фоновую задачу (некритично, не блокирует визард)
try:
frappe.enqueue(
@ -58,16 +46,15 @@ def setup_wizard_complete_handler(args):
at_front=False, # Некритично, может подождать
company_name=company_name
)
print("LOG: Task enqueued successfully")
frappe.log_error(
f"Task enqueued successfully for company: {company_name}",
"Asset Categories Setup - Task Enqueued"
f"Background task enqueued successfully\nCompany: {company_name}\nQueue: default\nTimeout: 300s",
"AC Task Enqueued"
)
except Exception as e:
print(f"LOG: ERROR enqueueing task: {str(e)}")
import traceback
frappe.log_error(
f"Failed to enqueue task: {str(e)}",
"Asset Categories Setup - Enqueue ERROR"
f"Failed to enqueue background task\nCompany: {company_name}\nError: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"AC Enqueue ERROR"
)
raise
@ -76,4 +63,3 @@ def setup_wizard_complete_handler(args):
title="Настройка выполняется",
indicator="blue"
)
print("=" * 80)