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

More handoff changes #238

Merged
merged 12 commits into from
Apr 7, 2024
8 changes: 7 additions & 1 deletion backend/app/rest/log_records_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,15 @@ def get_log_records():
except:
pass

sort_direction = "DESC"
try:
sort_direction = request.args.get("sort_direction").upper()
except:
pass

try:
log_records = log_records_service.get_log_records(
page_number, return_all, results_per_page, filters
page_number, return_all, sort_direction, results_per_page, filters
)
return jsonify(log_records), 201
except Exception as e:
Expand Down
12 changes: 1 addition & 11 deletions backend/app/rest/residents_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def update_resident(resident_id):
return (
jsonify(
{
"message": "Resident record with id {resident_id} updated sucessfully".format(
"message": "Tenant record with id {resident_id} updated sucessfully".format(
resident_id=resident_id
)
}
Expand Down Expand Up @@ -119,16 +119,6 @@ def get_residents():
page_number = int(request.args.get("page_number"))
except:
pass
try:
filters = json.loads(request.args.get("filters"))
except:
filters = None

filters = None
try:
filters = json.loads(request.args.get("filters"))
except:
pass

filters = None
try:
Expand Down
11 changes: 8 additions & 3 deletions backend/app/services/implementations/log_records_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def to_json_list(self, logs):
"first_name": log[2],
"last_name": log[3],
},
"residents": log[4],
"residents": log[4] if log[4] else [],
"attn_to": {
"id": log[5],
"first_name": log[6],
Expand Down Expand Up @@ -209,7 +209,12 @@ def join_tag_attributes(self):
) t ON logs.log_id = t.log_id\n"

def get_log_records(
self, page_number, return_all, results_per_page=10, filters=None
self,
page_number,
return_all,
sort_direction="DESC",
results_per_page=10,
filters=None,
):
try:
sql = "SELECT\n \
Expand All @@ -236,7 +241,7 @@ def get_log_records(
sql += self.join_tag_attributes()
sql += self.filter_log_records(filters)

sql += "\nORDER BY datetime DESC"
sql += f"\nORDER BY datetime {sort_direction}"

if not return_all:
sql += f"\nLIMIT {results_per_page}"
Expand Down
97 changes: 51 additions & 46 deletions backend/app/services/implementations/residents_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
DuplicateResidentException,
)
from datetime import datetime
from sqlalchemy.sql.expression import or_, and_
from sqlalchemy.sql.expression import or_, and_, case
from pytz import timezone


Expand Down Expand Up @@ -40,25 +40,15 @@ def to_resident_json(self, resident, current_date):
def to_residents_json_list(self, residents, current_date):
residents_json_list = []
for result in residents:
resident, building = result[0], result[1]
resident, building, status = result[0], result[1], result[2]

resident_dict = resident.to_dict()
resident_dict["building"]["name"] = building
resident_dict["status"] = self.get_resident_status(
current_date, resident_dict["date_joined"], resident_dict["date_left"]
)
resident_dict["status"] = status

residents_json_list.append(resident_dict)
return residents_json_list

def get_resident_status(self, current_date, date_joined, date_left):
if current_date < date_joined:
return "Future"
elif date_left is None or current_date <= date_left:
return "Current"
else:
return "Past"

def convert_to_date_obj(self, date):
return datetime.strptime(date, "%Y-%m-%d")

Expand All @@ -78,7 +68,7 @@ def is_date_left_invalid_resident(self, resident):

return False

def construct_filters(self, query, filters, current_date):
def construct_filters(self, query, filters, status_column):
residents = filters.get("residents")
buildings = filters.get("buildings")
statuses = filters.get("statuses")
Expand All @@ -101,35 +91,12 @@ def construct_filters(self, query, filters, current_date):
if residents is not None:
query = query.filter(Residents.id.in_(residents))
if statuses is not None:
conditions = []

# Construct the conditions for each case
for status in statuses:
if status == "Future":
conditions.append(Residents.date_joined > current_date)
elif status == "Current":
conditions.append(
and_(
Residents.date_joined <= current_date,
or_(
Residents.date_left.is_(None),
Residents.date_left >= current_date,
),
)
)
elif status == "Past":
conditions.append(Residents.date_left < current_date)

# OR them together and add to filter
query = query.filter(or_(*conditions))

query = query.filter(status_column.in_(statuses))
if date_joined is not None:
query = query.filter(Residents.date_joined >= date_joined)
if date_left is not None:
query = query.filter(Residents.date_left <= date_left)

query = query.order_by(Residents.last_modified.desc())

return query

def add_resident(self, resident):
Expand Down Expand Up @@ -163,7 +130,7 @@ def update_resident(self, resident_id, updated_resident):
).update({Residents.date_left: None, **updated_resident})
if not create_update_resident:
raise Exception(
"Resident with id {resident_id} not found".format(
"Tenant with id {resident_id} not found".format(
resident_id=resident_id
)
)
Expand Down Expand Up @@ -214,23 +181,44 @@ def get_residents(self, return_all, page_number, results_per_page, filters=None)
try:
current_date = datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d")

# add a status column based on the current date
status_column = case(
(
and_(
Residents.date_joined <= current_date,
or_(
Residents.date_left.is_(None),
Residents.date_left >= current_date,
),
),
"Current",
),
(Residents.date_joined > current_date, "Future"),
(Residents.date_left < current_date, "Past"),
).label("status")

residents_results = Residents.query.join(
Buildings, Buildings.id == Residents.building_id
).with_entities(Residents, Buildings.name.label("building"))
).with_entities(Residents, Buildings.name.label("building"), status_column)
if filters:
residents_results = self.construct_filters(
residents_results, filters, current_date
residents_results, filters, status_column
)

