Logger for views ,utils and signals #108

Merged
ismail merged 4 commits from frontend into main 2025-07-06 13:33:25 +03:00
10 changed files with 619 additions and 17 deletions

View File

@ -24,6 +24,10 @@ from django.utils.timezone import now
from django.db import transaction
from django_q.tasks import async_task
#logging
import logging
logger=logging.getLogger(__name__)
User = get_user_model()
# @receiver(post_save, sender=models.SaleQuotation)
@ -88,7 +92,15 @@ def create_car_location(sender, instance, created, **kwargs):
"""
try:
if created:
# Log that the signal was triggered for a new car
logger.debug(f"Post-save signal triggered for new Car (VIN: {instance.vin}). Attempting to create CarLocation.")
if instance.dealer is None:
# Log the critical data integrity error before raising
logger.error(
f"Attempted to create CarLocation for car (VIN: {instance.vin}) "
f"but 'dealer' field is missing. This indicates a data integrity issue or unhandled logic."
)
raise ValueError(
f"Cannot create CarLocation for car {instance.vin}: dealer is missing."
)
@ -99,7 +111,18 @@ def create_car_location(sender, instance, created, **kwargs):
showroom=instance.dealer,
description=f"Initial location set for car {instance.vin}.",
)
# Log successful CarLocation creation
logger.info(
f"Successfully created CarLocation for new car (VIN: {instance.vin}) "
f"with owner '{instance.dealer.name}' (ID: {instance.dealer.pk})."
)
except Exception as e:
# --- Single-line log for general error during CarLocation creation ---
logger.error(
f"Failed to create CarLocation for car (VIN: {instance.vin}). "
f"An unexpected error occurred: {e}",
exc_info=True
)
print(f"Failed to create CarLocation for car {instance.vin}: {e}")
@ -517,6 +540,8 @@ def track_lead_status_change(sender, instance, **kwargs):
:return: None
"""
if instance.pk: # Ensure the instance is being updated, not created
# Log that a lead update is being checked for status changes
logger.debug(f"Checking for status change on Lead ID: {instance.pk}.")
try:
old_lead = models.Lead.objects.get(pk=instance.pk)
if old_lead.status != instance.status: # Check if status has changed
@ -526,7 +551,17 @@ def track_lead_status_change(sender, instance, **kwargs):
new_status=instance.status,
changed_by=instance.staff, # Assuming the assigned staff made the change
)
# --- Single-line log for successful status change and history creation ---
logger.info(
f"Lead ID: {instance.pk} status changed from '{old_lead.status}' to '{instance.status}'. "
f"LeadStatusHistory recorded by Staff: {instance.staff.username if instance.staff else 'N/A'}."
)
except models.Lead.DoesNotExist:
# --- Single-line log for expected Lead.DoesNotExist (e.g., during initial object creation) ---
logger.debug(
f"Lead ID: {instance.pk} not found in database when checking for status change. "
f"This might occur during initial object creation. Skipping status history tracking."
)
pass # Ignore if the lead doesn't exist (e.g., during initial creation)

View File

@ -25,6 +25,8 @@ from django.utils.translation import gettext_lazy as _
from django_ledger.models.transactions import TransactionModel
from django_ledger.models.journal_entry import JournalEntryModel
import logging
logger=logging.getLogger(__name__)
def make_random_password(
length=10, allowed_chars="abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
@ -56,11 +58,19 @@ def get_jwt_token():
"api_token": settings.CAR_API_TOKEN,
"api_secret": settings.CAR_API_SECRET,
}
logger.debug(f"Attempting to fetch JWT token from: {url}")
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
#logging for success
logger.info("Successfully fetched JWT token.")
return response.text
except requests.exceptions.RequestException as e:
#logging for error
logger.error(
f"HTTP error fetching JWT token from {url}: ",
exc_info=True
)
print(f"Error obtaining JWT token: {e}")
return None
@ -214,8 +224,22 @@ def reserve_car(car, request):
)
car.status = models.CarStatusChoices.RESERVED
car.save()
# --- Logging for Success ---
logger.info(
f"Car {car.id} ('{car.make} {car.model}') reserved successfully "
f"by user {request.user.id} ('{request.user.username}'). "
f"Reserved until: {reserved_until}."
)
messages.success(request, _("Car reserved successfully."))
except Exception as e:
# --- Logging for Error ---
logger.error(
f"Error reserving car {car.id} ('{car.make} {car.model}') "
f"for user {request.user.id} ('{request.user.username}'). "
f"Error: {e}",
exc_info=True
)
messages.error(request, f"Error reserving car: {e}")
return redirect("car_detail", dealer_slug=request.dealer.slug, slug=car.slug)
@ -1260,7 +1284,13 @@ def handle_account_process(invoice, amount, finance_data):
)
try:
car.item_model.for_inventory = False
logger.debug(f"Set item_model.for_inventory to False for car {car.vin}.")
except Exception as e:
logger.error(
f"Error updating item_model.for_inventory for car {car.vin} (Invoice {invoice.invoice_number}): {e}",
exc_info=True
)
print(e)
car.finances.is_sold = True
car.finances.save()

