Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug fixed when creating receipt and deleting the receipts #326

Merged
merged 7 commits into from
Apr 12, 2024
5 changes: 2 additions & 3 deletions backend/api/invoices/delete.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from django.contrib import messages
from django.http import HttpRequest, JsonResponse, QueryDict, HttpResponse
from django.http import HttpRequest, JsonResponse, QueryDict, HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import resolve
from django.urls import resolve, reverse
from django.urls.exceptions import Resolver404
from django.views.decorators.http import require_http_methods

from backend.models import Invoice, QuotaLimit


Expand Down
36 changes: 19 additions & 17 deletions backend/api/receipts/delete.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, JsonResponse
from django.shortcuts import render
from django.http import HttpRequest, JsonResponse, HttpResponse, HttpResponseRedirect, QueryDict
from django.shortcuts import render, redirect
from django.urls import resolve, Resolver404, reverse
from django.views.decorators.http import require_http_methods

from backend.models import Receipt


@require_http_methods(["DELETE"])
@login_required
def receipt_delete(request: HttpRequest, id: int):
receipt = Receipt.objects.filter(id=id).first()
receipt = Receipt.objects.get(id=id)
TreyWW marked this conversation as resolved.
Show resolved Hide resolved
if not receipt:
return JsonResponse(status=404, data={"message": "Receipt not found"})

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"})

# QuotaLimit.delete_quota_usage("receipts-count", request.user, receipt.id, receipt.date_uploaded) # Don't want to delete receipts
# from records because it does cost us PER receipt. So makes sense not to allow Upload, delete, upload .. etc
if not receipt.has_access(request.user):
return JsonResponse({"message": "You do not have permission to delete this invoice"}, status=404)

receipt.delete()
messages.success(request, "Receipt deleted")
return render(
request,
"pages/receipts/_search_results.html",
{"receipts": Receipt.objects.filter(user=request.user).order_by("-date")},
)
messages.success(request, f"Receipt deleted with the name of {receipt.name}")
if request.user.logged_in_as_team:
return render(
request,
"pages/receipts/_search_results.html",
{"receipts": Receipt.objects.filter(organization=request.user.logged_in_as_team).order_by("-date")},
)
else:
return render(
request,
"pages/receipts/_search_results.html",
{"receipts": Receipt.objects.filter(user=request.user).order_by("-date")},
)
27 changes: 15 additions & 12 deletions backend/api/receipts/new.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,25 @@ def receipt_create(request: HttpRequest):
if not date:
date = None

receipt = Receipt(
name=name,
image=file,
date=date,
merchant_store=merchant_store,
purchase_category=purchase_category,
total_price=total_price,
)
receipt_data = {
"name": name,
"image": file,
"date": date,
"merchant_store": merchant_store,
"purchase_category": purchase_category,
"total_price": total_price,
}

if request.user.logged_in_as_team:
receipt.organization = request.user.logged_in_as_team
receipt_data["organization"] = request.user.logged_in_as_team
receipts = Receipt.objects.filter(organization=request.user.logged_in_as_team).order_by("-date")
else:
receipt.user = request.user
receipt_data["user"] = request.user
receipts = Receipt.objects.filter(user=request.user).order_by("-date")

receipt.save()
receipt = Receipt(**receipt_data)
QuotaUsage.create_str(request.user, "receipts-count", receipt.id)
receipt.save()
# r = requests.post(
# "https://ocr.asprise.com/api/receipt",
# data={
Expand All @@ -74,5 +77,5 @@ def receipt_create(request: HttpRequest):
return render(
request,
"pages/receipts/_search_results.html",
{"receipts": Receipt.objects.filter(user=request.user).order_by("-date")},
{"receipts": receipts},
)
12 changes: 12 additions & 0 deletions backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,18 @@ class Receipt(models.Model):
class Meta:
constraints = [USER_OR_ORGANIZATION_CONSTRAINT()]

def __str__(self):
return f"{self.name} - {self.date} ({self.total_price})"

def has_access(self, user: User) -> bool:
if not user.is_authenticated:
return False

if user.logged_in_as_team:
return self.organization == user.logged_in_as_team
else:
return self.user == user


class ReceiptDownloadToken(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Expand Down
17 changes: 6 additions & 11 deletions infrastructure/aws/iam/sfn.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import json
from typing import NoReturn

import logging
from mypy_boto3_iam.type_defs import CreatePolicyResponseTypeDef, PolicyTypeDef

from infrastructure.aws.handler import get_iam_client, DEBUG_LEVEL
from infrastructure.aws.handler import get_iam_client as iam_client, DEBUG_LEVEL
from settings.settings import AWS_TAGS_APP_NAME

iam_client = get_iam_client()

import logging

logger = logging.getLogger(__name__)

Expand All @@ -21,8 +16,8 @@ def get_sfn_execute_role_arn() -> str | None:
print("[AWS] Fetching scheduler role by name...", flush=True)

try:
response = iam_client.get_role(RoleName=f"{AWS_TAGS_APP_NAME}-invoicing-scheduler")
except (iam_client.exceptions.NoSuchEntityException, iam_client.exceptions.ServiceFailureException):
response = iam_client().get_role(RoleName=f"{AWS_TAGS_APP_NAME}-invoicing-scheduler")
except (iam_client().exceptions.NoSuchEntityException, iam_client().exceptions.ServiceFailureException):
response = {}

if response.get("Role"):
Expand All @@ -38,7 +33,7 @@ def get_or_create_policy() -> CreatePolicyResponseTypeDef | PolicyTypeDef:
if DEBUG_LEVEL == "debug":
print("[AWS] Fetching all policies by prefix...", flush=True)

response = iam_client.list_policies(Scope="Local", PathPrefix=f"/{AWS_TAGS_APP_NAME}-scheduled-invoices/")
response = iam_client().list_policies(Scope="Local", PathPrefix=f"/{AWS_TAGS_APP_NAME}-scheduled-invoices/")

policies = [
policy for policy in response.get("Policies", []) if policy.get("PolicyName") == f"{AWS_TAGS_APP_NAME}-invoicing-scheduler-fn"
Expand All @@ -57,7 +52,7 @@ def get_or_create_policy() -> CreatePolicyResponseTypeDef | PolicyTypeDef:
if DEBUG_LEVEL:
print("[AWS] Creating new policy for scheduler step function to access API Destination...", flush=True)

return iam_client.create_policy(
return iam_client().create_policy(
PolicyName=f"{AWS_TAGS_APP_NAME}-invoicing-scheduler-fn",
Path=f"/{AWS_TAGS_APP_NAME}-scheduled-invoices/",
PolicyDocument=json.dumps(
Expand Down
6 changes: 2 additions & 4 deletions infrastructure/aws/schedules/list_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@

from mypy_boto3_scheduler.type_defs import ScheduleSummaryTypeDef

from infrastructure.aws.handler import get_event_bridge_scheduler
from infrastructure.aws.handler import get_event_bridge_scheduler as event_bridge_scheduler
from settings.settings import AWS_TAGS_APP_NAME

event_bridge_scheduler = get_event_bridge_scheduler()


@dataclass(frozen=True)
class SuccessResponse:
Expand All @@ -24,7 +22,7 @@ class ErrorResponse:

def list_schedules() -> ScheduleListResponse:
try:
schedules = event_bridge_scheduler.list_schedules(
schedules = event_bridge_scheduler().list_schedules(
NamePrefix=f"{AWS_TAGS_APP_NAME}-scheduled-invoices",
State="ENABLED",
) # possibly add groups in the future
Expand Down