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

Finish seeding scripts and other bugs/improvements #229

Merged
merged 2 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions backend/app/models/residents.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class Residents(db.Model):
__tablename__ = "residents"
id = db.Column(db.Integer, primary_key=True, nullable=False)
initial = db.Column(db.String, nullable=False)
room_num = db.Column(db.Integer, nullable=False)
room_num = db.Column(db.String, nullable=False)
date_joined = db.Column(db.Date, nullable=False)
date_left = db.Column(db.Date, nullable=True)
building_id = db.Column(db.Integer, db.ForeignKey("buildings.id"), nullable=False)
Expand All @@ -22,12 +22,13 @@ class Residents(db.Model):
"LogRecords", secondary="log_record_residents", back_populates="residents"
)

resident_id = db.column_property(initial + cast(room_num, String))
resident_id = db.column_property(initial + room_num)

__table_args__ = (
db.CheckConstraint(
"date_left IS NULL OR date_left > date_joined", name="check_date_left_valid"
),
db.UniqueConstraint("initial", "room_num"),
)

def to_dict(self, include_relationships=False):
Expand Down
2 changes: 1 addition & 1 deletion backend/app/rest/auth_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def register():

response = {"requires_two_fa": False, "auth_user": None}

if os.getenv("TWILIO_ENABLED") == "True" and auth_dto.role == "Relief Staff":
if os.getenv("TWO_FA_ENABLED") == "True" and auth_dto.role == "Relief Staff":
response["requires_two_fa"] = True
return jsonify(response), 200

Expand Down
6 changes: 2 additions & 4 deletions backend/app/rest/residents_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def add_resident():
)

# Check for the existence of a resident prior to adding them
fmt_resident_id = resident.get("initial") + str(resident.get("room_num"))
fmt_resident_id = resident.get("initial") + resident.get("room_num")
try:
existing_resident = residents_service.get_resident_by_id(fmt_resident_id)
if existing_resident:
Expand Down Expand Up @@ -62,9 +62,7 @@ def update_resident(resident_id):
)

