Skip to content

Commit

Permalink
Code refactored (#216)
Browse files Browse the repository at this point in the history
refactor: Refactored some backend code
  • Loading branch information
Domejko authored Mar 12, 2024
1 parent b511d76 commit 5fd0e5c
Show file tree
Hide file tree
Showing 12 changed files with 63 additions and 97 deletions.
2 changes: 1 addition & 1 deletion backend/api/base/modal.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def open_modal(request: HttpRequest, modal_name, context_type=None, context_valu
invoice = context_value
try:
invoice = Invoice.objects.get(user=request.user, id=invoice)
except:
except Invoice.DoesNotExist:
return render(request, template_name, context)

if invoice.client_to:
Expand Down
25 changes: 13 additions & 12 deletions backend/api/currency_converter/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,28 +39,29 @@ def convert_currency(init_currency, target_currency, amount, date=None):
if not isinstance(amount, (int, float)):
raise ValueError("Amount is not an accepted datatype")

currency_rates = CurrencyRates()

if date is not None:
if not isinstance(date, datetime.datetime):
raise ValueError("Date is not an accepted datatype")

if date is not None:
# Check if date was a weekend
# Forex's source has no records on weekends (5,6 = Sat, Sun)
if date.weekday() >= 5:
elif date.weekday() >= 5:
# move to friday before the weekend
date = date.replace(day=date.day - (date.weekday() - 4))

currency_rates = CurrencyRates()

try:
if date is not None:
try:
target_amount = currency_rates.convert(init_currency, target_currency, amount, date)
else:
return round(target_amount, 2)
except Exception as e:
# Handle specific exceptions raised by forex_python if needed
raise ValueError(f"Error in currency conversion: {e}")
else:
try:
target_amount = currency_rates.convert(init_currency, target_currency, amount)
return round(target_amount, 2)
except Exception as e:
# Handle specific exceptions raised by forex_python if needed
raise ValueError(f"Error in currency conversion: {e}")
return round(target_amount, 2)
except Exception as e:
raise ValueError(f"Error in currency conversion: {e}")


def currency_conversion(request: HttpRequest):
Expand Down
2 changes: 1 addition & 1 deletion backend/api/invoices/create/set_destination.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def set_destination_to(request: HttpRequest):
try:
client = Client.objects.get(user=request.user, id=selected_client)
context["existing_client"] = client
except:
except Client.DoesNotExist:
messages.error("Client not found")

return render(request, "pages/invoices/create/_to_destination.html", context)
Expand Down
2 changes: 1 addition & 1 deletion backend/api/invoices/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def delete_invoice(request: HttpRequest):

try:
invoice = Invoice.objects.get(id=invoice)
except:
except Invoice.DoesNotExist:
return JsonResponse({"message": "Invoice not found"}, status=404)

if not invoice.user.logged_in_as_team and invoice.user != request.user:
Expand Down
30 changes: 12 additions & 18 deletions backend/api/invoices/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,19 @@
def edit_invoice(request: HttpRequest):
try:
invoice = Invoice.objects.get(id=request.POST.get("invoice_id"))
except:
except Invoice.DoesNotExist:
return JsonResponse({"message": "Invoice not found"}, status=404)

if request.user.logged_in_as_team:
if request.user.logged_in_as_team != invoice.organization:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
else:
if request.user != invoice.user:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
elif request.user != invoice.user:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)

attributes_to_updates = {
"date_due": datetime.strptime(request.POST.get("date_due"), "%Y-%m-%d").date(),
Expand Down Expand Up @@ -76,13 +74,9 @@ def change_status(request: HttpRequest, invoice_id: int, status: str) -> HttpRes
except Invoice.DoesNotExist:
return return_message(request, "Invoice not found")

if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization:
if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization or request.user != invoice.user:
return return_message(request, "You don't have permission to make changes to this invoice.")

else:
if request.user != invoice.user:
return return_message(request, "You don't have permission to make changes to this invoice.")

if status not in ["paid", "overdue", "pending"]:
return return_message(request, "Invalid status. Please choose from: pending, paid, overdue")

Expand Down
10 changes: 4 additions & 6 deletions backend/api/receipts/delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ def receipt_delete(request: HttpRequest, id: int):
if not receipt:
return JsonResponse(status=404, data={"message": "Receipt not found"})

if request.user.logged_in_as_team:
if receipt.organization != request.user.logged_in_as_team:
return JsonResponse(status=403, data={"message": "Forbidden"})
else:
if receipt.user != request.user:
return JsonResponse(status=403, data={"message": "Forbidden"})
if request.user.logged_in_as_team and receipt.organization != request.user.logged_in_as_team:
return JsonResponse(status=403, data={"message": "Forbidden"})
elif receipt.user != request.user:
return JsonResponse(status=403, data={"message": "Forbidden"})

receipt.delete()
messages.success(request, "Receipt deleted")
Expand Down
5 changes: 0 additions & 5 deletions backend/auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,5 @@ def authenticate(self, request, username=None, password=None, **kwargs):
return None
else:
if user.check_password(password):
if user.is_active:
return user

if user.awaiting_email_verification:
return user
return user
return None
10 changes: 2 additions & 8 deletions backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,7 @@ class InvoiceItem(models.Model):
price = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)

def get_total_price(self):
if self.is_service:
return self.hours * self.price_per_hour
else:
return self.price
return self.hours * self.price_per_hour if self.is_service else self.price

def __str__(self):
return self.description
Expand Down Expand Up @@ -346,10 +343,7 @@ def get_subtotal(self):
def get_total_price(self):
total = 0
subtotal = self.get_subtotal()
if self.vat_number:
total = subtotal * 1.2
else:
total = subtotal
total = subtotal * 1.2 if self.vat_number else subtotal
return round(total, 2)


Expand Down
18 changes: 8 additions & 10 deletions backend/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,18 @@ def delete_old_profile_picture(sender, instance, **kwargs):

@receiver(post_delete, sender=UserSettings)
def set_profile_picture_to_none(sender, instance, **kwargs):
if instance.profile_picture:
# Check if the file exists in the storage
if default_storage.exists(instance.profile_picture.name):
instance.profile_picture.delete(save=False)
# Check if the file exists in the storage
if instance.profile_picture and default_storage.exists(instance.profile_picture.name):
instance.profile_picture.delete(save=False)


@receiver(post_delete, sender=Receipt)
def set_profile_picture_to_none(sender, instance, **kwargs):
if instance.image:
# Check if the file exists in the storage
if default_storage.exists(instance.image.name):
instance.image.delete(save=False)
instance.image = None
instance.save()
# Check if the file exists in the storage
if instance.image and default_storage.exists(instance.image.name):
instance.image.delete(save=False)
instance.image = None
instance.save()


@receiver(post_save, sender=User)
Expand Down
14 changes: 2 additions & 12 deletions backend/views/core/invoices/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def invoice_page_post(request: HttpRequest):
if is_existing_client:
try:
client = Client.objects.get(user=request.user, id=request.POST.get("selected_client"))
except:
except Client.DoesNotExist:
messages.error(request, "Client not found")
invoice.delete()
return render(request, "pages/invoices/create/create.html")
Expand All @@ -55,10 +55,7 @@ def invoice_page_post(request: HttpRequest):
invoice.client_city = request.POST.get("to_city")
invoice.client_county = request.POST.get("to_county")
invoice.client_country = request.POST.get("to_country")
if request.POST.get("is_representative") == "on":
invoice.client_is_representative = True
else:
invoice.client_is_representative = False
invoice.client_is_representative = True if request.POST.get("is_representative") == "on" else False

invoice.self_name = request.POST.get("from_name")
invoice.self_company = request.POST.get("from_company")
Expand Down Expand Up @@ -89,10 +86,3 @@ def create_invoice_page(request: HttpRequest):
if request.method == "POST":
return invoice_page_post(request)
return invoice_page_get(request)


@require_http_methods(["GET", "POST"])
def edit_invoice_page(request: HttpRequest):
if request.method == "POST":
return invoice_page_post(request)
return invoice_page_get(request)
28 changes: 13 additions & 15 deletions backend/views/core/invoices/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def invoice_get_existing_data(invoice_obj):
def invoice_edit_page_get(request, invoice_id):
try:
invoice = Invoice.objects.get(id=invoice_id)
except:
except Invoice.DoesNotExist:
return JsonResponse({"message": "Invoice not found"}, status=404)

# use to populate fields with existing data in edit_from_destination.html AND edit_to_destination.html
Expand All @@ -68,21 +68,19 @@ def invoice_edit_page_get(request, invoice_id):
def edit_invoice(request: HttpRequest, invoice_id):
try:
invoice = Invoice.objects.get(id=invoice_id)
except:
except Invoice.DoesNotExist:
return JsonResponse({"message": "Invoice not found"}, status=404)

if request.user.logged_in_as_team:
if request.user.logged_in_as_team != invoice.organization:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
else:
if request.user != invoice.user:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
if request.user.logged_in_as_team and request.user.logged_in_as_team != invoice.organization:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)
elif request.user != invoice.user:
return JsonResponse(
{"message": "You do not have permission to edit this invoice"},
status=403,
)

