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

InspectionRequirements - GET By Id, Update #188

Merged
merged 2 commits into from
Jan 7, 2025
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
2 changes: 1 addition & 1 deletion compliance-api/src/compliance_api/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from .position import Position
from .project import Project
from .req_source_document_map import RequirementSourceDocumentMap
from .requirement_source import RequirementSource
from .requirement_source import RequirementSource, RequirementSourceEnum
from .staff_user import StaffUser
from .topic import Topic
from .unapproved_project import UnapprovedProject
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from ..base_model import BaseModelVersioned
from ..base_model import BaseModelVersioned, db


class InspectionReqDetailDocument(BaseModelVersioned):
Expand Down Expand Up @@ -52,7 +52,7 @@ class InspectionReqDetailDocument(BaseModelVersioned):
"InspectionReqSourceDetail",
back_populates="documents",
lazy="select",
uselist=False
uselist=False,
)
document_type = relationship(
"DocumentType", foreign_keys=[document_type_id], lazy="select"
Expand All @@ -68,3 +68,28 @@ def create_doc_detail(cls, doc_detail_obj, session=None):
else:
doc_detail.save()
return doc_detail

@classmethod
def update_doc_detail(cls, doc_detail_id, doc_detail_data, session=None):
"""Update requirement doc detail."""
query = cls.query.filter_by(id=doc_detail_id)
doc_detail: InspectionReqDetailDocument = query.first()
if not doc_detail or doc_detail.is_deleted:
return None
query.update(doc_detail_data)
if session:
session.flush()
else:
db.session.commit()
return doc_detail

@classmethod
def delete_req_doc_details_by_ids(cls, req_doc_detail_ids, session=None):
"""Delete the requirement doc details by req_doc_detail_ids."""
cls.query.filter(InspectionReqDetailDocument.id.in_(req_doc_detail_ids)).update(
{cls.is_deleted: True, cls.is_active: False}
)
if session:
session.flush()
else:
db.session.commit()
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from ..base_model import BaseModelVersioned
from ..base_model import BaseModelVersioned, db


class InspectionReqSourceDetail(BaseModelVersioned):
Expand Down Expand Up @@ -60,7 +60,7 @@ class InspectionReqSourceDetail(BaseModelVersioned):
"InspectionRequirement",
back_populates="requirement_source_details",
lazy="select",
uselist=False
uselist=False,
)
requirement_source = relationship(
"RequirementSource", foreign_keys=[requirement_source_id], lazy="joined"
Expand All @@ -81,3 +81,37 @@ def create_source_detail(cls, source_detail_obj, session=None):
else:
source_detail.save()
return source_detail

@classmethod
def update_requirement_source_detail(
cls, req_detail_id, source_detail_data, session=None
):
"""Update requirement detail."""
query = cls.query.filter_by(id=req_detail_id)
source_detail: InspectionReqSourceDetail = query.first()
if not source_detail or source_detail.is_deleted:
return None
query.update(source_detail_data)
if session:
session.flush()
else:
db.session.commit()
return source_detail

@classmethod
def get_all_by_requirement_id(cls, requirement_id):
"""Get all requirement detail entries by requirement_id."""
return cls.query.filter_by(
requirement_id=requirement_id, is_active=True, is_deleted=False
).all()

@classmethod
def delete_req_details_by_ids(cls, req_detail_ids, session=None):
"""Delete the requirement details by req_detail_ids."""
cls.query.filter(InspectionReqSourceDetail.id.in_(req_detail_ids)).update(
{cls.is_deleted: True, cls.is_active: False}
)
if session:
session.flush()
else:
db.session.commit()
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class InspectionRequirement(BaseModelVersioned):
requirement_source_details = relationship(
"InspectionReqSourceDetail",
back_populates="inspection_requirement",
lazy="select"
lazy="select",
)

@classmethod
Expand All @@ -79,8 +79,22 @@ def create_requirement(cls, requirement_obj, session=None):
@classmethod
def get_by_inspection_id(cls, inspection_id):
"""Get requirements by inspection id."""
return db.session.query(InspectionRequirement).filter(
InspectionRequirement.inspection_id == inspection_id,
InspectionRequirement.is_deleted.is_(False),
InspectionRequirement.is_active.is_(True)
).all()
return (
db.session.query(InspectionRequirement)
.filter_by(inspection_id=inspection_id, is_deleted=False, is_active=True)
.all()
)

@classmethod
def update_requirement(cls, requirement_id, requirement_data, session=None):
"""Update inspection requirement."""
query = cls.query.filter_by(id=requirement_id)
requirement: InspectionRequirement = query.first()
if not requirement or requirement.is_deleted:
return None
query.update(requirement_data)
if session:
session.flush()
else:
db.session.commit()
return requirement
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from flask_restx import Namespace, Resource

from compliance_api.auth import auth
from compliance_api.schemas.inspection_requirement import InspectionRequirementCreateSchema, InspectionRequirementSchema
from compliance_api.schemas.inspection_requirement import (
InspectionRequirementCreateSchema, InspectionRequirementSchema, InspectionRequirementUpdateSchema)
from compliance_api.services import InspectionRequirementService
from compliance_api.utils.util import cors_preflight

Expand All @@ -21,16 +22,24 @@
API, InspectionRequirementSchema(), "InspectionRequirementList"
)

