monkey patched asset categories

This commit is contained in:
Ali 2026-01-10 01:50:48 +04:00
parent 8865bb7b18
commit 64dd4cc631
3 changed files with 260 additions and 20 deletions

View File

@ -68,75 +68,122 @@ 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"
)
try:
# Проверяем, что компания существует
if not frappe.db.exists("Company", company_name):
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"
"Asset Categories Creation - ERROR"
)
return
# Проверка идемпотентности: если категории уже есть, не создаем
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}")
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 - Info"
"Asset Categories Creation - SKIP"
)
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"
)
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)}",
"Asset Categories Creation - Error"
f"Failed to create asset categories for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - 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...")
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!")
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)}",
"Asset Categories Creation - Error"
f"Required accounts not found for {company_name}: {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - Accounts ERROR"
)
return
# Создаем категории
print("LOG: Starting to create categories...")
created_count = 0
skipped_count = 0
for category_name in asset_categories:
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
@ -151,19 +198,26 @@ 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()}")
frappe.log_error(
f"Failed to create Asset Category '{category_name}': {str(e)}",
"Asset Categories Creation - Error"
f"Failed to create Asset Category '{category_name}': {str(e)}\n\nTraceback:\n{traceback.format_exc()}",
"Asset Categories Creation - Category ERROR"
)
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(message)
print(f"LOG: {message}")
def prevent_delete_system_asset_categories(doc, method):

View File

@ -0,0 +1,150 @@
"""
Диагностический скрипт для проверки создания категорий активов.
Использование:
bench --site <site-name> execute jey_erp.debug_asset_categories.diagnose
"""
import frappe
def diagnose():
"""Проверяет состояние системы и причину отсутствия категорий активов"""
print("\n" + "=" * 80)
print("ДИАГНОСТИКА: Создание категорий активов")
print("=" * 80 + "\n")
# 1. Проверка существования компании
print("1. Проверка компаний:")
companies = frappe.get_all("Company", fields=["name", "country"])
if companies:
print(f" ✓ Найдено компаний: {len(companies)}")
for idx, comp in enumerate(companies, 1):
print(f" {idx}. {comp.name} (Country: {comp.get('country', 'N/A')})")
else:
print(" ✗ Компании не найдены!")
return
# 2. Проверка категорий активов
print("\n2. Проверка категорий активов:")
from jey_erp.custom.create_asset_categories import get_system_asset_categories
system_categories = get_system_asset_categories()
print(f" Системных категорий должно быть: {len(system_categories)}")
existing_categories = frappe.get_all(
"Asset Category",
filters={"asset_category_name": ["in", system_categories]},
pluck="asset_category_name"
)
if existing_categories:
print(f" ✓ Найдено категорий: {len(existing_categories)}")
for cat in existing_categories:
print(f" - {cat}")
else:
print(f" ✗ Категории не найдены (0 из {len(system_categories)})")
# 3. Проверка счетов
print("\n3. Проверка необходимых счетов:")
company_name = companies[0].name
required_accounts = [
"Tikililər üzrə yığılmış amortizasiya",
"Amortizasiya xərci",
"Digər uzunmüddətli aktivlər"
]
for account_name in required_accounts:
account = frappe.db.get_value(
"Account",
{"account_name": account_name, "company": company_name},
"name"
)
if account:
print(f"{account_name}: {account}")
else:
print(f"{account_name}: НЕ НАЙДЕН!")
# 4. Проверка Error Log
print("\n4. Проверка логов ошибок (последние 10):")
error_logs = frappe.get_all(
"Error Log",
filters={
"error": ["like", "%Asset Categories%"]
},
fields=["name", "creation", "error"],
order_by="creation desc",
limit=10
)
if error_logs:
print(f" Найдено логов: {len(error_logs)}")
for log in error_logs:
print(f"\n [{log.creation}] {log.name}")
print(f" {log.error[:200]}...")
else:
print(" Логи не найдены")
# 5. Проверка хука
print("\n5. Проверка хука setup_wizard_complete:")
hooks = frappe.get_hooks("setup_wizard_complete")
if hooks:
print(f" ✓ Хук зарегистрирован: {hooks}")
else:
print(" ✗ Хук НЕ зарегистрирован!")
# 6. Проверка фоновых задач
print("\n6. Проверка фоновых задач:")
try:
from rq import Queue
from frappe.utils.background_jobs import get_redis_conn
q = Queue('default', connection=get_redis_conn())
jobs = q.jobs
if jobs:
print(f" В очереди задач: {len(jobs)}")
for job in jobs:
print(f" - {job.func_name}")
else:
print(" Очередь пуста")
# Проверка failed jobs
failed_q = Queue('failed', connection=get_redis_conn())
failed_jobs = failed_q.jobs
if failed_jobs:
print(f"\n FAILED задач: {len(failed_jobs)}")
for job in failed_jobs:
print(f"{job.func_name}: {job.exc_info}")
except Exception as e:
print(f" Ошибка проверки очереди: {str(e)}")
print("\n" + "=" * 80)
print("ДИАГНОСТИКА ЗАВЕРШЕНА")
print("=" * 80 + "\n")
def force_create():
"""Принудительно создает категории активов для первой компании"""
print("\n" + "=" * 80)
print("ПРИНУДИТЕЛЬНОЕ СОЗДАНИЕ КАТЕГОРИЙ АКТИВОВ")
print("=" * 80 + "\n")
companies = frappe.get_all("Company", limit=1)
if not companies:
print("✗ Компании не найдены!")
return
company_name = companies[0].name
print(f"Создание категорий для компании: {company_name}\n")
from jey_erp.custom.create_asset_categories import create_asset_categories_for_company
create_asset_categories_for_company(company_name)
print("\n" + "=" * 80)
print("СОЗДАНИЕ ЗАВЕРШЕНО")
print("=" * 80 + "\n")

View File

@ -12,32 +12,68 @@ 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"
)
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"
)
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"
"Asset Categories Setup - ERROR"
)
return
# LOG: Перед постановкой в очередь
print(f"LOG: Enqueueing task for company: {company_name}")
# Ставим в очередь фоновую задачу (некритично, не блокирует визард)
frappe.enqueue(
"jey_erp.custom.create_asset_categories.create_asset_categories_for_company",
queue="default",
timeout=300,
enqueue_after_commit=True,
at_front=False, # Некритично, может подождать
company_name=company_name
)
try:
frappe.enqueue(
"jey_erp.custom.create_asset_categories.create_asset_categories_for_company",
queue="default",
timeout=300,
enqueue_after_commit=True,
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"
)
except Exception as e:
print(f"LOG: ERROR enqueueing task: {str(e)}")
frappe.log_error(
f"Failed to enqueue task: {str(e)}",
"Asset Categories Setup - Enqueue ERROR"
)
raise
frappe.msgprint(
f"Категории активов будут созданы в фоновом режиме для {company_name}",
title="Настройка выполняется",
indicator="blue"
)
print("=" * 80)