monkey patched asset categories
This commit is contained in:
parent
64dd4cc631
commit
0aadaf202d
|
|
@ -68,122 +68,115 @@ def create_asset_categories_for_company(company_name):
|
||||||
Args:
|
Args:
|
||||||
company_name: Название компании
|
company_name: Название компании
|
||||||
"""
|
"""
|
||||||
print("=" * 80)
|
|
||||||
print(f"LOG: create_asset_categories_for_company STARTED for company: {company_name}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"create_asset_categories_for_company started for company: {company_name}",
|
f"Function started\nCompany: {company_name}",
|
||||||
"Asset Categories Creation - START"
|
"AC Create Start"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Проверяем, что компания существует
|
# Проверяем, что компания существует
|
||||||
print(f"LOG: Checking if company exists: {company_name}")
|
|
||||||
company_exists = frappe.db.exists("Company", company_name)
|
company_exists = frappe.db.exists("Company", company_name)
|
||||||
print(f"LOG: Company exists: {company_exists}")
|
|
||||||
|
|
||||||
if not company_exists:
|
if not company_exists:
|
||||||
print(f"LOG: ERROR - Company not found: {company_name}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Company '{company_name}' not found",
|
f"Company not found in database\nSearched for: {company_name}",
|
||||||
"Asset Categories Creation - ERROR"
|
"AC Company ERROR"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
frappe.log_error(
|
||||||
|
f"Company exists in database\nCompany: {company_name}",
|
||||||
|
"AC Company OK"
|
||||||
|
)
|
||||||
|
|
||||||
# Проверка идемпотентности: если категории уже есть, не создаем
|
# Проверка идемпотентности: если категории уже есть, не создаем
|
||||||
system_categories = get_system_asset_categories()
|
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(
|
existing_categories = frappe.db.count(
|
||||||
"Asset Category",
|
"Asset Category",
|
||||||
filters={"asset_category_name": ["in", system_categories]}
|
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:
|
if existing_categories > 0:
|
||||||
print(f"LOG: Categories already exist ({existing_categories}), skipping creation")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Asset categories already exist ({existing_categories} found). Skipping creation.",
|
f"Categories already exist, skipping creation\nFound: {existing_categories} of {len(system_categories)}",
|
||||||
"Asset Categories Creation - SKIP"
|
"AC Already Exist"
|
||||||
)
|
)
|
||||||
return
|
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(
|
frappe.log_error(
|
||||||
f"Asset categories creation completed for company: {company_name}",
|
f"Starting category creation\nCompany: {company_name}\nCategories to create: {len(system_categories)}",
|
||||||
"Asset Categories Creation - COMPLETED"
|
"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:
|
except Exception as e:
|
||||||
# Не пробрасываем исключение - это фоновая задача
|
# Не пробрасываем исключение - это фоновая задача
|
||||||
print(f"LOG: ERROR during category creation: {str(e)}")
|
|
||||||
import traceback
|
import traceback
|
||||||
print(f"LOG: Traceback: {traceback.format_exc()}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Failed to create asset categories for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
|
f"Failed to create asset categories\nCompany: {company_name}\nError: {str(e)}\n\nFull traceback:\n{traceback.format_exc()}",
|
||||||
"Asset Categories Creation - ERROR"
|
"AC Create ERROR"
|
||||||
)
|
)
|
||||||
|
|
||||||
print("=" * 80)
|
|
||||||
|
|
||||||
|
|
||||||
def _create_categories_for_company(company_name):
|
def _create_categories_for_company(company_name):
|
||||||
"""
|
"""
|
||||||
Внутренняя функция для создания категорий активов.
|
Внутренняя функция для создания категорий активов.
|
||||||
Извлечена из create_asset_categories для переиспользования.
|
Извлечена из create_asset_categories для переиспользования.
|
||||||
"""
|
"""
|
||||||
print(f"LOG: _create_categories_for_company called for: {company_name}")
|
|
||||||
asset_categories = get_system_asset_categories()
|
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:
|
try:
|
||||||
print("LOG: Searching for account: Tikililər üzrə yığılmış amortizasiya")
|
|
||||||
accumulated_depreciation = get_account_by_name(
|
accumulated_depreciation = get_account_by_name(
|
||||||
"Tikililər üzrə yığılmış amortizasiya",
|
"Tikililər üzrə yığılmış amortizasiya",
|
||||||
company_name
|
company_name
|
||||||
)
|
)
|
||||||
print(f"LOG: Found accumulated_depreciation: {accumulated_depreciation}")
|
|
||||||
|
|
||||||
print("LOG: Searching for account: Amortizasiya xərci")
|
|
||||||
depreciation_expense = get_account_by_name(
|
depreciation_expense = get_account_by_name(
|
||||||
"Amortizasiya xərci",
|
"Amortizasiya xərci",
|
||||||
company_name
|
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(
|
fixed_asset = get_account_by_name(
|
||||||
"Digər uzunmüddətli aktivlər",
|
"Digər uzunmüddətli aktivlər",
|
||||||
company_name
|
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:
|
except Exception as e:
|
||||||
print(f"LOG: ERROR - Failed to find required accounts: {str(e)}")
|
|
||||||
import traceback
|
import traceback
|
||||||
print(f"LOG: Traceback: {traceback.format_exc()}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Required accounts not found for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
|
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()}",
|
||||||
"Asset Categories Creation - Accounts ERROR"
|
"AC Accounts ERROR"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# Создаем категории
|
# Создаем категории
|
||||||
print("LOG: Starting to create categories...")
|
|
||||||
created_count = 0
|
created_count = 0
|
||||||
skipped_count = 0
|
skipped_count = 0
|
||||||
|
errors = []
|
||||||
|
|
||||||
for idx, category_name in enumerate(asset_categories, 1):
|
for idx, category_name in enumerate(asset_categories, 1):
|
||||||
print(f"LOG: Processing category {idx}/{len(asset_categories)}: {category_name}")
|
|
||||||
try:
|
try:
|
||||||
if not frappe.db.exists("Asset Category", category_name):
|
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 = frappe.new_doc("Asset Category")
|
||||||
asset_category.asset_category_name = category_name
|
asset_category.asset_category_name = category_name
|
||||||
asset_category.enable_cwip_accounting = 0
|
asset_category.enable_cwip_accounting = 0
|
||||||
|
|
@ -198,26 +191,25 @@ def _create_categories_for_company(company_name):
|
||||||
|
|
||||||
asset_category.insert(ignore_permissions=True)
|
asset_category.insert(ignore_permissions=True)
|
||||||
created_count += 1
|
created_count += 1
|
||||||
print(f"LOG: Successfully created category: {category_name}")
|
|
||||||
else:
|
else:
|
||||||
skipped_count += 1
|
skipped_count += 1
|
||||||
print(f"LOG: Category already exists, skipping: {category_name}")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"LOG: ERROR creating category '{category_name}': {str(e)}")
|
|
||||||
import traceback
|
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(
|
frappe.log_error(
|
||||||
f"Failed to create Asset Category '{category_name}': {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
|
f"Failed to create category\n{error_msg}\n\nFull traceback:\n{traceback.format_exc()}",
|
||||||
"Asset Categories Creation - Category ERROR"
|
f"AC Cat ERROR {idx}"
|
||||||
)
|
)
|
||||||
|
|
||||||
print("LOG: Committing to database...")
|
|
||||||
frappe.db.commit()
|
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")
|
status = "SUCCESS" if created_count > 0 else ("SKIP" if skipped_count > 0 else "ERROR")
|
||||||
print(f"LOG: {message}")
|
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):
|
def prevent_delete_system_asset_categories(doc, method):
|
||||||
|
|
|
||||||
|
|
@ -12,42 +12,30 @@ def setup_wizard_complete_handler(args):
|
||||||
- country: Выбранная страна
|
- country: Выбранная страна
|
||||||
- currency: Валюта по умолчанию
|
- currency: Валюта по умолчанию
|
||||||
"""
|
"""
|
||||||
# LOG: Хук вызван
|
|
||||||
print("=" * 80)
|
|
||||||
print("LOG: setup_wizard_complete_handler CALLED")
|
|
||||||
print(f"LOG: Received args: {args}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"setup_wizard_complete_handler called with args: {args}",
|
f"Hook called\nArgs: {args}",
|
||||||
"Asset Categories Setup - Hook Called"
|
"AC Setup Hook"
|
||||||
)
|
)
|
||||||
|
|
||||||
company_name = args.get("company_name")
|
company_name = args.get("company_name")
|
||||||
print(f"LOG: company_name from args: {company_name}")
|
|
||||||
|
|
||||||
if not company_name:
|
if not company_name:
|
||||||
# Fallback: получаем первую компанию
|
# Fallback: получаем первую компанию
|
||||||
print("LOG: company_name not in args, trying fallback to get first company")
|
|
||||||
companies = frappe.get_all("Company", limit=1)
|
companies = frappe.get_all("Company", limit=1)
|
||||||
print(f"LOG: Found companies: {companies}")
|
|
||||||
|
|
||||||
if companies:
|
if companies:
|
||||||
company_name = companies[0].name
|
company_name = companies[0].name
|
||||||
print(f"LOG: Using first company: {company_name}")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Company name not in args, using first company: {company_name}",
|
f"Company name not in args, using fallback\nCompanies found: {companies}\nUsing: {company_name}",
|
||||||
"Asset Categories Setup - Fallback"
|
"AC Setup Fallback"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print("LOG: ERROR - No companies found!")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
"Company name not found in setup wizard args and no companies exist",
|
"Company name not found in setup wizard args and no companies exist in database",
|
||||||
"Asset Categories Setup - ERROR"
|
"AC Setup ERROR"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# LOG: Перед постановкой в очередь
|
|
||||||
print(f"LOG: Enqueueing task for company: {company_name}")
|
|
||||||
|
|
||||||
# Ставим в очередь фоновую задачу (некритично, не блокирует визард)
|
# Ставим в очередь фоновую задачу (некритично, не блокирует визард)
|
||||||
try:
|
try:
|
||||||
frappe.enqueue(
|
frappe.enqueue(
|
||||||
|
|
@ -58,16 +46,15 @@ def setup_wizard_complete_handler(args):
|
||||||
at_front=False, # Некритично, может подождать
|
at_front=False, # Некритично, может подождать
|
||||||
company_name=company_name
|
company_name=company_name
|
||||||
)
|
)
|
||||||
print("LOG: Task enqueued successfully")
|
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Task enqueued successfully for company: {company_name}",
|
f"Background task enqueued successfully\nCompany: {company_name}\nQueue: default\nTimeout: 300s",
|
||||||
"Asset Categories Setup - Task Enqueued"
|
"AC Task Enqueued"
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"LOG: ERROR enqueueing task: {str(e)}")
|
import traceback
|
||||||
frappe.log_error(
|
frappe.log_error(
|
||||||
f"Failed to enqueue task: {str(e)}",
|
f"Failed to enqueue background task\nCompany: {company_name}\nError: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
|
||||||
"Asset Categories Setup - Enqueue ERROR"
|
"AC Enqueue ERROR"
|
||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
@ -76,4 +63,3 @@ def setup_wizard_complete_handler(args):
|
||||||
title="Настройка выполняется",
|
title="Настройка выполняется",
|
||||||
indicator="blue"
|
indicator="blue"
|
||||||
)
|
)
|
||||||
print("=" * 80)
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue