Skip to content

Commit

Permalink
Merge pull request #38 from jadmsaadaot/SUBMIT-task#30
Browse files Browse the repository at this point in the history
Handle inserting projects to account and getting projects by account
  • Loading branch information
jadmsaadaot authored Aug 21, 2024
2 parents b9ac4b8 + 348ba46 commit 13e364d
Show file tree
Hide file tree
Showing 32 changed files with 331 additions and 73 deletions.
2 changes: 1 addition & 1 deletion submit-api/migrations/versions/0223afc14044_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""empty message
"""Create account, role, account_project, account_user, account_role, project_team tables
Revision ID: 0223afc14044
Revises: 20bcb68bc2ac
Expand Down
2 changes: 1 addition & 1 deletion submit-api/migrations/versions/20bcb68bc2ac_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""
"""Create staff_users table
Revision ID: 20bcb68bc2ac
Revises:
Expand Down
2 changes: 1 addition & 1 deletion submit-api/migrations/versions/6dfc3501adbb_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""empty message
"""Add description column to roles table
Revision ID: 6dfc3501adbb
Revises: 0223afc14044
Expand Down
2 changes: 1 addition & 1 deletion submit-api/migrations/versions/8e112bda0a34_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""empty message
"""Add unique constraint to account proponent_id
Revision ID: 8e112bda0a34
Revises: 97de805275ec
Expand Down
2 changes: 1 addition & 1 deletion submit-api/migrations/versions/97de805275ec_.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""empty message
"""Add ACCOUNT_PRIMARY_ADMIN role
Revision ID: 97de805275ec
Revises: 6dfc3501adbb
Expand Down
43 changes: 43 additions & 0 deletions submit-api/migrations/versions/a4785881834c_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Add projects table
Revision ID: a4785881834c
Revises: 5a6eda61c0c4
Create Date: 2024-08-19 17:45:56.220026
"""
import sqlalchemy as sa
from alembic import op


# revision identifiers, used by Alembic.
revision = 'a4785881834c'
down_revision = '5a6eda61c0c4'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('projects',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('proponent_id', sa.String(), nullable=False),
sa.Column('proponent_name', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('proponent_id')
)
with op.batch_alter_table('account_projects', schema=None) as batch_op:
batch_op.create_foreign_key(None, 'projects', ['project_id'], ['id'])
batch_op.drop_column('name')

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('account_projects', schema=None) as batch_op:
batch_op.add_column(sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=False))
batch_op.drop_constraint(None, type_='foreignkey')

op.drop_table('projects')
# ### end Alembic commands ###
42 changes: 42 additions & 0 deletions submit-api/migrations/versions/b79603b76ea0_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Change proponent_id column type to integer
Revision ID: b79603b76ea0
Revises: a4785881834c
Create Date: 2024-08-20 15:17:44.896108
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'b79603b76ea0'
down_revision = 'a4785881834c'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('accounts', schema=None) as batch_op:
batch_op.alter_column('proponent_id',
existing_type=sa.VARCHAR(),
type_=sa.Integer(),
existing_nullable=False,
postgresql_using='proponent_id::integer')

with op.batch_alter_table('projects', schema=None) as batch_op:
batch_op.alter_column('proponent_id',
existing_type=sa.VARCHAR(),
type_=sa.Integer(),
existing_nullable=False,
postgresql_using='proponent_id::integer')

# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass

# ### end Alembic commands ###
1 change: 1 addition & 0 deletions submit-api/src/submit_api/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@
from .account_user import AccountUser
from .base_model import BaseModel
from .db import db, ma, migrate
from .project import Project
from .project_team import ProjectTeam
from .role import Role
2 changes: 1 addition & 1 deletion submit-api/src/submit_api/models/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Account(BaseModel):
__tablename__ = 'accounts'

id = Column(db.Integer, primary_key=True, autoincrement=True)
proponent_id = Column(db.String(), nullable=False, unique=True)
proponent_id = Column(db.Integer(), nullable=False, unique=True)

@classmethod
def get_by_proponent_id(cls, proponent_id) -> Account:
Expand Down
3 changes: 1 addition & 2 deletions submit-api/src/submit_api/models/account_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ class AccountProject(BaseModel):

id = Column(db.Integer, primary_key=True, autoincrement=True)
account_id = Column(db.Integer, ForeignKey('accounts.id'), nullable=False)
project_id = Column(db.Integer, nullable=False)
name = Column(db.String(), nullable=False)
project_id = Column(db.Integer, ForeignKey('projects.id'), nullable=False)

