From 5fd0e5c1e5fa799556ec3102eb89be1d780d0032 Mon Sep 17 00:00:00 2001 From: Slawek Bierwiaczonek <119700507+Domejko@users.noreply.github.com> Date: Tue, 12 Mar 2024 19:36:27 +0100 Subject: [PATCH] Code refactored (#216) refactor: Refactored some backend code --- backend/api/base/modal.py | 2 +- backend/api/currency_converter/convert.py | 25 ++++++++-------- .../api/invoices/create/set_destination.py | 2 +- backend/api/invoices/delete.py | 2 +- backend/api/invoices/edit.py | 30 ++++++++----------- backend/api/receipts/delete.py | 10 +++---- backend/auth_backends.py | 5 ---- backend/models.py | 10 ++----- backend/signals.py | 18 +++++------ backend/views/core/invoices/create.py | 14 ++------- backend/views/core/invoices/edit.py | 28 ++++++++--------- backend/views/core/invoices/view.py | 14 ++++----- 12 files changed, 63 insertions(+), 97 deletions(-) diff --git a/backend/api/base/modal.py b/backend/api/base/modal.py index 4f9f2468..ee6ec881 100644 --- a/backend/api/base/modal.py +++ b/backend/api/base/modal.py @@ -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: diff --git a/backend/api/currency_converter/convert.py b/backend/api/currency_converter/convert.py index 849105d5..a17f9e06 100644 --- a/backend/api/currency_converter/convert.py +++ b/backend/api/currency_converter/convert.py @@ -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): diff --git a/backend/api/invoices/create/set_destination.py b/backend/api/invoices/create/set_destination.py index 5e59411b..63eeedaa 100644 --- a/backend/api/invoices/create/set_destination.py +++ b/backend/api/invoices/create/set_destination.py @@ -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) diff --git a/backend/api/invoices/delete.py b/backend/api/invoices/delete.py index 2821cdf6..d16b417f 100644 --- a/backend/api/invoices/delete.py +++ b/backend/api/invoices/delete.py @@ -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: diff --git a/backend/api/invoices/edit.py b/backend/api/invoices/edit.py index da1415a3..4430d46d 100644 --- a/backend/api/invoices/edit.py +++ b/backend/api/invoices/edit.py @@ -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(), @@ -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") diff --git a/backend/api/receipts/delete.py b/backend/api/receipts/delete.py index 43d36902..55ebe036 100644 --- a/backend/api/receipts/delete.py +++ b/backend/api/receipts/delete.py @@ -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") diff --git a/backend/auth_backends.py b/backend/auth_backends.py index be826569..e9f1e6fa 100644 --- a/backend/auth_backends.py +++ b/backend/auth_backends.py @@ -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 diff --git a/backend/models.py b/backend/models.py index 30fde387..abdf1752 100644 --- a/backend/models.py +++ b/backend/models.py @@ -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 @@ -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) diff --git a/backend/signals.py b/backend/signals.py index f66db3c0..e0784967 100644 --- a/backend/signals.py +++ b/backend/signals.py @@ -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) diff --git a/backend/views/core/invoices/create.py b/backend/views/core/invoices/create.py index ab592ed8..f07e7605 100644 --- a/backend/views/core/invoices/create.py +++ b/backend/views/core/invoices/create.py @@ -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") @@ -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") @@ -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) diff --git a/backend/views/core/invoices/edit.py b/backend/views/core/invoices/edit.py index 04adc604..74ce8290 100644 --- a/backend/views/core/invoices/edit.py +++ b/backend/views/core/invoices/edit.py @@ -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 @@ -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(), @@ -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: diff --git a/backend/views/core/invoices/view.py b/backend/views/core/invoices/view.py index 3c054770..7aebccbd 100644 --- a/backend/views/core/invoices/view.py +++ b/backend/views/core/invoices/view.py @@ -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