# Check for the existence of a resident prior to adding them
fmt_resident_id = updated_resident.get("initial") + str(
updated_resident.get("room_num")
)
fmt_resident_id = updated_resident.get("initial") + updated_resident.get("room_num")
try:
existing_resident = residents_service.get_resident_by_id(fmt_resident_id)
if existing_resident and existing_resident["id"] != resident_id:
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/interfaces/residents_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def add_resident(self, id, initial, room_num, date_joined, date_left, building_i
:param initial: initial of resident
:type initial: string
:param room_num: room number which the resident resides in
:type room_num: int
:type room_num: string
:param date_joined: the date the resident joined
:type date_joined: date
:param date_left: the date the resident left, if exists
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""add unique constraint to combined resident id

Revision ID: 6ba7859cdf27
Revises: a1f05c8f324c
Create Date: 2024-01-29 02:25:45.352261

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = "6ba7859cdf27"
down_revision = "a1f05c8f324c"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("entities")
with op.batch_alter_table("residents", schema=None) as batch_op:
batch_op.create_unique_constraint(None, ["initial", "room_num"])

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("residents", schema=None) as batch_op:
batch_op.drop_constraint(None, type_="unique")

op.create_table(
"entities",
sa.Column("id", sa.INTEGER(), autoincrement=True, nullable=False),
sa.Column("string_field", sa.VARCHAR(), autoincrement=False, nullable=False),
sa.Column("int_field", sa.INTEGER(), autoincrement=False, nullable=False),
sa.Column(
"enum_field",
postgresql.ENUM("A", "B", "C", "D", name="enum"),
autoincrement=False,
nullable=False,
),
sa.Column(
"string_array_field",
postgresql.ARRAY(sa.VARCHAR()),
autoincrement=False,
nullable=False,
),
sa.Column("bool_field", sa.BOOLEAN(), autoincrement=False, nullable=False),
sa.Column("file_name", sa.VARCHAR(), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint("id", name="entities_pkey"),
)
# ### end Alembic commands ###
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""change resident room number to be string

Revision ID: eff8a5a7fda3
Revises: 6ba7859cdf27
Create Date: 2024-01-31 04:13:02.272243

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "eff8a5a7fda3"
down_revision = "6ba7859cdf27"
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("residents", schema=None) as batch_op:
batch_op.alter_column(
"room_num",
existing_type=sa.INTEGER(),
type_=sa.String(),
existing_nullable=False,
)

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("residents", schema=None) as batch_op:
batch_op.alter_column(
"room_num",
existing_type=sa.String(),
type_=sa.INTEGER(),
existing_nullable=False,
)

# ### end Alembic commands ###
22 changes: 22 additions & 0 deletions db-init/create-multiple-dbs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/bin/bash

set -e
set -u

function create_user_and_database() {
local database=$1
echo " Creating user and database '$database'"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
CREATE USER $database;
CREATE DATABASE $database;
GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
EOSQL
}

if [ -n "$POSTGRES_MULTIPLE_DATABASES" ]; then
echo "Multiple database creation requested: $POSTGRES_MULTIPLE_DATABASES"
for db in $(echo $POSTGRES_MULTIPLE_DATABASES | tr ',' ' '); do
create_user_and_database $db
done
echo "Multiple databases created"
fi
36 changes: 21 additions & 15 deletions frontend/src/components/common/Pagination.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import {
MenuList,
MenuItem,
Button,
NumberInput,
NumberInputField,
IconButton,
Flex,
Box,
Text,
Input,
} from "@chakra-ui/react";

import {
Expand Down Expand Up @@ -42,14 +41,23 @@ const Pagination = ({
}: Props): React.ReactElement => {
const numPages = Math.ceil(Math.max(1, numRecords) / resultsPerPage);

const handleNumberInputChange = (
newUserPageNumString: string,
newUserPageNum: number,
) => {
if (newUserPageNum < 1 || newUserPageNum > numPages) {
const handleNumberInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const input = e.target.value as string;

if (input === "") {
setUserPageNum(NaN);
return;
}
setUserPageNum(newUserPageNum);

const numericInput = input.replace(/[^0-9]/g, "");

if (numericInput !== "") {
const newUserPageNum = Number(numericInput);
if (newUserPageNum < 1 || newUserPageNum > numPages) {
return;
}
setUserPageNum(newUserPageNum);
}
};

// Only fetch records if a valid page num is present AND the page num has changed
Expand Down Expand Up @@ -106,19 +114,17 @@ const Pagination = ({
width="210px"
>
<Text>Page</Text>
<NumberInput
<Input
maxW="60px"
value={!Number.isNaN(userPageNum) ? userPageNum : ""}
max={numPages}
size="sm"
onChange={handleNumberInputChange}
onBlur={() => handleBlur()}
>
<NumberInputField
fontWeight="700"
onKeyUp={(e) => handleKeyUp(e)}
/>
</NumberInput>
fontWeight="700"
color="gray.750"
onKeyUp={(e) => handleKeyUp(e)}
/>
<Text>of {numPages}</Text>
</Flex>
<IconButton
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/forms/CreateResident.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const CreateResident = ({
const addResident = async () => {
const res = await ResidentAPIClient.createResident({
initial: initials.toUpperCase(),
roomNum: parseInt(roomNumber, 10),
roomNum: roomNumber,
dateJoined: convertToString(moveInDate),
buildingId,
});
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/forms/EditResident.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const EditResident = ({
getRecords,
}: Props): React.ReactElement => {
const [initials, setInitials] = useState("");
const [roomNumber, setRoomNumber] = useState(-1);
const [roomNumber, setRoomNumber] = useState("");
const [moveInDate, setMoveInDate] = useState(new Date());
const [buildingId, setBuildingId] = useState<number>(resident.building.id);
const [moveOutDate, setMoveOutDate] = useState<Date | undefined>();
Expand Down Expand Up @@ -102,7 +102,7 @@ const EditResident = ({
const handleRoomNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const inputValue = e.target.value as string;
if (inputValue !== null && /^[0-9]{0,3}$/.test(inputValue)) {
setRoomNumber(parseInt(inputValue, 10));
setRoomNumber(inputValue);
setRoomNumberError(false);
}
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/types/ResidentTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type Resident = {
id: number;
residentId: string;
initial: string;
roomNum: number;
roomNum: string;
dateJoined: string;
dateLeft?: string;
building: BuildingRecord;
Expand Down
Loading
Loading