inspection_requirement_update_model = ApiHelper.convert_ma_schema_to_restx_model(
API, InspectionRequirementUpdateSchema(), "InspectionRequirementUpdate"
)


@cors_preflight("GET, OPTIONS, POST")
@API.route("", methods=["POST", "GET", "OPTIONS"])
class InspectionRequirements(Resource):
"""InspectionRequirements."""

@staticmethod
@ApiHelper.swagger_decorators(API, endpoint_description="Get all requirements by inspection")
@ApiHelper.swagger_decorators(
API, endpoint_description="Get all requirements by inspection"
)
@auth.require
@API.response(code=200, description="Success", model=[inspection_requirement_list_model])
@API.response(
code=200, description="Success", model=[inspection_requirement_list_model]
)
def get(inspection_id):
"""Get requirements by inspection id."""
requirements = InspectionRequirementService.get_all(inspection_id)
Expand All @@ -56,3 +65,39 @@ def post(inspection_id):
InspectionRequirementSchema().dump(created_requirement),
HTTPStatus.CREATED,
)


@cors_preflight("GET, PATCH, DELETE, OPTIONS")
@API.route("/<int:requirement_id>", methods=["GET", "PATCH", "OPTIONS", "DELETE"])
class InspectionRequirement(Resource):
"""InspectionRequirement resource."""

@staticmethod
@API.response(
code=200, description="Success", model=[inspection_requirement_list_model]
)
@ApiHelper.swagger_decorators(
API, endpoint_description="Fetch inspection requirement by id"
)
@auth.require
def get(requirement_id):
"""Fetch all inspection requirement."""
requirement = InspectionRequirementService.get_by_id(requirement_id)
return InspectionRequirementSchema().dump(requirement), HTTPStatus.OK