attributes_to_updates = {
"date_due": datetime.strptime(request.POST.get("date_due"), "%Y-%m-%d").date(),
Expand All @@ -105,7 +103,7 @@ def edit_invoice(request: HttpRequest, invoice_id):
client_to_id = request.POST.get("selected_client")
try:
client_to_obj = Client.objects.get(id=client_to_id, user=request.user)
except:
except Client.DoesNotExist:
client_to_obj = None

if client_to_obj:
Expand Down
14 changes: 6 additions & 8 deletions backend/views/core/invoices/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,12 @@ def preview(request, invoice_id):
messages.error(request, "Invoice not found")
return redirect("invoices dashboard")

if request.user.logged_in_as_team:
if invoice.organization != request.user.logged_in_as_team:
messages.error(request, "You don't have access to this invoice")
return redirect("invoices dashboard")
else:
if invoice.user != request.user:
messages.error(request, "You don't have access to this invoice")
return redirect("invoices dashboard")
if request.user.logged_in_as_team and invoice.organization != request.user.logged_in_as_team:
messages.error(request, "You don't have access to this invoice")
return redirect("invoices dashboard")
elif invoice.user != request.user:
messages.error(request, "You don't have access to this invoice")
return redirect("invoices dashboard")

try:
currency_symbol = request.user.user_profile.get_currency_symbol
Expand Down

0 comments on commit 5fd0e5c

Please sign in to comment.