File diff suppressed because it is too large Load Diff

View File

@ -63,10 +63,12 @@
class="btn btn-sm btn-phoenix-primary me-md-2">
{% trans 'View' %}
</a>
{% if perms.django_ledger.change_billmodel %}
<a href="{% url 'django_ledger:bill-update' entity_slug=entity_slug bill_pk=bill.uuid %}"
class="btn btn-sm btn-phoenix-warning me-md-2">
{% trans 'Update' %}
</a>
{% if bill.can_pay %}
<button onclick="djLedger.toggleModal('{{ bill.get_html_id }}')"
@ -80,6 +82,7 @@
{% trans 'Cancel' %}
</button>
{% endif %}
{% endif %}
</div>
</div>
</div>
@ -201,9 +204,10 @@
<div class="card-footer p-0">
<div class="d-flex flex-wrap gap-2 mt-2">
<!-- Update Button -->
{% if perms.django_ledger.change_billmodel%}
<a href="{% url 'bill-update' dealer_slug=dealer_slug entity_slug=entity_slug bill_pk=bill.uuid %}" class="btn btn-phoenix-primary">
<i class="fas fa-edit me-2"></i>{% trans 'Update' %}
</a>
<!-- Mark as Draft -->
{% if bill.can_draft %}
<button class="btn btn-phoenix-success"
@ -247,6 +251,7 @@
</button>
{% modal_action_v2 bill bill.get_mark_as_canceled_url bill.get_mark_as_canceled_message bill.get_mark_as_canceled_html_id %}
{% endif %}
{% endif %}
</div>
</div>
</div>
@ -254,6 +259,7 @@
{% endif %}
{% else %}
<!-- Create Bill Card -->
{% if perms.django_ledger.add_billmodel%}
<div class=" bg-light">
<div class="card-body text-center p-5">
<a href="{% url 'django_ledger:bill-create' entity_slug=entity_slug %}"
@ -263,6 +269,7 @@
</a>
</div>
</div>
{% endif %}
{% endif %}
</div>

View File

@ -9,7 +9,9 @@
<div class="d-flex justify-content-between mb-2">
<h3 class="">{% trans "Expenses" %}</h3>
{% if perms.django_ledger.add_itemmodel %}
<a href="{% url 'item_expense_create' request.dealer.slug %}" class="btn btn-md btn-phoenix-primary"><i class="fa fa-plus me-2"></i>{% trans "Add Expense" %}</a>
{% endif %}
</div>
{% include "partials/search_box.html" %}
{% if page_obj.object_list %}
@ -39,10 +41,12 @@
{{ expense.uom }}
</td>
<td class="align-middle product white-space-nowrap">
{% if perms.django_ledger.change_itemmodel %}
<a href="{% url 'item_expense_update' request.dealer.slug expense.pk %}"
class="btn btn-sm btn-phoenix-success">
{% trans "Update" %}
</a>
{% endif %}
</td>
<td class="align-middle product white-space-nowrap">

View File

@ -8,7 +8,9 @@
<div class="d-flex justify-content-between mb-2">
<h3 class="">{% trans "Services" %}</h3>
{% if perms.inventory.add_additionalservices %}
<a href="{% url 'item_service_create' request.dealer.slug %}" class="btn btn-md btn-phoenix-primary"><i class="fa fa-plus me-2"></i>{% trans "Add Service" %}</a>
{% endif %}
</div>
{% include "partials/search_box.html" %}
{% if page_obj.object_list %}
@ -46,10 +48,12 @@
{{ service.item.co }}
</td>
<td class="align-middle white-space-nowrap text-start">
{% if perms.inventory.add_additionalservices %}
<a href="{% url 'item_service_update' request.dealer.slug service.pk %}"
class="btn btn-sm btn-phoenix-success">
{% trans "Update" %}
</a>
{% endif %}
</td>
</tr>

View File

