Skip to content

Commit

Permalink
Removing token override + tests passing token wrong + data table query
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremytraini committed Apr 13, 2023
1 parent 02e2b16 commit 1114735
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 22 deletions.
12 changes: 7 additions & 5 deletions generate_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
# Instantiate a Faker object
fake = Faker()

NUM_INVOICES = 50
NUM_LINE_ITEMS = 200
NUM_INVOICES = 100
NUM_LINE_ITEMS = 300

def random_lat():
min_lat, max_lat = -34.05, -33.568
Expand All @@ -31,7 +31,7 @@ def random_lon():
fake.name(),
fake.email(),
fake.phone_number(),
) for i in range(20)]
) for _ in range(20)]

# Generate fake data for the invoices table
invoices = []
Expand Down Expand Up @@ -70,8 +70,10 @@ def random_lon():
customer[0],
customer[1],
delivery_date.strftime('%Y-%m-%d'),
customer[2],
customer[3],
round(random.uniform(supplier_warehouse[0], customer[2]), 6),
round(random.uniform(supplier_warehouse[1], customer[3]), 6),
# customer[2],
# customer[3],
customer[4],
customer[5],
customer[6],
Expand Down
104 changes: 103 additions & 1 deletion src/invoice_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,25 @@ def invoice_processing_delete_v2(invoice_id: int, owner: int):

return {}

def coord_distance(lat1, lon1, lat2, lon2):
from math import sin, cos, sqrt, atan2, radians

# Approximate radius of earth in km
R = 6373.0

lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

return R * c

def invoice_processing_query_v2(query: str, from_date: str, to_date: str, owner: int):
if query == "numActiveCustomers":
from_date = datetime.strptime(from_date, "%Y-%m-%d")
Expand Down Expand Up @@ -310,6 +329,7 @@ def invoice_processing_query_v2(query: str, from_date: str, to_date: str, owner:
"value": num_active_customers,
"change": percentage_change,
}

elif query == "numInvoices":
from_date = datetime.strptime(from_date, "%Y-%m-%d")
to_date = datetime.strptime(to_date, "%Y-%m-%d")
Expand Down Expand Up @@ -386,17 +406,99 @@ def invoice_processing_query_v2(query: str, from_date: str, to_date: str, owner:
"change": percentage_change
}

elif query == "avgDeliveryDistance":
from_date = datetime.strptime(from_date, "%Y-%m-%d")
to_date = datetime.strptime(to_date, "%Y-%m-%d")

query = (Invoices.select(Invoices.supplier_latitude, Invoices.supplier_longitude, Invoices.delivery_latitude, Invoices.delivery_longitude)
.where((Invoices.is_valid == True) &
(Invoices.invoice_start_date >= from_date) &
(Invoices.invoice_start_date <= to_date) &
(Invoices.owner == owner)))

total = 0
number = 0
for invoice in query:
total += coord_distance(invoice.supplier_latitude, invoice.supplier_longitude, invoice.delivery_latitude, invoice.delivery_longitude)
number += 1

if number:
average = total / number
else:
average = 0

# calculate the percentage change from the previous 12 months
previous_year_end = from_date - timedelta(days=1)
previous_year_start = previous_year_end - timedelta(days=365)

previous_year_query = (Invoices.select(Invoices.supplier_latitude, Invoices.supplier_longitude, Invoices.delivery_latitude, Invoices.delivery_longitude)
.where((Invoices.is_valid == True) &
(Invoices.invoice_start_date >= previous_year_start) &
(Invoices.invoice_start_date <= previous_year_end) &
(Invoices.owner == owner)))

previous_year_total = 0
previous_year_number = 0
for invoice in previous_year_query:
previous_year_total += coord_distance(invoice.supplier_latitude, invoice.supplier_longitude, invoice.delivery_latitude, invoice.delivery_longitude)
previous_year_number += 1

if previous_year_number:
previous_year_average = previous_year_total / previous_year_number
else:
previous_year_average = 0

if previous_year_average:
percentage_change = (average - previous_year_average) / previous_year_average * 100
else:
percentage_change = 0