@staticmethod
@API.response(
code=200, description="Sucess", model=[inspection_requirement_list_model]
)
@API.expect(inspection_requirement_update_model)
@ApiHelper.swagger_decorators(
API, endpoint_description="Update inspection requirement"
)
@auth.require
def patch(inspection_id, requirement_id):
"""Update inspection inspection requirement."""
requirement_data = InspectionRequirementUpdateSchema().load(API.payload)
updated_requirement = InspectionRequirementService.update(
inspection_id, requirement_id, requirement_data
)
return InspectionRequirementSchema().dump(updated_requirement), HTTPStatus.OK
3 changes: 2 additions & 1 deletion compliance-api/src/compliance_api/schemas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
from .inspection import (
InspectionAttendanceSchema, InspectionCreateSchema, InspectionOfficerSchema, InspectionSchema,
InspectionStatusSchema, InspectionUpdateSchema)
from .inspection_requirement import InspectionRequirementCreateSchema, InspectionRequirementSchema
from .inspection_requirement import (
InspectionRequirementCreateSchema, InspectionRequirementSchema, InspectionRequirementUpdateSchema)
from .paginate import PaginationParameterSchema
from .project import ProjectSchema
from .staff_user import StaffUserCreateSchema, StaffUserSchema, StaffUserUpdateSchema
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Inspection requirement Schema Schema."""
from marshmallow import EXCLUDE, fields
from marshmallow import EXCLUDE, ValidationError, fields, validates_schema

from compliance_api.models import InspectionReqDetailDocument, InspectionReqSourceDetail, InspectionRequirement
from compliance_api.models.requirement_source import RequirementSourceEnum

from .base_schema import AutoSchemaBase, BaseSchema

Expand All @@ -37,6 +38,16 @@ class InspectionReqDetailDocCreateSchema(BaseSchema):
)


class InspectionReqDetailDocUpdateSchema(InspectionReqDetailDocCreateSchema):
"""InspectionReqDetailDocUpdateSchema."""

id = fields.Int(
metadata={
"description": "The unique identifier of the requirement detail document"
}
)


class InspectionReqSourceDetailCreateSchema(BaseSchema):
"""InspectionReqSourceDetailSchema."""

Expand Down Expand Up @@ -69,6 +80,69 @@ class InspectionReqSourceDetailCreateSchema(BaseSchema):
)
documents = fields.List(fields.Nested(InspectionReqDetailDocCreateSchema))

@validates_schema
def validate_section_number(
self, data, **kwargs
): # pylint: disable=no-self-use, unused-argument
"""Ensure the correct requirement is selected for the section number."""
section_number = data.get("section_number", [])
requirement_source_id = data.get("requirement_source_id", None)
if section_number and RequirementSourceEnum(requirement_source_id) not in [
RequirementSourceEnum.ACT_2002,
RequirementSourceEnum.ACT_2018,
RequirementSourceEnum.COMPLIANCE_AGREEMENT,
RequirementSourceEnum.CERTIFIED_PROJECT_DESCRIPTION,
RequirementSourceEnum.NOT_EA_ACT,
]:
raise ValidationError(
"Invalid requirement source for the given section number",
field_name="section_number",
)

@validates_schema
def validate_amendment_number(
self, data, **kwargs
): # pylint: disable=no-self-use, unused-argument
"""Ensure the correct requirement is selected for the amendment number."""
amendment_number = data.get("amendment_number", [])
requirement_source_id = data.get("requirement_source_id", None)
if (
amendment_number
and RequirementSourceEnum(requirement_source_id)
!= RequirementSourceEnum.EAC_AMENDMENT
):
raise ValidationError(
"Invalid requirement source for the given amendment number",
field_name="amendment_number",
)

@validates_schema
def validate_condition_number(
self, data, **kwargs
): # pylint: disable=no-self-use, unused-argument
"""Ensure the correct requirement is selected for the condition number."""
condition_number = data.get("condition_number", [])
requirement_source_id = data.get("requirement_source_id", None)
if condition_number and RequirementSourceEnum(requirement_source_id) not in [
RequirementSourceEnum.SCHEDULE_B,
RequirementSourceEnum.EAC_CERTIFICATE,
]:
raise ValidationError(
"Invalid requirement source for the given condition number",
field_name="condition_number",
)


class InspectionReqSourceDetailUpdateSchema(InspectionReqSourceDetailCreateSchema):
"""InspectionRequirementUpdateSchema."""

id = fields.Int(
metadata={
"description": "The unique identifier of the requirement source detail."
}
)
documents = fields.List(fields.Nested(InspectionReqDetailDocUpdateSchema))


class InspectionRequirementCreateSchema(BaseSchema):
"""InspectionRequirementCreateSchema."""
Expand Down Expand Up @@ -100,6 +174,17 @@ class InspectionRequirementCreateSchema(BaseSchema):
)


class InspectionRequirementUpdateSchema(InspectionRequirementCreateSchema):
"""InspectionRequirementUpdateSchema."""

id = fields.Int(
metadata={"description": "The unique identifier of the requirement"}
)
requirement_source_details = fields.List(
fields.Nested(InspectionReqSourceDetailUpdateSchema)
)


class InspectionReqDetailDocSchema(
AutoSchemaBase
): # pylint: disable=too-many-ancestors
Expand Down
Loading
Loading