if not return_all:
residents_results = (
residents_results.order_by(Residents.last_modified.desc())
residents_results.order_by(
status_column,
case((Residents.date_left.is_(None), 0), else_=1),
Residents.room_num,
Residents.initial,
)
.limit(results_per_page)
.offset((page_number - 1) * results_per_page)
)
else:
residents_results = residents_results.order_by(
Residents.last_modified.desc()
Residents.room_num, Residents.initial
).all()

return {
Expand All @@ -244,14 +232,31 @@ def get_residents(self, return_all, page_number, results_per_page, filters=None)

def count_residents(self, filters):
try:
current_date = datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d")

# add a status column based on the current date
status_column = case(
(
and_(
Residents.date_joined <= current_date,
or_(
Residents.date_left.is_(None),
Residents.date_left >= current_date,
),
),
"Current",
),
(Residents.date_joined > current_date, "Future"),
(Residents.date_left < current_date, "Past"),
).label("status")

residents_results = Residents.query.join(
Buildings, Buildings.id == Residents.building_id
).with_entities(Residents, Buildings.name.label("building"))
).with_entities(Residents, Buildings.name.label("building"), status_column)

if filters:
current_date = datetime.now(timezone("US/Eastern")).strftime("%Y-%m-%d")
residents_results = self.construct_filters(
residents_results, filters, current_date
residents_results, filters, status_column
)

count = residents_results.count()
Expand Down
10 changes: 5 additions & 5 deletions backend/app/services/implementations/tags_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ def __init__(self, logger):

def get_tags(self, return_all, page_number, results_per_page):
try:
tags_results = Tag.query.order_by(Tag.last_modified.desc())

if return_all:
tags_results = tags_results.all()
tags_results = Tag.query.order_by(Tag.name).all()
else:
tags_results = tags_results.limit(results_per_page).offset(
(page_number - 1) * results_per_page
tags_results = (
Tag.query.order_by(Tag.last_modified.desc())
.limit(results_per_page)
.offset((page_number - 1) * results_per_page)
)

tags_results = list(map(lambda tag: tag.to_dict(), tags_results))
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/implementations/user_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def get_auth_id_by_user_id(self, user_id):
def get_users(self, return_all, page_number, results_per_page):
try:
if return_all:
users = User.query.order_by(User.last_modified.desc()).all()
users = User.query.order_by(User.last_name).all()
else:
users = (
User.query.order_by(User.last_modified.desc())
Expand Down
7 changes: 6 additions & 1 deletion backend/app/services/interfaces/log_records_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ def add_record(self, log_record):

@abstractmethod
def get_log_records(
self, page_number, return_all, results_per_page=10, filters=None
self,
page_number,
return_all,
sort_direction="desc",
results_per_page=10,
filters=None,
):
"""
Get all log records
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ class DuplicateResidentException(Exception):
"""

def __init__(self, resident_id):
message = f"Resident with ID {resident_id} already exists."
message = f"Tenant with ID {resident_id} already exists."
super().__init__(message)
4 changes: 2 additions & 2 deletions frontend/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Resident management system for Supportive Housing of Waterloo"
content="Tenant management system for Supportive Housing of Waterloo"
/>
<!--
manifest.json provides metadata used when your web app is installed on a
Expand All @@ -23,7 +23,7 @@
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>SHOW Resident Management</title>
<title>SHOW Tenant Management</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/APIClients/LogRecordAPIClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const filterLogRecords = async ({
returnAll = false,
pageNumber,
resultsPerPage,
sortDirection,
}: LogRecordFilters): Promise<GetLogRecordsReponse> => {
try {
const bearerToken = `Bearer ${getLocalStorageObjProperty(
Expand All @@ -77,6 +78,7 @@ const filterLogRecords = async ({
returnAll,
pageNumber,
resultsPerPage,
sortDirection,
},
headers: { Authorization: bearerToken },
});
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/APIClients/ResidentAPIClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,11 @@ const createResident = async ({
return {
errMessage:
axiosErr.response.data.error ??
`Resident with the specified user ID already exists.`,
`Tenant with the specified user ID already exists.`,
};
}
return {
errMessage: "Unable to add resident.",
errMessage: "Unable to add tenant.",
};
}
};
Expand Down Expand Up @@ -159,11 +159,11 @@ const editResident = async ({
return {
errMessage:
axiosErr.response.data.error ??
"Resident with the specified user ID already exists.",
"Tenant with the specified user ID already exists.",
};
}
return {
errMessage: "Unable to update resident.",
errMessage: "Unable to update tenant.",
};
}
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/common/NavigationBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ const NavigationBar = (): React.ReactElement => {
variant="link button-navbar"
onClick={navigateToResidentDirectory}
>
Resident Directory
Tenant Directory
</Button>

{authenticatedUser?.role === "Admin" && (
Expand Down
Loading
Loading