sqlalchemy updated
This commit is contained in:
@@ -88,8 +88,15 @@ class AuthenticationLoginEventMethods(MethodToEvent):
|
||||
|
||||
# Return response with token and headers
|
||||
return {
|
||||
**token,
|
||||
"headers": dict(request.headers),
|
||||
"completed": True,
|
||||
"message": "User is logged in successfully",
|
||||
"access_token": token.get("access_token"),
|
||||
"refresh_token": token.get("refresher_token"),
|
||||
"access_object": {
|
||||
"user_type": token.get("user_type"),
|
||||
"companies_list": token.get("companies_list"),
|
||||
},
|
||||
"user": token.get("user"),
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +183,9 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
|
||||
# Get reachable events
|
||||
reachable_event_codes = Event2Employee.get_event_codes(employee_id=employee.id)
|
||||
reachable_event_endpoints = Event2Employee.get_event_endpoints(
|
||||
employee_id=employee.id
|
||||
)
|
||||
|
||||
# Get staff and duties
|
||||
staff = Staff.filter_one(Staff.id == employee.staff_id, db=db_session).data
|
||||
@@ -206,6 +216,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
employee_id=employee.id,
|
||||
employee_uu_id=employee.uu_id.__str__(),
|
||||
reachable_event_codes=reachable_event_codes,
|
||||
reachable_event_endpoints=reachable_event_endpoints,
|
||||
)
|
||||
try: # Update Redis
|
||||
update_token = TokenService.update_token_at_redis(
|
||||
@@ -246,6 +257,10 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
reachable_event_codes = Event2Occupant.get_event_codes(
|
||||
build_living_space_id=selected_build_living_space.id
|
||||
)
|
||||
reachable_event_endpoints = Event2Occupant.get_event_endpoints(
|
||||
build_living_space_id=selected_build_living_space.id
|
||||
)
|
||||
|
||||
occupant_type = OccupantTypes.filter_one(
|
||||
OccupantTypes.id == selected_build_living_space.occupant_type_id,
|
||||
db=db,
|
||||
@@ -289,6 +304,7 @@ class AuthenticationSelectEventMethods(MethodToEvent):
|
||||
responsible_company_id=company_related.id,
|
||||
responsible_company_uuid=company_related.uu_id.__str__(),
|
||||
reachable_event_codes=reachable_event_codes,
|
||||
reachable_event_endpoints=reachable_event_endpoints,
|
||||
)
|
||||
|
||||
try: # Update Redis
|
||||
|
||||
@@ -69,9 +69,10 @@ async def authentication_select_company_or_occupant_type(
|
||||
request=request, data=data, token_dict=auth_dict
|
||||
):
|
||||
if data.is_employee:
|
||||
return {"selected_company": data.company_uu_id}
|
||||
return {"selected_company": data.company_uu_id, "completed": True}
|
||||
elif data.is_occupant:
|
||||
return {"selected_occupant": data.build_living_space_uu_id}
|
||||
return {"selected_occupant": data.build_living_space_uu_id, "completed": True}
|
||||
return {"completed": False, "selected_company": None, "selected_occupant": None}
|
||||
|
||||
|
||||
@endpoint_wrapper("/authentication/login")
|
||||
@@ -87,10 +88,9 @@ async def authentication_login_with_domain_and_creds(
|
||||
)
|
||||
|
||||
|
||||
@endpoint_wrapper("/authentication/check")
|
||||
@endpoint_wrapper("/authentication/valid")
|
||||
async def authentication_check_token_is_valid(
|
||||
request: "Request",
|
||||
data: EndpointBaseRequestModel,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Check if a token is valid.
|
||||
@@ -99,12 +99,10 @@ async def authentication_check_token_is_valid(
|
||||
access_token = TokenService.get_access_token_from_request(request=request)
|
||||
if TokenService.get_object_via_access_key(access_token=access_token):
|
||||
return {
|
||||
"status": True,
|
||||
"message": "Access Token is valid",
|
||||
}
|
||||
except HTTPException:
|
||||
return {
|
||||
"status": False,
|
||||
"message": "Access Token is NOT valid",
|
||||
}
|
||||
|
||||
@@ -261,9 +259,9 @@ AUTH_CONFIG = RouteFactoryConfig(
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/check",
|
||||
url_of_endpoint="/authentication/check",
|
||||
endpoint="/check",
|
||||
url_endpoint="/valid",
|
||||
url_of_endpoint="/authentication/valid",
|
||||
endpoint="/valid",
|
||||
method="GET",
|
||||
summary="Check access token is valid",
|
||||
description="Check access token is valid",
|
||||
|
||||
@@ -81,9 +81,9 @@ ACCOUNT_RECORDS_CONFIG = RouteFactoryConfig(
|
||||
endpoints=[
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/address/list",
|
||||
url_of_endpoint="/account/records/address/list",
|
||||
endpoint="/address/list",
|
||||
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",
|
||||
@@ -93,9 +93,9 @@ ACCOUNT_RECORDS_CONFIG = RouteFactoryConfig(
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/address/create",
|
||||
url_of_endpoint="/account/records/address/create",
|
||||
endpoint="/address/create",
|
||||
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",
|
||||
@@ -105,9 +105,9 @@ ACCOUNT_RECORDS_CONFIG = RouteFactoryConfig(
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/address/search",
|
||||
url_of_endpoint="/account/records/address/search",
|
||||
endpoint="/address/search",
|
||||
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",
|
||||
@@ -117,9 +117,9 @@ ACCOUNT_RECORDS_CONFIG = RouteFactoryConfig(
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/address/{address_uu_id}",
|
||||
url_of_endpoint="/account/records/address/{address_uu_id}",
|
||||
endpoint="/address/{address_uu_id}",
|
||||
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",
|
||||
|
||||
112
ApiEvents/EventServiceApi/events/address/endpoints.py
Normal file
112
ApiEvents/EventServiceApi/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
ApiEvents/EventServiceApi/events/company/company.py
Normal file
0
ApiEvents/EventServiceApi/events/company/company.py
Normal file
0
ApiEvents/EventServiceApi/events/company/duties.py
Normal file
0
ApiEvents/EventServiceApi/events/company/duties.py
Normal file
0
ApiEvents/EventServiceApi/events/company/duty.py
Normal file
0
ApiEvents/EventServiceApi/events/company/duty.py
Normal file
0
ApiEvents/EventServiceApi/events/company/staff.py
Normal file
0
ApiEvents/EventServiceApi/events/company/staff.py
Normal file
0
ApiEvents/EventServiceApi/events/identity/people.py
Normal file
0
ApiEvents/EventServiceApi/events/identity/people.py
Normal file
0
ApiEvents/EventServiceApi/events/identity/users.py
Normal file
0
ApiEvents/EventServiceApi/events/identity/users.py
Normal file
121
ApiEvents/ValidationServiceApi/events/available/endpoints.py
Normal file
121
ApiEvents/ValidationServiceApi/events/available/endpoints.py
Normal file
@@ -0,0 +1,121 @@
|
||||
from typing import TYPE_CHECKING, Dict, Any, Union
|
||||
|
||||
from ApiEvents.base_request_model import DictRequestModel, EndpointBaseRequestModel
|
||||
from ApiEvents.abstract_class import (
|
||||
RouteFactoryConfig,
|
||||
EndpointFactoryConfig,
|
||||
endpoint_wrapper,
|
||||
)
|
||||
from ApiValidations.Custom.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
from ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
|
||||
from ApiLibrary.common.line_number import get_line_number_for_error
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request, HTTPException, status, Body
|
||||
|
||||
|
||||
# Type aliases for common types
|
||||
prefix = "/available"
|
||||
|
||||
|
||||
async def check_endpoints_available(
|
||||
request: "Request"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Check if endpoints are available.
|
||||
"""
|
||||
auth_dict = check_endpoints_available.auth
|
||||
selection_of_user = None
|
||||
if auth_dict.is_occupant:
|
||||
selection_of_user = auth_dict.selected_occupant
|
||||
else:
|
||||
selection_of_user = auth_dict.selected_company
|
||||
if not selection_of_user:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang=auth_dict.lang,
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="User selection not found",
|
||||
)
|
||||
return {"reachable_event_endpoints": selection_of_user.reachable_event_endpoints}
|
||||
|
||||
|
||||
async def check_endpoint_available(
|
||||
request: "Request",
|
||||
data: EndpointBaseRequestModel,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Check if endpoints are available.
|
||||
"""
|
||||
auth_dict = check_endpoint_available.auth
|
||||
print("data", data)
|
||||
data_dict = data.data
|
||||
endpoint_asked = data_dict.get("endpoint", None)
|
||||
|
||||
if not endpoint_asked:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang=auth_dict.lang,
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Endpoint not found",
|
||||
)
|
||||
|
||||
selection_of_user = None
|
||||
if auth_dict.is_occupant:
|
||||
selection_of_user = auth_dict.selected_occupant
|
||||
else:
|
||||
selection_of_user = auth_dict.selected_company
|
||||
if not selection_of_user:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang=auth_dict.lang,
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="User selection not found",
|
||||
)
|
||||
|
||||
if endpoint_asked not in selection_of_user.reachable_event_endpoints:
|
||||
raise HTTPExceptionApi(
|
||||
error_code="",
|
||||
lang=auth_dict.lang,
|
||||
loc=get_line_number_for_error(),
|
||||
sys_msg="Endpoint not found",
|
||||
)
|
||||
return {
|
||||
"endpoint": endpoint_asked,
|
||||
"status": "OK"
|
||||
}
|
||||
|
||||
|
||||
AVAILABLE_CONFIG = RouteFactoryConfig(
|
||||
name="available_endpoints",
|
||||
prefix=prefix,
|
||||
tags=["Available Endpoints"],
|
||||
include_in_schema=True,
|
||||
endpoints=[
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/endpoints",
|
||||
url_of_endpoint=f"{prefix}/endpoints",
|
||||
endpoint="/endpoints",
|
||||
method="POST",
|
||||
summary="Retrieve all endpoints available for user",
|
||||
description="",
|
||||
is_auth_required=True, # Needs token_dict
|
||||
is_event_required=False,
|
||||
endpoint_function=check_endpoints_available,
|
||||
),
|
||||
EndpointFactoryConfig(
|
||||
url_prefix=prefix,
|
||||
url_endpoint="/endpoint",
|
||||
url_of_endpoint=f"{prefix}/endpoint",
|
||||
endpoint="/endpoint",
|
||||
method="POST",
|
||||
summary="Retrieve an endpoint available for user",
|
||||
description="",
|
||||
is_auth_required=True, # Needs token_dict
|
||||
is_event_required=False,
|
||||
endpoint_function=check_endpoint_available,
|
||||
),
|
||||
],
|
||||
).as_dict()
|
||||
325
ApiEvents/ValidationServiceApi/events/available/models.py
Normal file
325
ApiEvents/ValidationServiceApi/events/available/models.py
Normal file
@@ -0,0 +1,325 @@
|
||||
"""
|
||||
request models.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any, Literal, Optional, TypedDict, Union
|
||||
from pydantic import BaseModel, Field, model_validator, RootModel, ConfigDict
|
||||
from ApiEvents.base_request_model import BaseRequestModel, DictRequestModel
|
||||
from ApiValidations.Custom.token_objects import EmployeeTokenObject, OccupantTokenObject
|
||||
from ApiValidations.Request.base_validations import ListOptions
|
||||
from ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
|
||||
from Schemas.identity.identity import (
|
||||
AddressPostcode,
|
||||
Addresses,
|
||||
RelationshipEmployee2PostCode,
|
||||
)
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from fastapi import Request
|
||||
|
||||
|
||||
class AddressListEventMethods(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,
|
||||
"52afe375-dd95-4f4b-aaa2-4ec61bc6de52": ListAddressResponse,
|
||||
}
|
||||
|
||||
@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(),
|
||||
).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),
|
||||
).query
|
||||
Addresses.filter_attr = list_options
|
||||
records = Addresses.filter_all().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 AddressCreateEventMethods(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,
|
||||
}
|
||||
|
||||
@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 AddressSearchEventMethods(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,
|
||||
}
|
||||
|
||||
@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],
|
||||
) -> JSONResponse:
|
||||
"""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 AddressUpdateEventMethods(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,
|
||||
}
|
||||
|
||||
@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.",
|
||||
)
|
||||
@@ -81,7 +81,7 @@ VALIDATION_CONFIG_MAIN =RouteFactoryConfig(
|
||||
method="POST",
|
||||
summary="Select company or occupant type",
|
||||
description="Select company or occupant type",
|
||||
is_auth_required=False, # Needs token_dict
|
||||
is_auth_required=True, # Needs token_dict
|
||||
is_event_required=False,
|
||||
endpoint_function=validations_validations_select,
|
||||
),
|
||||
@@ -93,7 +93,7 @@ VALIDATION_CONFIG_MAIN =RouteFactoryConfig(
|
||||
method="POST",
|
||||
summary="Select company or occupant type",
|
||||
description="Select company or occupant type",
|
||||
is_auth_required=False, # Needs token_dict
|
||||
is_auth_required=True, # Needs token_dict
|
||||
is_event_required=False,
|
||||
endpoint_function=validations_headers_select,
|
||||
),
|
||||
@@ -105,7 +105,7 @@ VALIDATION_CONFIG_MAIN =RouteFactoryConfig(
|
||||
method="POST",
|
||||
summary="Select company or occupant type",
|
||||
description="Select company or occupant type",
|
||||
is_auth_required=False, # Needs token_dict
|
||||
is_auth_required=True, # Needs token_dict
|
||||
is_event_required=False,
|
||||
endpoint_function=validations_validations_and_headers_select,
|
||||
),
|
||||
|
||||
@@ -75,7 +75,7 @@ class ValidationsBoth(MethodToEvent):
|
||||
return {
|
||||
"headers": validation.headers,
|
||||
"validation": validation.validation,
|
||||
"language_models": language_model_all,
|
||||
# "language_models": language_model_all,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -7,9 +7,10 @@ to be used by the dynamic route creation system.
|
||||
|
||||
from typing import Dict, List, Any, TypeVar
|
||||
from .events.validation.endpoints import VALIDATION_CONFIG
|
||||
from .events.available.endpoints import AVAILABLE_CONFIG
|
||||
|
||||
# Registry of all route configurations
|
||||
ROUTE_CONFIGS = [VALIDATION_CONFIG]
|
||||
ROUTE_CONFIGS = [VALIDATION_CONFIG, AVAILABLE_CONFIG]
|
||||
|
||||
|
||||
def get_route_configs() -> List[Dict[str, Any]]:
|
||||
|
||||
Reference in New Issue
Block a user