new api service and logic implemented
This commit is contained in:
0
Events/AllEvents/events/__init__.py
Normal file
0
Events/AllEvents/events/__init__.py
Normal file
9
Events/AllEvents/events/account/__init__.py
Normal file
9
Events/AllEvents/events/account/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
Account records package initialization.
|
||||
"""
|
||||
|
||||
from .endpoints import ACCOUNT_RECORDS_CONFIG
|
||||
|
||||
__all__ = [
|
||||
"ACCOUNT_RECORDS_CONFIG",
|
||||
]
|
||||
351
Events/AllEvents/events/account/account_records.py
Normal file
351
Events/AllEvents/events/account/account_records.py
Normal file
@@ -0,0 +1,351 @@
|
||||
"""
|
||||
Account records service implementation.
|
||||
"""
|
||||
|
||||
from typing import Union
|
||||
from pydantic import Field
|
||||
|
||||
from ApiEvents.abstract_class import MethodToEvent, endpoint_wrapper
|
||||
from ApiEvents.base_request_model import DictRequestModel
|
||||
from ApiValidations.Custom.token_objects import (
|
||||
OccupantTokenObject,
|
||||
EmployeeTokenObject,
|
||||
)
|
||||
from ApiLibrary import system_arrow
|
||||
from ApiValidations.Request.account_records import (
|
||||
InsertAccountRecord,
|
||||
UpdateAccountRecord,
|
||||
)
|
||||
from ApiValidations.Request.base_validations import ListOptions
|
||||
from Schemas import (
|
||||
BuildLivingSpace,
|
||||
AccountRecords,
|
||||
BuildIbans,
|
||||
BuildDecisionBookPayments,
|
||||
ApiEnumDropdown,
|
||||
)
|
||||
from Services.PostgresDb.Models.alchemy_response import (
|
||||
AlchemyJsonResponse,
|
||||
)
|
||||
from ApiValidations.Response import AccountRecordResponse
|
||||
from .models import (
|
||||
InsertAccountRecordRequestModel,
|
||||
UpdateAccountRecordRequestModel,
|
||||
ListOptionsRequestModel,
|
||||
)
|
||||
|
||||
|
||||
class AccountListEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "SELECT"
|
||||
event_description = ""
|
||||
event_category = ""
|
||||
|
||||
__event_keys__ = {
|
||||
"7192c2aa-5352-4e36-98b3-dafb7d036a3d": "account_records_list",
|
||||
"208e6273-17ef-44f0-814a-8098f816b63a": "account_records_list_flt_res",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"7192c2aa-5352-4e36-98b3-dafb7d036a3d": (
|
||||
AccountRecordResponse,
|
||||
[AccountRecords.__language_model__],
|
||||
),
|
||||
"208e6273-17ef-44f0-814a-8098f816b63a": (
|
||||
AccountRecordResponse,
|
||||
[AccountRecords.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def account_records_list(
|
||||
cls,
|
||||
list_options: ListOptionsRequestModel,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
db_session = AccountRecords.new_session()
|
||||
if isinstance(token_dict, OccupantTokenObject):
|
||||
AccountRecords.pre_query = AccountRecords.filter_all(
|
||||
AccountRecords.company_id
|
||||
== token_dict.selected_occupant.responsible_company_id,
|
||||
db=db_session,
|
||||
).query
|
||||
elif isinstance(token_dict, EmployeeTokenObject):
|
||||
AccountRecords.pre_query = AccountRecords.filter_all(
|
||||
AccountRecords.company_id == token_dict.selected_company.company_id,
|
||||
db=db_session,
|
||||
).query
|
||||
AccountRecords.filter_attr = list_options
|
||||
records = AccountRecords.filter_all(db=db_session)
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Account records listed successfully",
|
||||
result=records,
|
||||
cls_object=AccountRecords,
|
||||
filter_attributes=list_options,
|
||||
response_model=AccountRecordResponse,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def account_records_list_flt_res(
|
||||
cls,
|
||||
list_options: ListOptionsRequestModel,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
db_session = AccountRecords.new_session()
|
||||
if not isinstance(token_dict, OccupantTokenObject):
|
||||
raise AccountRecords.raise_http_exception(
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
error_case="UNAUTHORIZED",
|
||||
message="Only Occupant can see this data",
|
||||
data={},
|
||||
)
|
||||
|
||||
return_list = []
|
||||
living_space: BuildLivingSpace = BuildLivingSpace.filter_by_one(
|
||||
id=token_dict.selected_occupant.living_space_id
|
||||
).data
|
||||
if not living_space:
|
||||
raise AccountRecords.raise_http_exception(
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
error_case="UNAUTHORIZED",
|
||||
message="Living space not found",
|
||||
data={},
|
||||
)
|
||||
|
||||
if not list_options:
|
||||
list_options = ListOptions()
|
||||
|
||||
main_filters = [
|
||||
AccountRecords.living_space_id
|
||||
== token_dict.selected_occupant.living_space_id,
|
||||
BuildDecisionBookPayments.process_date
|
||||
>= str(system_arrow.now().shift(months=-3).date()),
|
||||
BuildDecisionBookPayments.process_date
|
||||
< str(system_arrow.find_last_day_of_month(living_space.expiry_ends)),
|
||||
BuildDecisionBookPayments.process_date
|
||||
>= str(system_arrow.get(living_space.expiry_starts)),
|
||||
BuildDecisionBookPayments.is_confirmed == True,
|
||||
AccountRecords.active == True,
|
||||
]
|
||||
order_type = "desc"
|
||||
if list_options.order_type:
|
||||
order_type = "asc" if list_options.order_type[0] == "a" else "desc"
|
||||
|
||||
order_by_list = BuildDecisionBookPayments.process_date.desc()
|
||||
if list_options.order_field:
|
||||
if list_options.order_field == "process_date":
|
||||
order_by_list = (
|
||||
BuildDecisionBookPayments.process_date.asc()
|
||||
if order_type == "asc"
|
||||
else BuildDecisionBookPayments.process_date.desc()
|
||||
)
|
||||
if list_options.order_field == "bank_date":
|
||||
order_by_list = (
|
||||
AccountRecords.bank_date.desc()
|
||||
if order_type == "asc"
|
||||
else AccountRecords.bank_date.asc()
|
||||
)
|
||||
if list_options.order_field == "currency_value":
|
||||
order_by_list = (
|
||||
AccountRecords.currency_value.desc()
|
||||
if order_type == "asc"
|
||||
else AccountRecords.currency_value.asc()
|
||||
)
|
||||
if list_options.order_field == "process_comment":
|
||||
order_by_list = (
|
||||
AccountRecords.process_comment.desc()
|
||||
if order_type == "asc"
|
||||
else AccountRecords.process_comment.asc()
|
||||
)
|
||||
if list_options.order_field == "payment_amount":
|
||||
order_by_list = (
|
||||
BuildDecisionBookPayments.payment_amount.desc()
|
||||
if order_type == "asc"
|
||||
else BuildDecisionBookPayments.payment_amount.asc()
|
||||
)
|
||||
|
||||
if list_options.query:
|
||||
for key, value in list_options.query.items():
|
||||
if key == "process_date":
|
||||
main_filters.append(BuildDecisionBookPayments.process_date == value)
|
||||
if key == "bank_date":
|
||||
main_filters.append(AccountRecords.bank_date == value)
|
||||
if key == "currency":
|
||||
main_filters.append(BuildDecisionBookPayments.currency == value)
|
||||
if key == "currency_value":
|
||||
main_filters.append(AccountRecords.currency_value == value)
|
||||
if key == "process_comment":
|
||||
main_filters.append(AccountRecords.process_comment == value)
|
||||
if key == "payment_amount":
|
||||
main_filters.append(
|
||||
BuildDecisionBookPayments.payment_amount == value
|
||||
)
|
||||
|
||||
query = (
|
||||
AccountRecords.session.query(
|
||||
BuildDecisionBookPayments.process_date,
|
||||
BuildDecisionBookPayments.payment_amount,
|
||||
BuildDecisionBookPayments.currency,
|
||||
AccountRecords.bank_date,
|
||||
AccountRecords.currency_value,
|
||||
AccountRecords.process_comment,
|
||||
BuildDecisionBookPayments.uu_id,
|
||||
)
|
||||
.join(
|
||||
AccountRecords,
|
||||
AccountRecords.id == BuildDecisionBookPayments.account_records_id,
|
||||
)
|
||||
.filter(*main_filters)
|
||||
).order_by(order_by_list)
|
||||
|
||||
query.limit(list_options.size or 5).offset(
|
||||
(list_options.page or 1 - 1) * list_options.size or 5
|
||||
)
|
||||
for list_of_values in query.all() or []:
|
||||
return_list.append(
|
||||
{
|
||||
"process_date": list_of_values[0],
|
||||
"payment_amount": list_of_values[1],
|
||||
"currency": list_of_values[2],
|
||||
"bank_date": list_of_values[3],
|
||||
"currency_value": list_of_values[4],
|
||||
"process_comment": list_of_values[5],
|
||||
}
|
||||
)
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Account records listed successfully",
|
||||
result=return_list,
|
||||
cls_object=AccountRecords,
|
||||
filter_attributes=list_options,
|
||||
response_model=AccountRecordResponse,
|
||||
)
|
||||
|
||||
|
||||
class AccountCreateEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "CREATE"
|
||||
event_description = ""
|
||||
event_category = ""
|
||||
|
||||
__event_keys__ = {
|
||||
"31f4f32f-0cd4-4995-8a6a-f9f56335848a": "account_records_create",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"31f4f32f-0cd4-4995-8a6a-f9f56335848a": (
|
||||
InsertAccountRecord,
|
||||
[AccountRecords.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def account_records_create(
|
||||
cls,
|
||||
data: InsertAccountRecordRequestModel,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
data_dict = data.excluded_dump()
|
||||
if isinstance(token_dict, OccupantTokenObject):
|
||||
db_session = AccountRecords.new_session()
|
||||
build_iban = BuildIbans.filter_one(
|
||||
BuildIbans.iban == data.iban,
|
||||
BuildIbans.build_id == token_dict.selected_occupant.build_id,
|
||||
db=db_session,
|
||||
).data
|
||||
if not build_iban:
|
||||
raise BuildIbans.raise_http_exception(
|
||||
status_code="HTTP_404_NOT_FOUND",
|
||||
error_case="UNAUTHORIZED",
|
||||
message=f"{data.iban} is not found in company related to your organization",
|
||||
data={
|
||||
"iban": data.iban,
|
||||
},
|
||||
)
|
||||
account_record = AccountRecords.find_or_create(**data.excluded_dump())
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Account record created successfully",
|
||||
result=account_record,
|
||||
)
|
||||
elif isinstance(token_dict, EmployeeTokenObject):
|
||||
# Build.pre_query = Build.select_action(
|
||||
# employee_id=token_dict.selected_employee.employee_id,
|
||||
# )
|
||||
# build_ids_list = Build.filter_all(
|
||||
# )
|
||||
# build_iban = BuildIbans.filter_one(
|
||||
# BuildIbans.iban == data.iban,
|
||||
# BuildIbans.build_id.in_([build.id for build in build_ids_list.data]),
|
||||
# ).data
|
||||
# if not build_iban:
|
||||
# BuildIbans.raise_http_exception(
|
||||
# status_code="HTTP_404_NOT_FOUND",
|
||||
# error_case="UNAUTHORIZED",
|
||||
# message=f"{data.iban} is not found in company related to your organization",
|
||||
# data={
|
||||
# "iban": data.iban,
|
||||
# },
|
||||
# )
|
||||
bank_date = system_arrow.get(data.bank_date)
|
||||
data_dict["bank_date_w"] = bank_date.weekday()
|
||||
data_dict["bank_date_m"] = bank_date.month
|
||||
data_dict["bank_date_d"] = bank_date.day
|
||||
data_dict["bank_date_y"] = bank_date.year
|
||||
|
||||
if int(data.currency_value) < 0:
|
||||
debit_type = ApiEnumDropdown.filter_by_one(
|
||||
system=True, enum_class="DebitTypes", key="DT-D"
|
||||
).data
|
||||
data_dict["receive_debit"] = debit_type.id
|
||||
data_dict["receive_debit_uu_id"] = str(debit_type.uu_id)
|
||||
else:
|
||||
debit_type = ApiEnumDropdown.filter_by_one(
|
||||
system=True, enum_class="DebitTypes", key="DT-R"
|
||||
).data
|
||||
data_dict["receive_debit"] = debit_type.id
|
||||
data_dict["receive_debit_uu_id"] = str(debit_type.uu_id)
|
||||
|
||||
account_record = AccountRecords.insert_one(data_dict).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Account record created successfully",
|
||||
result=account_record,
|
||||
)
|
||||
|
||||
|
||||
class AccountUpdateEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "UPDATE"
|
||||
event_description = ""
|
||||
event_category = ""
|
||||
|
||||
__event_keys__ = {
|
||||
"ec98ef2c-bcd0-432d-a8f4-1822a56c33b2": "account_records_update",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"ec98ef2c-bcd0-432d-a8f4-1822a56c33b2": (
|
||||
UpdateAccountRecord,
|
||||
[AccountRecords.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def account_records_update(
|
||||
cls,
|
||||
build_uu_id: str,
|
||||
data: UpdateAccountRecordRequestModel,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
if isinstance(token_dict, OccupantTokenObject):
|
||||
pass
|
||||
elif isinstance(token_dict, EmployeeTokenObject):
|
||||
pass
|
||||
AccountRecords.build_parts_id = token_dict.selected_occupant.build_part_id
|
||||
account_record = AccountRecords.update_one(build_uu_id, data).data
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Account record updated successfully",
|
||||
result=account_record,
|
||||
cls_object=AccountRecords,
|
||||
response_model=UpdateAccountRecord,
|
||||
)
|
||||
131
Events/AllEvents/events/account/endpoints.py
Normal file
131
Events/AllEvents/events/account/endpoints.py
Normal file
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
Account records endpoint configurations.
|
||||
|
||||
"""
|
||||
|
||||
from ApiEvents.abstract_class import (
|
||||
RouteFactoryConfig,
|
||||
EndpointFactoryConfig,
|
||||
endpoint_wrapper,
|
||||
)
|
||||
from ApiEvents.base_request_model import EndpointBaseRequestModel
|
||||
|
||||
from Services.PostgresDb.Models.alchemy_response import DictJsonResponse
|
||||
from fastapi import Request, Path, Body
|
||||
|
||||
|
||||
@endpoint_wrapper("/account/records/list")
|
||||
async def address_list(request: "Request", data: EndpointBaseRequestModel):
|
||||
"""Handle address list endpoint."""
|
||||
auth_dict = address_list.auth
|
||||
code_dict = getattr(address_list, "func_code", {"function_code": None})
|
||||
return {"auth_dict": auth_dict, "code_dict": code_dict, "data": data}
|
||||
|
||||
|
||||
@endpoint_wrapper("/account/records/create")
|
||||
async def address_create(request: "Request", data: EndpointBaseRequestModel):
|
||||
"""Handle address creation endpoint."""
|
||||
return {
|
||||
"data": data,
|
||||
"request": str(request.headers),
|
||||
"request_url": str(request.url),
|
||||
"request_base_url": str(request.base_url),
|
||||
}
|
||||
|
||||
|
||||
@endpoint_wrapper("/account/records/search")
|
||||
async def address_search(request: "Request", data: EndpointBaseRequestModel):
|
||||
"""Handle address search endpoint."""
|
||||
auth_dict = address_search.auth
|
||||
code_dict = getattr(address_search, "func_code", {"function_code": None})
|
||||
return {"auth_dict": auth_dict, "code_dict": code_dict, "data": data}
|
||||
|
||||
|
||||
@endpoint_wrapper("/account/records/{address_uu_id}")
|
||||
async def address_update(
|
||||
request: Request,
|
||||
address_uu_id: str = Path(..., description="UUID of the address to update"),
|
||||
request_data: EndpointBaseRequestModel = Body(..., description="Request body"),
|
||||
):
|
||||
"""
|
||||
Handle address update endpoint.
|
||||
|
||||
Args:
|
||||
request: FastAPI request object
|
||||
address_uu_id: UUID of the address to update
|
||||
request_data: Request body containing updated address data
|
||||
|
||||
Returns:
|
||||
DictJsonResponse: Response containing updated address info
|
||||
"""
|
||||
auth_dict = address_update.auth
|
||||
return DictJsonResponse(
|
||||
data={
|
||||
"address_uu_id": address_uu_id,
|
||||
"data": request_data.root,
|
||||
"request": str(request.headers),
|
||||
"request_url": str(request.url),
|
||||
"request_base_url": str(request.base_url),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
prefix = "/account/records"
|
||||
|
||||
# Account Records Router Configuration
|
||||
ACCOUNT_RECORDS_CONFIG = RouteFactoryConfig(
|
||||
name="account_records",
|
||||
prefix=prefix,
|
||||
tags=["Account Records"],
|
||||
include_in_schema=True,
|
||||
endpoints=[
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/list",
|
||||
url_of_endpoint=f"{prefix}/list",
|
||||
endpoint="/list",
|
||||
method="POST",
|
||||
summary="List Active/Delete/Confirm Address",
|
||||
description="List Active/Delete/Confirm Address",
|
||||
is_auth_required=True,
|
||||
is_event_required=True,
|
||||
endpoint_function=address_list,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/create",
|
||||
url_of_endpoint=f"{prefix}/create",
|
||||
endpoint="/create",
|
||||
method="POST",
|
||||
summary="Create Address with given auth levels",
|
||||
description="Create Address with given auth levels",
|
||||
is_auth_required=False,
|
||||
is_event_required=False,
|
||||
endpoint_function=address_create,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/search",
|
||||
url_of_endpoint=f"{prefix}/search",
|
||||
endpoint="/search",
|
||||
method="POST",
|
||||
summary="Search Address with given auth levels",
|
||||
description="Search Address with given auth levels",
|
||||
is_auth_required=True,
|
||||
is_event_required=True,
|
||||
endpoint_function=address_search,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/{address_uu_id}",
|
||||
url_of_endpoint="{prefix}/" + "{address_uu_id}",
|
||||
endpoint="/{address_uu_id}",
|
||||
method="PUT",
|
||||
summary="Update Address with given auth levels",
|
||||
description="Update Address with given auth levels",
|
||||
is_auth_required=True,
|
||||
is_event_required=True,
|
||||
endpoint_function=address_update,
|
||||
),
|
||||
],
|
||||
).as_dict()
|
||||
54
Events/AllEvents/events/account/models.py
Normal file
54
Events/AllEvents/events/account/models.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""
|
||||
Account records request and response models.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any
|
||||
from pydantic import BaseModel, Field, RootModel
|
||||
from ApiEvents.base_request_model import BaseRequestModel
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ApiValidations.Request import (
|
||||
InsertAccountRecord,
|
||||
UpdateAccountRecord,
|
||||
ListOptions,
|
||||
)
|
||||
|
||||
|
||||
class AddressUpdateRequest(RootModel[Dict[str, Any]]):
|
||||
"""Request model for address update."""
|
||||
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"street": "123 Main St",
|
||||
"city": "Example City",
|
||||
"country": "Example Country",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class AddressUpdateResponse(BaseModel):
|
||||
"""Response model for address update."""
|
||||
|
||||
address_uu_id: str = Field(..., description="UUID of the updated address")
|
||||
data: Dict[str, Any] = Field(..., description="Updated address data")
|
||||
function_code: str = Field(..., description="Function code for the endpoint")
|
||||
|
||||
|
||||
class InsertAccountRecordRequestModel(BaseRequestModel["InsertAccountRecord"]):
|
||||
"""Request model for inserting account records."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class UpdateAccountRecordRequestModel(BaseRequestModel["UpdateAccountRecord"]):
|
||||
"""Request model for updating account records."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ListOptionsRequestModel(BaseRequestModel["ListOptions"]):
|
||||
"""Request model for list options."""
|
||||
|
||||
pass
|
||||
351
Events/AllEvents/events/address/address.py
Normal file
351
Events/AllEvents/events/address/address.py
Normal file
@@ -0,0 +1,351 @@
|
||||
"""
|
||||
request models.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any, List, Optional, TypedDict, Union
|
||||
from pydantic import BaseModel, Field, model_validator, RootModel, ConfigDict
|
||||
from ApiEvents.abstract_class import MethodToEvent
|
||||
from ApiEvents.base_request_model import BaseRequestModel, DictRequestModel
|
||||
from ApiValidations.Custom.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
from ApiValidations.Request.address import SearchAddress, UpdateAddress
|
||||
from ApiValidations.Request.base_validations import ListOptions
|
||||
from ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
|
||||
from Schemas.identity.identity import (
|
||||
AddressPostcode,
|
||||
AddressStreet,
|
||||
Addresses,
|
||||
RelationshipEmployee2PostCode,
|
||||
)
|
||||
from ApiValidations.Request import (
|
||||
InsertAddress,
|
||||
)
|
||||
from ApiValidations.Response import (
|
||||
ListAddressResponse,
|
||||
)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
class AddressListEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "SELECT"
|
||||
event_description = "List Address records"
|
||||
event_category = "Address"
|
||||
|
||||
__event_keys__ = {
|
||||
"9c251d7d-da70-4d63-a72c-e69c26270442": "address_list_super_user",
|
||||
"52afe375-dd95-4f4b-aaa2-4ec61bc6de52": "address_list_employee",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"9c251d7d-da70-4d63-a72c-e69c26270442": (
|
||||
ListAddressResponse,
|
||||
[Addresses.__language_model__],
|
||||
),
|
||||
"52afe375-dd95-4f4b-aaa2-4ec61bc6de52": (
|
||||
ListAddressResponse,
|
||||
[Addresses.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def address_list_super_user(
|
||||
cls,
|
||||
list_options: ListOptions,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
db = RelationshipEmployee2PostCode.new_session()
|
||||
post_code_list = RelationshipEmployee2PostCode.filter_all(
|
||||
RelationshipEmployee2PostCode.company_id
|
||||
== token_dict.selected_company.company_id,
|
||||
db=db,
|
||||
).data
|
||||
post_code_id_list = [post_code.member_id for post_code in post_code_list]
|
||||
if not post_code_id_list:
|
||||
raise HTTPExceptionApi(
|
||||
status_code=404,
|
||||
detail="User has no post code registered. User can not list addresses.",
|
||||
)
|
||||
get_street_ids = [
|
||||
street_id[0]
|
||||
for street_id in AddressPostcode.select_only(
|
||||
AddressPostcode.id.in_(post_code_id_list),
|
||||
select_args=[AddressPostcode.street_id],
|
||||
order_by=AddressPostcode.street_id.desc(),
|
||||
db=db,
|
||||
).data
|
||||
]
|
||||
if not get_street_ids:
|
||||
raise HTTPExceptionApi(
|
||||
status_code=404,
|
||||
detail="User has no street registered. User can not list addresses.",
|
||||
)
|
||||
Addresses.pre_query = Addresses.filter_all(
|
||||
Addresses.street_id.in_(get_street_ids),
|
||||
db=db,
|
||||
).query
|
||||
Addresses.filter_attr = list_options
|
||||
records = Addresses.filter_all(db=db).data
|
||||
return {}
|
||||
# return AlchemyJsonResponse(
|
||||
# completed=True, message="List Address records", result=records
|
||||
# )
|
||||
|
||||
@classmethod
|
||||
def address_list_employee(
|
||||
cls,
|
||||
list_options: ListOptions,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
# Addresses.filter_attr = list_options
|
||||
Addresses.pre_query = Addresses.filter_all(
|
||||
Addresses.street_id.in_(get_street_ids),
|
||||
)
|
||||
records = Addresses.filter_all().data
|
||||
return
|
||||
# return AlchemyJsonResponse(
|
||||
# completed=True, message="List Address records", result=records
|
||||
# )
|
||||
|
||||
|
||||
class AddressCreateEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "CREATE"
|
||||
event_description = ""
|
||||
event_category = ""
|
||||
|
||||
__event_keys__ = {
|
||||
"ffdc445f-da10-4ce4-9531-d2bdb9a198ae": "create_address",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"ffdc445f-da10-4ce4-9531-d2bdb9a198ae": (
|
||||
InsertAddress,
|
||||
[Addresses.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def create_address(
|
||||
cls,
|
||||
data: InsertAddress,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
post_code = AddressPostcode.filter_one(
|
||||
AddressPostcode.uu_id == data.post_code_uu_id,
|
||||
).data
|
||||
if not post_code:
|
||||
raise HTTPExceptionApi(
|
||||
status_code=404,
|
||||
detail="Post code not found. User can not create address without post code.",
|
||||
)
|
||||
|
||||
data_dict = data.excluded_dump()
|
||||
data_dict["street_id"] = post_code.street_id
|
||||
data_dict["street_uu_id"] = str(post_code.street_uu_id)
|
||||
del data_dict["post_code_uu_id"]
|
||||
address = Addresses.find_or_create(**data_dict)
|
||||
address.save()
|
||||
address.update(is_confirmed=True)
|
||||
address.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Address created successfully",
|
||||
result=address.get_dict(),
|
||||
)
|
||||
|
||||
|
||||
class AddressSearchEventMethod(MethodToEvent):
|
||||
"""Event methods for searching addresses.
|
||||
|
||||
This class handles address search functionality including text search
|
||||
and filtering.
|
||||
"""
|
||||
|
||||
event_type = "SEARCH"
|
||||
event_description = "Search for addresses using text and filters"
|
||||
event_category = "Address"
|
||||
|
||||
__event_keys__ = {
|
||||
"e0ac1269-e9a7-4806-9962-219ac224b0d0": "search_address",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"e0ac1269-e9a7-4806-9962-219ac224b0d0": (
|
||||
SearchAddress,
|
||||
[Addresses.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _build_order_clause(
|
||||
cls, filter_list: Dict[str, Any], schemas: List[str], filter_table: Any
|
||||
) -> Any:
|
||||
"""Build the ORDER BY clause for the query.
|
||||
|
||||
Args:
|
||||
filter_list: Dictionary of filter options
|
||||
schemas: List of available schema fields
|
||||
filter_table: SQLAlchemy table to query
|
||||
|
||||
Returns:
|
||||
SQLAlchemy order_by clause
|
||||
"""
|
||||
# Default to ordering by UUID if field not in schema
|
||||
if filter_list.get("order_field") not in schemas:
|
||||
filter_list["order_field"] = "uu_id"
|
||||
else:
|
||||
# Extract table and field from order field
|
||||
table_name, field_name = str(filter_list.get("order_field")).split(".")
|
||||
filter_table = getattr(databases.sql_models, table_name)
|
||||
filter_list["order_field"] = field_name
|
||||
|
||||
# Build order clause
|
||||
field = getattr(filter_table, filter_list.get("order_field"))
|
||||
return (
|
||||
field.desc()
|
||||
if str(filter_list.get("order_type"))[0] == "d"
|
||||
else field.asc()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _format_record(cls, record: Any, schemas: List[str]) -> Dict[str, str]:
|
||||
"""Format a database record into a dictionary.
|
||||
|
||||
Args:
|
||||
record: Database record to format
|
||||
schemas: List of schema fields
|
||||
|
||||
Returns:
|
||||
Formatted record dictionary
|
||||
"""
|
||||
result = {}
|
||||
for index, schema in enumerate(schemas):
|
||||
value = str(record[index])
|
||||
# Special handling for UUID fields
|
||||
if "uu_id" in value:
|
||||
value = str(value)
|
||||
result[schema] = value
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def search_address(
|
||||
cls,
|
||||
data: SearchAddress,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
) -> Any:
|
||||
"""Search for addresses using text search and filters.
|
||||
|
||||
Args:
|
||||
data: Search parameters including text and filters
|
||||
token_dict: Authentication token
|
||||
|
||||
Returns:
|
||||
JSON response with search results
|
||||
|
||||
Raises:
|
||||
HTTPExceptionApi: If search fails
|
||||
"""
|
||||
try:
|
||||
# Start performance measurement
|
||||
start_time = perf_counter()
|
||||
|
||||
# Get initial query
|
||||
search_result = AddressStreet.search_address_text(search_text=data.search)
|
||||
if not search_result:
|
||||
raise HTTPExceptionApi(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="No addresses found matching search criteria",
|
||||
)
|
||||
|
||||
query = search_result.get("query")
|
||||
schemas = search_result.get("schema")
|
||||
|
||||
# Apply filters
|
||||
filter_list = data.list_options.dump()
|
||||
filter_table = AddressStreet
|
||||
|
||||
# Build and apply order clause
|
||||
order = cls._build_order_clause(filter_list, schemas, filter_table)
|
||||
|
||||
# Apply pagination
|
||||
page_size = int(filter_list.get("size"))
|
||||
offset = (int(filter_list.get("page")) - 1) * page_size
|
||||
|
||||
# Execute query
|
||||
query = (
|
||||
query.order_by(order)
|
||||
.limit(page_size)
|
||||
.offset(offset)
|
||||
.populate_existing()
|
||||
)
|
||||
records = list(query.all())
|
||||
|
||||
# Format results
|
||||
results = [cls._format_record(record, schemas) for record in records]
|
||||
|
||||
# Log performance
|
||||
duration = perf_counter() - start_time
|
||||
print(f"Address search completed in {duration:.3f}s")
|
||||
|
||||
return AlchemyJsonResponse(
|
||||
completed=True, message="Address search results", result=results
|
||||
)
|
||||
|
||||
except HTTPExceptionApi as e:
|
||||
# Re-raise HTTP exceptions
|
||||
raise e
|
||||
except Exception as e:
|
||||
# Log and wrap other errors
|
||||
print(f"Address search error: {str(e)}")
|
||||
raise HTTPExceptionApi(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Failed to search addresses",
|
||||
) from e
|
||||
|
||||
|
||||
class AddressUpdateEventMethod(MethodToEvent):
|
||||
|
||||
event_type = "UPDATE"
|
||||
event_description = ""
|
||||
event_category = ""
|
||||
|
||||
__event_keys__ = {
|
||||
"1f9c3a9c-e5bd-4dcd-9b9a-3742d7e03a27": "update_address",
|
||||
}
|
||||
__event_validation__ = {
|
||||
"1f9c3a9c-e5bd-4dcd-9b9a-3742d7e03a27": (
|
||||
UpdateAddress,
|
||||
[Addresses.__language_model__],
|
||||
),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def update_address(
|
||||
cls,
|
||||
address_uu_id: str,
|
||||
data: UpdateAddress,
|
||||
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
if isinstance(token_dict, EmployeeTokenObject):
|
||||
address = Addresses.filter_one(
|
||||
Addresses.uu_id == address_uu_id,
|
||||
).data
|
||||
if not address:
|
||||
raise HTTPExceptionApi(
|
||||
status_code=404,
|
||||
detail=f"Address not found. User can not update with given address uuid : {address_uu_id}",
|
||||
)
|
||||
|
||||
data_dict = data.excluded_dump()
|
||||
updated_address = address.update(**data_dict)
|
||||
updated_address.save()
|
||||
return AlchemyJsonResponse(
|
||||
completed=True,
|
||||
message="Address updated successfully",
|
||||
result=updated_address.get_dict(),
|
||||
)
|
||||
elif isinstance(token_dict, OccupantTokenObject):
|
||||
raise HTTPExceptionApi(
|
||||
status_code=403,
|
||||
detail="Occupant can not update address.",
|
||||
)
|
||||
112
Events/AllEvents/events/address/endpoints.py
Normal file
112
Events/AllEvents/events/address/endpoints.py
Normal file
@@ -0,0 +1,112 @@
|
||||
"""
|
||||
Account records endpoint configurations.
|
||||
|
||||
"""
|
||||
|
||||
from ApiEvents.abstract_class import (
|
||||
RouteFactoryConfig,
|
||||
EndpointFactoryConfig,
|
||||
endpoint_wrapper,
|
||||
)
|
||||
from ApiEvents.base_request_model import EndpointBaseRequestModel
|
||||
|
||||
from Services.PostgresDb.Models.alchemy_response import DictJsonResponse
|
||||
from fastapi import Request, Path, Body
|
||||
|
||||
|
||||
@endpoint_wrapper("/address/list")
|
||||
async def address_list(request: "Request", data: EndpointBaseRequestModel):
|
||||
"""Handle address list endpoint."""
|
||||
auth_dict = address_list.auth
|
||||
code_dict = getattr(address_list, "func_code", {"function_code": None})
|
||||
return {"auth_dict": auth_dict, "code_dict": code_dict, "data": data}
|
||||
|
||||
|
||||
@endpoint_wrapper("/address/create")
|
||||
async def address_create(request: "Request", data: EndpointBaseRequestModel):
|
||||
"""Handle address creation endpoint."""
|
||||
return {
|
||||
"data": data,
|
||||
"request": str(request.headers),
|
||||
"request_url": str(request.url),
|
||||
"request_base_url": str(request.base_url),
|
||||
}
|
||||
|
||||
|
||||
@endpoint_wrapper("/address/update/{address_uu_id}")
|
||||
async def address_update(
|
||||
request: Request,
|
||||
address_uu_id: str = Path(..., description="UUID of the address to update"),
|
||||
request_data: EndpointBaseRequestModel = Body(..., description="Request body"),
|
||||
):
|
||||
"""
|
||||
Handle address update endpoint.
|
||||
|
||||
Args:
|
||||
request: FastAPI request object
|
||||
address_uu_id: UUID of the address to update
|
||||
request_data: Request body containing updated address data
|
||||
|
||||
Returns:
|
||||
DictJsonResponse: Response containing updated address info
|
||||
"""
|
||||
auth_dict = address_update.auth
|
||||
return DictJsonResponse(
|
||||
data={
|
||||
"address_uu_id": address_uu_id,
|
||||
"data": request_data.root,
|
||||
"request": str(request.headers),
|
||||
"request_url": str(request.url),
|
||||
"request_base_url": str(request.base_url),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
prefix = "/address"
|
||||
|
||||
|
||||
# Address Router Configuration
|
||||
ADDRESS_CONFIG = RouteFactoryConfig(
|
||||
name="address",
|
||||
prefix=prefix,
|
||||
tags=["Address"],
|
||||
include_in_schema=True,
|
||||
endpoints=[
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/list",
|
||||
url_of_endpoint=f"{prefix}/list",
|
||||
endpoint="/list",
|
||||
method="POST",
|
||||
summary="List Active/Delete/Confirm Address",
|
||||
description="List Active/Delete/Confirm Address",
|
||||
is_auth_required=True,
|
||||
is_event_required=True,
|
||||
endpoint_function=address_list,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/create",
|
||||
url_of_endpoint=f"{prefix}/create",
|
||||
endpoint="/create",
|
||||
method="POST",
|
||||
summary="Create Address with given auth levels",
|
||||
description="Create Address with given auth levels",
|
||||
is_auth_required=False,
|
||||
is_event_required=False,
|
||||
endpoint_function=address_create,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/{address_uu_id}",
|
||||
url_of_endpoint="{prefix}/" + "{address_uu_id}",
|
||||
endpoint="/{address_uu_id}",
|
||||
method="PUT",
|
||||
summary="Update Address with given auth levels",
|
||||
description="Update Address with given auth levels",
|
||||
is_auth_required=True,
|
||||
is_event_required=True,
|
||||
endpoint_function=address_update,
|
||||
),
|
||||
],
|
||||
).as_dict()
|
||||
0
Events/AllEvents/events/address/models.py
Normal file
0
Events/AllEvents/events/address/models.py
Normal file
0
Events/AllEvents/events/building/build_area.py
Normal file
0
Events/AllEvents/events/building/build_area.py
Normal file
0
Events/AllEvents/events/building/build_parts.py
Normal file
0
Events/AllEvents/events/building/build_parts.py
Normal file
0
Events/AllEvents/events/building/build_sites.py
Normal file
0
Events/AllEvents/events/building/build_sites.py
Normal file
0
Events/AllEvents/events/building/build_types.py
Normal file
0
Events/AllEvents/events/building/build_types.py
Normal file
0
Events/AllEvents/events/building/living_spaces.py
Normal file
0
Events/AllEvents/events/building/living_spaces.py
Normal file
0
Events/AllEvents/events/company/company.py
Normal file
0
Events/AllEvents/events/company/company.py
Normal file
0
Events/AllEvents/events/company/department.py
Normal file
0
Events/AllEvents/events/company/department.py
Normal file
0
Events/AllEvents/events/company/duties.py
Normal file
0
Events/AllEvents/events/company/duties.py
Normal file
0
Events/AllEvents/events/company/duty.py
Normal file
0
Events/AllEvents/events/company/duty.py
Normal file
0
Events/AllEvents/events/company/employee.py
Normal file
0
Events/AllEvents/events/company/employee.py
Normal file
0
Events/AllEvents/events/company/staff.py
Normal file
0
Events/AllEvents/events/company/staff.py
Normal file
0
Events/AllEvents/events/identity/people.py
Normal file
0
Events/AllEvents/events/identity/people.py
Normal file
0
Events/AllEvents/events/identity/users.py
Normal file
0
Events/AllEvents/events/identity/users.py
Normal file
Reference in New Issue
Block a user