@ -8,7 +8,9 @@
<div class="d-flex justify-content-between mb-2">
<h3 class="">{% trans "Bank Accounts" %}</h3>
{% if perms.django_ledger.add_bankaccountmodel%}
<a href="{% url 'bank_account_create' request.dealer.slug %}" class="btn btn-md btn-phoenix-primary"><i class="fa fa-plus me-2"></i>{% trans "Add Bank Account" %}</a>
{% endif %}
</div>
{% include "partials/search_box.html" %}
{% if page_obj.object_list %}
@ -38,10 +40,12 @@
{{ bank.account_type|capfirst }}
</td>
<td class="align-middle product white-space-nowrap">
{% if perms.django_ledger.change_bankaccountmodel%}
<a href="{% url 'bank_account_update' request.dealer.slug bank.pk %}"
class="btn btn-sm btn-phoenix-success">
{% trans "Update" %}
</a>
{% endif %}
</td>
</tr>

View File

@ -14,7 +14,9 @@
<div class="row mt-4">
<div class="d-flex justify-content-between mb-2">
<h3 class="">{% trans "Bills" %}</h3>
{% if perms.django_ledger.add_billmodel %}
<a href="{% url 'bill-create' request.dealer.slug entity.slug %}" class="btn btn-md btn-phoenix-primary"><i class="fa fa-plus me-2"></i>{% trans 'New Bill' %}</a>
{% endif %}
</div>
<div class="col-12">
@ -78,12 +80,14 @@
{{bill.vendor.vendor_name}}
</td>
<td class="align-middle product white-space-nowrap">
{% if perms.django_ledger.view_billmodel %}
<div class="btn-reveal-trigger position-static">
<button class="btn btn-sm dropdown-toggle dropdown-caret-none transition-none btn-reveal fs-10" type="button" data-bs-toggle="dropdown" data-boundary="window" aria-haspopup="true" aria-expanded="false" data-bs-reference="parent"><span class="fas fa-ellipsis-h fs-10"></span></button>
<div class="dropdown-menu dropdown-menu-end py-2">
<a href="{% url 'bill-detail' dealer_slug=request.dealer.slug entity_slug=entity.slug bill_pk=bill.pk %}" class="dropdown-item text-success-dark">{% trans 'View' %}</a>
</div>
</div>
{% endif %}
</td>
</tr>
{% empty %}

View File

@ -11,8 +11,11 @@
<h3 class="">
{{ _("Vendors") |capfirst }}
</h2>
<a href="{% url 'vendor_create' request.dealer.slug %}"
class="btn btn-md btn-phoenix-primary"><i class="fa fa-plus me-2"></i>{{ _("Add Vendor") }}</a>
{% if perms.django_ledger.add_vendormodel %}
<a href="{% url 'vendor_create' request.dealer.slug %}" class="btn btn-md btn-phoenix-primary">
<i class="fa fa-plus me-2"></i>{{ _("Add Vendor") }}
</a>
{% endif %}
</div>
{% include "partials/search_box.html" %}
{% if page_obj.object_list %}
@ -121,14 +124,21 @@
<span class="fas fa-ellipsis-h fs-10"></span>
</button>
<div class="dropdown-menu dropdown-menu-end py-2">
{% if perms.django_ledger.change_vendormodel %}
<a href="{% url 'vendor_update' request.dealer.slug vendor.slug %}"
class="dropdown-item text-success-dark">{% trans "Edit" %}</a>
class="dropdown-item text-success-dark">{% trans "Edit" %}
</a>
{% endif %}
{% if perms.django_ledger.delete_vendormodel %}
<div class="dropdown-divider"></div>
<button class="delete-btn dropdown-item text-danger"
data-url="{% url 'vendor_delete' request.dealer.slug vendor.slug %}"
data-message="{{ _("Are you sure you want to delete this vendor") }}?"
data-bs-toggle="modal"
data-bs-target="#deleteModal">{{ _("Delete") }}</button>
data-bs-target="#deleteModal">{{ _("Delete") }}
</button>
{% endif %}
</div>
</div>
</td>

View File

@ -28,10 +28,14 @@
</ul>
</div>
<div class="card-footer d-flex">
{% if perms.django_ledger.change_vendormodel %}
<a class="btn btn-sm btn-phoenix-primary me-1" href="{% url 'vendor_update' request.dealer.slug vendor.slug %}">
{% trans "Edit" %}
<i class="fa fa-pencil"></i>
</a>
{% endif %}
{% if perms.django_ledger.delete_vendormodel %}
<button class="btn btn-phoenix-danger btn-sm delete-btn"
data-url="{% url 'vendor_delete' request.dealer.slug vendor.slug %}"
data-message="{{ _("Are you sure you want to delete this vendor")}}?"
@ -39,6 +43,7 @@
{{ _("Delete") }}
<i class="fas fa-trash"></i>
</button>
{% endif %}
</div>
</div>
</div>