from django_ledger.forms.account import AccountModelUpdateForm, AccountModelCreateForm import requests import os from dotenv import load_dotenv from django.contrib.auth.models import Permission from django.contrib.auth.models import Group from django_ledger.models.invoice import InvoiceModel from django_ledger.utils import accruable_net_summary from decimal import Decimal from django_ledger.models import ( EstimateModel, EntityModel, ItemModel, ItemTransactionModel, AccountModel, CustomerModel, EntityManagementModel, ) # from rich import print from datetime import date from inventory.models import ( Car, Dealer, VatRate, Lead, CarMake, CarModel, Schedule, CustomGroup, ) from inventory.utils import CarFinanceCalculator from appointment.models import Appointment, AppointmentRequest, Service, StaffMember from appointment.models import Appointment, AppointmentRequest, Service, StaffMember from django.contrib.auth import get_user_model from django_ledger.io.io_core import get_localdate from datetime import datetime, timedelta from django.utils import timezone import hashlib from django_ledger.io import roles User = get_user_model() load_dotenv(".env") def run(): # print(Service.objects.first().pk) # print(Appointment.objects.first().client) # appointment = Appointment.objects.create( # client_name="John Doe", # client_email="john@example.com", # service="Haircut", # date_time="2023-10-15 10:00:00", # status="pending") # make = CarMake.objects.first() # Lead.objects.create( # first_name="John", # last_name="Doe", # email="john@example.com", # phone_number="123-456-7890", # address="123 Main St", # id_car_make=make, # id_car_model=make.carmodel_set.first(), # year="2022", # source="website", # channel="online", # staff="John Doe", # priority="high", # ) # schedult = Schedule.objects.create( # name="John Doe", # email="john@example.com", # phone_number="123-456-7890", # address="123 Main St", # id_car_make=make, # id_car_model=make.carmodel_set.first(), # year="2022", # source="website", # channel="online", # staff="John Doe", # priority="high", # ) # now = timezone.now() # end_time = now + timedelta(minutes=10) # service = Service.objects.first() # appointment_request = AppointmentRequest.objects.create( # date=now.date(), # start_time=now.time(), # end_time=end_time.time(), # service=service, # staff_member=StaffMember.objects.first(), # ) # appointment = Appointment.objects.create( # client=User.objects.first(), # appointment_request=appointment_request, # phone="123-456-7890", # address="123 Main St", # ) # dealer = Dealer.objects.get(user__email="ismail.mosa.ibrahim@gmail.com") # entity = dealer.entity # car_list = Car.objects.filter(dealer=dealer).all() # context = { # "items": [ # { # "car": x, # "product": entity.get_items_all() # .filter(item_role=ItemModel.ITEM_ROLE_PRODUCT, name=x.vin) # .first(), # } # for x in car_list # ], # } # for i in car_list: # hash_object = hashlib.sha256() # hash_object.update(f"{i.id_car_make.name}{i.id_car_model.name}".encode('utf-8')) # print(hash_object.hexdigest() , i.id_car_make.name, i.id_car_model.name) # def get_item(tx:ItemTransactionModel): # data = {"data": {}} # data["data"]["info"] = tx.item_model.additional_info.get('car_info') # data["data"]["finance"] = tx.item_model.additional_info.get('car_finance') # if tx.has_estimate(): # data["data"]["estimate"] = tx.ce_model # data["data"]["has_estimate"] = True # data["data"]["customer"] = tx.ce_model.customer # if tx.has_invoice(): # data["data"]["invoice"] = tx.invoice_model # data["data"]["has_invoice"] = True # data["data"]["customer"] = tx.invoice_model.customer # return data # transactions = ItemTransactionModel.objects.all() # output = [] # for transaction in transactions: # output.append(get_item(transaction)) # print(output) # info = item.additional_info["car_info"] # finance = item.additional_info["car_finance"] # print({"vin":info["make"],"mode":info["model"],"year":info["year"],"trim":info["trim"],"mileage":info["mileage"],"cost_price":finance["cost_price"],"selling_price":finance["selling_price"]}) # info = item.additional_info["car_info"] # finance = item.additional_info["car_finance"] # print({"vin":info["make"],"mode":info["model"],"year":info["year"],"trim":info["trim"],"mileage":info["mileage"],"cost_price":finance["cost_price"],"selling_price":finance["selling_price"]}) # for account in AccountModel.objects.all(): # print(account.path) # print(CustomerModel.objects.all()) # customer = CustomerModel.objects.first() # dealer = Dealer.objects.filter(user__email="esma3el555@gmail.com").first() # customer = CustomerModel.objects.filter(dealer=dealer).first() # print(Car.objects.filter(dealer=dealer,status="available")) # CustomGroup.objects.all().delete() # Group.objects.all().delete() # dealer = Dealer.objects.filter(user__email="esma3el555@gmail.com").first() # group_names = ["Manager", "Inventory", "Accountant", "Agent", "Sales"] # for group_name in group_names: # group,created = Group.objects.get_or_create(name=f"{dealer.pk}_{group_name}") # group_manager,created = CustomGroup.objects.get_or_create(name=group_name, dealer=dealer, group=group) # group_manager.set_default_permissions() # for perm in Permission.objects.filter(content_type__app_label='django_ledger',content_type__model__in=["estimatemodel","invoicemodel","customermodel"]): # sales = CustomGroup.objects.last() # sales.set_default_permissions() # for perm in Permission.objects.filter(content_type__app_label='inventory',content_type__model__in=["lead","salequotation","salequotationcar"]): # print(perm) # print(Permission.objects.filter(codename__in=['view_car','view_carlocation','view_customcard','view_carcolors','view_cartransfer','view_estimatemodel','view_invoicemodel','view_saleorder'])) # print(Permission.objects.filter(codename__in=['view_estimatemodel','view_invoicemodel','view_saleorder'])) # CustomGroup.objects.filter(name='Accountant').last().set_default_permissions() # CustomGroup.objects.filter(name='Inventory').last().set_default_permissions() # EntityManagementModel.objects.create(entity=,user=) # print(Permission.objects.filter(codename__icontains='customermodel').first().codename) # print(os.getenv("DJANGO_ALLOWED_HOSTS")) car_makes = CarMake.objects.all()[:10] # Fetch the entity and COGS account entity = EntityModel.objects.get(admin__email="ismail.mosa.ibrahim@gmail.com") coa = entity.get_default_coa() cogs = entity.get_default_coa_accounts().filter(role=roles.COGS).first() # Loop through car makes and create accounts for make in range(len(car_makes)): # Start from 0 to include all items # Generate a unique code # Create the account # account = AccountModel.objects.create( # name=car_makes[make].name, # code=code, # role=roles.COGS, # coa_model=coa, # balance_type="debit", # active=True, # depth=2, # path=code # ) # account = entity.create_account( # name=car_makes[make].name, # code=code, # role=roles.COGS, # coa_model=coa, # balance_type="debit", # active=True # ) last_account = ( entity.get_all_accounts() .filter(role=roles.COGS) .order_by("-created") .first() ) if len(last_account.code) == 4: code = f"{int(last_account.code)}{1:03d}" elif len(last_account.code) > 4: code = f"{int(last_account.code) + 1}" # account = entity.create_account( # name=car_makes[make].name, # code=code, # role=roles.COGS, # coa_model=coa, # balance_type="debit", # active=True # ) account = AccountModel( name=car_makes[make].name, code=code, role=roles.COGS, coa_model=coa, balance_type="debit", active=True, depth=3, ) # 00060004001S last_account = ( entity.get_all_accounts() .filter(role=roles.COGS) .order_by("-created") .first() ) path = "" if len(last_account.code) == 12: path = f"{int(last_account.path)}{1:03d}" elif len(last_account.code) > 12: path = f"{int(last_account.path) + 1}" # account.path = path try: account = cogs.add_child(instance=account) account.move(cogs, pos="sorted-sibling") account.refresh_from_db() account.save() except Exception as e: print(e) # form_data = { # 'name': car_makes[make].name, # 'code': code, # 'role': roles.COGS, # 'balance_type': 'debit', # 'active': True, # 'coa_model': coa # Ensure the COA model is included # } # Create the form instance with the data # create_form = AccountModelCreateForm(data=form_data, coa_model=coa) # # Validate and save the form # if create_form.is_valid(): # account = create_form.save(commit=False) # account.coa_model = coa # Set the entity for the account # Add the account as a child of the COGS account # cogs.add_child(instance=account) # print(f"Account '{account.name}' created successfully.") # else: # print(f"Failed to create account. Errors: {create_form.errors}") # form = AccountModelUpdateForm(instance=account) # if form.is_valid(): # instance = form.save(commit=False) # instance._position = "sorted-sibling" # instance._ref_node_id = cogs.pk # instance.save() # print(f"Account {account.name} created successfully.") # else: # print(f"Failed to create account {account.name}. Errors: {form.errors}")