@classmethod
def add_projects_bulk(cls, projects):
Expand Down
1 change: 1 addition & 0 deletions submit-api/src/submit_api/models/account_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class AccountUser(BaseModel):
work_email_address = Column(db.String(100), nullable=False)
work_contact_number = Column(db.String(50), nullable=False)
auth_guid = Column(db.String(), nullable=False, unique=True)
account = db.relationship('Account', foreign_keys=[account_id], lazy='joined')

__table_args__ = (
Index('ix_account_users_auth_guid', 'auth_guid', unique=True),
Expand Down
62 changes: 62 additions & 0 deletions submit-api/src/submit_api/models/project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Account Project model class.
Manages the account project
"""
from __future__ import annotations

from sqlalchemy import Column, event
from sqlalchemy.exc import ArgumentError, IntegrityError

from submit_api.exceptions import PermissionDeniedError

from .db import db


class Project(db.Model):
"""Definition of the Project entity."""

__tablename__ = 'projects'

id = Column(db.Integer, primary_key=True, autoincrement=True)
name = Column(db.String(), nullable=False)
proponent_id = Column(db.Integer(), nullable=False, unique=True)
proponent_name = Column(db.String(), nullable=False)

def __init__(self, **kwargs):
"""Initialize the Project entity."""
raise ArgumentError("Project is read-only, cannot create new instances.")

@classmethod
def get_all_projects_in_ids(cls, project_ids):
"""Get all projects in the given project ids."""
return cls.query.filter(cls.id.in_(project_ids)).all()


@event.listens_for(Project, 'before_insert')
def before_insert():
"""Raise an error when trying to insert into the Project table."""
raise IntegrityError(
"Insertions are not allowed on this table",
params=None,
orig=PermissionDeniedError('Insertions are not allowed on this table')
)


@event.listens_for(Project, 'before_update')
def before_update():
"""Raise an error when trying to update the Project table."""
raise IntegrityError(
"Updates are not allowed on this table",
params=None,
orig=PermissionDeniedError('Updates are not allowed on this table')
)


@event.listens_for(Project, 'before_delete')
def before_delete():
"""Raise an error when trying to delete from the Project table."""
raise IntegrityError(
"Deletions are not allowed on this table",
params=None,
orig=PermissionDeniedError('Deletions are not allowed on this table')
)
3 changes: 2 additions & 1 deletion submit-api/src/submit_api/models/queries/account_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model to handle all complex operations related to User."""
from submit_api.models import AccountUser, db
from submit_api.models import AccountUser, db, Account


# pylint: disable=too-few-public-methods
Expand All @@ -24,5 +24,6 @@ def get_by_guid(cls, guid: str):
"""Find user by guid"""
result = (db.session.query(AccountUser)
.filter(AccountUser.auth_guid == guid)
.join(Account)
.first())
return result
36 changes: 36 additions & 0 deletions submit-api/src/submit_api/models/queries/project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Copyright © 2024 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model to handle all complex operations related to User."""
from submit_api.models import db, AccountProject, Project


# pylint: disable=too-few-public-methods
class ProjectQueries:
"""Query module for complex projects queries"""

@classmethod
def get_projects_by_account_id(cls, account_id: int):
"""Find projects by account_id"""
result = (db.session.query(AccountProject)
.filter(AccountProject.account_id == account_id)
.join(Project)
.first())
return result

@classmethod
def get_projects_by_proponent_id(cls, proponent_id: int):
"""Find projects by proponent_id"""
result = (db.session.query(Project)
.filter(Project.proponent_id == proponent_id))
return result
2 changes: 1 addition & 1 deletion submit-api/src/submit_api/resources/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def post():


@cors_preflight("GET, OPTIONS")
@API.route("/proponent/<proponent_id>", methods=["GET", "OPTIONS"])
@API.route("/proponent/<int:proponent_id>", methods=["GET", "OPTIONS"])
@API.doc(params={"proponent_id": "The account identifier"})
class User(Resource):
"""Resource for managing a single account"""
Expand Down
38 changes: 33 additions & 5 deletions submit-api/src/submit_api/resources/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,46 @@


@cors_preflight("GET, OPTIONS, POST")
@API.route("", methods=["POST", "GET", "OPTIONS"])
class Projects(Resource):
@API.route("/accounts/<int:account_id>", methods=["POST", "GET", "OPTIONS"])
class ProjectsByAccount(Resource):
"""Resource for managing projects."""

@staticmethod
@ApiHelper.swagger_decorators(API, endpoint_description="Get projects by account id")
@API.expect(project_add_list)
@API.response(code=HTTPStatus.CREATED, model=project_list_model, description="Get projects")
@API.response(HTTPStatus.BAD_REQUEST, "Bad Request")
@cors.crossdomain(origin="*")
def get(account_id):
"""Get projects by account id."""
projects = ProjectService.get_projects_by_account_id(account_id)
return ProjectSchema(many=True).dump(projects), HTTPStatus.OK

@staticmethod
@ApiHelper.swagger_decorators(API, endpoint_description="Add projects in bulk")
@API.expect(project_add_list)
@API.response(code=HTTPStatus.CREATED, model=project_list_model, description="Added projects")
@API.response(HTTPStatus.BAD_REQUEST, "Bad Request")
@cors.crossdomain(origin="*")
def post():
def post(account_id):
"""Add projects in bulk."""
projects_data = AddProjectSchema(many=True).load(API.payload)
added_projects = ProjectService.bulk_add_projects(projects_data)
projects_data = AddProjectSchema().load(API.payload)
added_projects = ProjectService.bulk_add_projects(account_id, projects_data.get("project_ids"))
return ProjectSchema(many=True).dump(added_projects), HTTPStatus.CREATED


@cors_preflight("GET, OPTIONS, POST")
@API.route("/proponents/<int:proponent_id>", methods=["POST", "GET", "OPTIONS"])
class Projects(Resource):
"""Resource for managing projects."""

@staticmethod
@ApiHelper.swagger_decorators(API, endpoint_description="Get projects by proponent id")
@API.expect(project_add_list)
@API.response(code=HTTPStatus.CREATED, model=project_list_model, description="Get projects")
@API.response(HTTPStatus.BAD_REQUEST, "Bad Request")
@cors.crossdomain(origin="*")
def get(proponent_id):
"""Get projects by proponent id."""
projects = ProjectService.get_projects_by_proponent_id(proponent_id)
return ProjectSchema(many=True).dump(projects), HTTPStatus.OK
4 changes: 2 additions & 2 deletions submit-api/src/submit_api/schemas/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Meta: # pylint: disable=too-few-public-methods
unknown = EXCLUDE

id = fields.Int(data_key="id")
proponent_id = fields.Str(data_key="proponent_id")
proponent_id = fields.Int(data_key="proponent_id")


class AccountCreateSchema(Schema):
Expand All @@ -31,5 +31,5 @@ class Meta: # pylint: disable=too-few-public-methods
work_email_address = fields.Str(data_key="work_email_address")
work_contact_number = fields.Str(data_key="work_contact_number")
position = fields.Str(data_key="position")
proponent_id = fields.Str(data_key="proponent_id")
proponent_id = fields.Int(data_key="proponent_id")
auth_guid = fields.Str(data_key="auth_guid")
8 changes: 3 additions & 5 deletions submit-api/src/submit_api/schemas/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class Meta: # pylint: disable=too-few-public-methods

id = fields.Int(data_key="id")
name = fields.Str(data_key="name")
project_id = fields.Str(data_key="project_id")
account_id = fields.Str(data_key="account_id")
proponent_id = fields.Int(data_key="proponent_id")
proponent_name = fields.Str(data_key="proponent_name")


class AddProjectSchema(Schema):
Expand All @@ -28,6 +28,4 @@ class Meta: # pylint: disable=too-few-public-methods

unknown = EXCLUDE

name = fields.Str(data_key="name")
project_id = fields.Int(data_key="project_id")
account_id = fields.Int(data_key="account_id")
project_ids = fields.List(fields.Int(), data_key="project_ids")
3 changes: 3 additions & 0 deletions submit-api/src/submit_api/schemas/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

from marshmallow import EXCLUDE, Schema, fields

from submit_api.schemas.account import AccountSchema


class UserSchema(Schema):
"""User schema."""
Expand All @@ -20,3 +22,4 @@ class Meta: # pylint: disable=too-few-public-methods
work_email_address = fields.Str(data_key="email_address")
work_contact_number = fields.Str(data_key="contact_number")
account_id = fields.Int(data_key="account_id")
account = fields.Nested(AccountSchema, data_key="account", dump_only=True)
Loading

0 comments on commit 13e364d

Please sign in to comment.