return {
"value": average,
"change": percentage_change
}

elif query == "clientDataTable":
from_date = datetime.strptime(from_date, "%Y-%m-%d")
to_date = datetime.strptime(to_date, "%Y-%m-%d")

# Get name, total invoices and total invoice value for each client

query = (Invoices.select(Invoices.customer_name,
fn.COUNT(Invoices.id).alias('total_invoices'),
fn.SUM(Invoices.total_amount).alias('total_invoice_value'))
.where((Invoices.is_valid == True) &
(Invoices.invoice_start_date >= from_date) &
(Invoices.invoice_start_date <= to_date) &
(Invoices.owner == owner))
)

query = query.group_by(Invoices.customer_name)

client_data = []
for i, invoice in enumerate(query):
client_data.append({
"id": i,
"name": invoice.customer_name,
"total-deliveries": invoice.total_invoices,
"total-revenue": '{:.2f}'.format(round(invoice.total_invoice_value, 2))
})

return {
"data": client_data
}

elif query == "heatmapCoords":
from_date = datetime.strptime(from_date, "%Y-%m-%d")
to_date = datetime.strptime(to_date, "%Y-%m-%d")

delivery_coords = []
query = (Invoices.select(Invoices.delivery_latitude, Invoices.delivery_longitude, Invoices.total_amount)
.where((Invoices.is_valid == True) &
(Invoices.invoice_start_date >= from_date) &
(Invoices.invoice_start_date <= to_date) &
(Invoices.owner == owner)))

delivery_coords = []
for invoice in query:
delivery_coords.append({
"lat": invoice.delivery_latitude,
Expand Down
6 changes: 3 additions & 3 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,14 +97,14 @@ async def not_found_error_exception_handler(request: Request, exc: NotFoundError
},
)

@app.exception_handler(InternalServerError)
async def validation_exception_handler(request: Request, exc: InternalServerError):
@app.exception_handler(Exception)
async def validation_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={
"code": 500,
"name": "Internal Server Error",
"detail": exc.detail
"detail": str(exc)
},
)

Expand Down
17 changes: 8 additions & 9 deletions src/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,14 @@ def report_delete_v2(token: str, report_id: int) -> Dict[None, None]:
report = Reports.get_by_id(report_id)
except DoesNotExist:
raise NotFoundError(detail=f"Report with id {report_id} not found")

if not token == ADMIN_TOKEN:
try:
session = Sessions.get(token=token)
except DoesNotExist:
raise UnauthorisedError("Invalid token")

if not report.owner == session.user:
raise ForbiddenError("You do not have permission to delete this report")

try:
session = Sessions.get(token=token)
except DoesNotExist:
raise UnauthorisedError("Invalid token")

if not report.owner == session.user:
raise ForbiddenError("You do not have permission to delete this report")

report.delete_instance()

Expand Down
2 changes: 2 additions & 0 deletions tests/report/lint_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def test_lint_valid_invoice():
lint_report = report_lint_v1(invoice)

assert lint_report == {
"num_errors": 0,
"num_warnings": 0,
"report": []
}

Expand Down
7 changes: 3 additions & 4 deletions tests/server_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import json
from src.config import full_url
from src.type_structure import *
from src.constants import ADMIN_TOKEN

# Invoice Endpoints

Expand Down Expand Up @@ -219,19 +218,19 @@ def report_check_validity_v1(report_id: int) -> Server_call_return:

def report_delete_v2(token: str, report_id: int) -> Server_call_return:
payload = {
"token": ADMIN_TOKEN,
"report_id": report_id
}
headers = {
"Authorization": "bearer " + token
}
response = requests.delete(full_url + 'report/delete/v2', params=payload, headers=headers)

print(response.json())

return json.loads(response.text)
return response.json()

def report_change_name_v2(token: str, report_id: int, new_name: str) -> Server_call_return:
payload = {
"token": ADMIN_TOKEN,
"report_id": report_id,
"new_name": new_name
}
Expand Down

0 comments on commit 1114735

Please sign in to comment.