validations and dockerfiles are updated

This commit is contained in:
2025-01-10 12:40:52 +03:00
parent f4f9e584ff
commit 4eb95e4d9c
107 changed files with 400185 additions and 1338 deletions

View File

@@ -1,72 +1,131 @@
import typing
from abc import ABC
from fastapi import status
from fastapi.exceptions import HTTPException
from typing import TypeVar, Union, Dict, Any, Optional, Type
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
TokenType = TypeVar('TokenType', bound=Union[EmployeeTokenObject, OccupantTokenObject])
class ActionsSchema(ABC):
def __init__(self, endpoint: str = None):
"""Base class for defining API action schemas.
This class handles endpoint registration and validation in the database.
"""
def __init__(self, endpoint: str):
"""Initialize with an API endpoint path.
Args:
endpoint: The API endpoint path (e.g. "/users/create")
"""
self.endpoint = endpoint
def retrieve_action_from_endpoint(self):
def retrieve_action_from_endpoint(self) -> Dict[str, Any]:
"""Retrieve the endpoint registration from the database.
Returns:
Dict containing the endpoint registration data
Raises:
HTTPException: If endpoint is not found in database
"""
from databases import EndpointRestriction
endpoint_restriction = EndpointRestriction.filter_one(
EndpointRestriction.endpoint_name.ilike(f"%{self.endpoint}%"), system=True
EndpointRestriction.endpoint_name.ilike(f"%{self.endpoint}%"),
system=True
).data
if not endpoint_restriction:
raise HTTPException(
status_code=404,
detail=f"Endpoint {self.endpoint} not found in the database",
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Endpoint {self.endpoint} not found in the database"
)
return endpoint_restriction
class ActionsSchemaFactory:
"""Factory class for creating action schemas.
This class validates and initializes action schemas for API endpoints.
"""
def __init__(self, action: ActionsSchema):
"""Initialize with an action schema.
Args:
action: The action schema to initialize
Raises:
HTTPException: If action initialization fails
"""
self.action = action
try:
self.action_match = self.action.retrieve_action_from_endpoint()
except HTTPException as e:
# Re-raise HTTP exceptions as-is
raise e
except Exception as e:
err = e
# Log and wrap other exceptions
print(f"ActionsSchemaFactory Error: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to initialize action schema"
) from e
class MethodToEvent(ABC, ActionsSchemaFactory):
action_key: str = None
event_type: str = None
"""Base class for mapping methods to API events.
This class handles method registration and validation for API events.
"""
action_key: Optional[str] = None
event_type: Optional[str] = None
event_description: str = ""
event_category: str = ""
__event_keys__: dict = {}
__event_validation__: dict = {}
__event_keys__: Dict[str, str] = {}
__event_validation__: Dict[str, Any] = {}
@classmethod
def call_event_method(cls, method_uu_id: str, *args, **kwargs):
def call_event_method(cls, method_uu_id: str, *args: Any, **kwargs: Any) -> Any:
"""Call an event method by its UUID.
Args:
method_uu_id: UUID of the method to call
*args: Positional arguments to pass to method
**kwargs: Keyword arguments to pass to method
Returns:
The result of the called method
Raises:
AttributeError: If method UUID is not found
"""
function_name = cls.__event_keys__.get(method_uu_id)
if not function_name:
raise AttributeError(f"No method found for UUID: {method_uu_id}")
return getattr(cls, function_name)(*args, **kwargs)
@classmethod
def ban_token_objects(
cls,
token: typing.Union[EmployeeTokenObject, OccupantTokenObject],
ban_list: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
from fastapi import status
from fastapi.exceptions import HTTPException
if token.user_type == ban_list.user_type:
if isinstance(token, EmployeeTokenObject):
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail="No employee can reach this event. An notification is send to admin about event registration",
)
if isinstance(token, OccupantTokenObject):
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail="No occupant can reach this event. An notification is send to admin about event registration",
)
token: TokenType,
ban_list: Type[TokenType]
) -> None:
"""Check if a token type is banned from accessing an event.
Args:
token: The token to check
ban_list: The token type that is banned
Raises:
HTTPException: If token type matches banned type
"""
if isinstance(token, ban_list):
user_type = "employee" if isinstance(token, EmployeeTokenObject) else "occupant"
raise HTTPException(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail=f"No {user_type} can reach this event. A notification has been sent to admin."
)

View File

@@ -7,15 +7,16 @@ from api_validations.validations_request import (
ListOptions,
)
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.validations_response.account import AccountListResponse
from api_validations.validations_response.account_responses import AccountRecordsListResponse
from databases import (
AccountRecords,
BuildIbans,
)
from databases.sql_models.building.build import Build, BuildLivingSpace
from databases.sql_models.building.build import BuildLivingSpace
from databases.sql_models.building.decision_book import BuildDecisionBookPayments
from databases.sql_models.others.enums import ApiEnumDropdown
@@ -31,8 +32,8 @@ class AccountRecordsListEventMethods(MethodToEvent):
"208e6273-17ef-44f0-814a-8098f816b63a": "account_records_list_flt_res",
}
__event_validation__ = {
"7192c2aa-5352-4e36-98b3-dafb7d036a3d": AccountListResponse,
"208e6273-17ef-44f0-814a-8098f816b63a": AccountListResponse,
"7192c2aa-5352-4e36-98b3-dafb7d036a3d": AccountRecordsListResponse,
"208e6273-17ef-44f0-814a-8098f816b63a": AccountRecordsListResponse,
}
@classmethod
@@ -53,7 +54,12 @@ class AccountRecordsListEventMethods(MethodToEvent):
AccountRecords.filter_attr = list_options
records = AccountRecords.filter_all()
return AlchemyJsonResponse(
completed=True, message="List Build record", result=records
completed=True,
message="Account records listed successfully",
result=records,
cls_object=AccountRecords,
filter_attributes=list_options,
response_model=AccountRecordsListResponse
)
@classmethod
@@ -182,7 +188,9 @@ class AccountRecordsListEventMethods(MethodToEvent):
"process_comment": list_of_values[5],
}
)
return dict(completed=True, message="List Build record", result=return_list)
return AlchemyJsonResponse(
completed=True, message="List Account records", result=return_list
)
class AccountRecordsCreateEventMethods(MethodToEvent):
@@ -221,9 +229,7 @@ class AccountRecordsCreateEventMethods(MethodToEvent):
)
account_record = AccountRecords.find_or_create(**data.excluded_dump())
return AlchemyJsonResponse(
completed=True,
message="Update Build record",
result=account_record.get_dict(),
completed=True, message="Account record created successfully", result=account_record
)
elif isinstance(token_dict, EmployeeTokenObject):
# Build.pre_query = Build.select_action(
@@ -263,14 +269,9 @@ class AccountRecordsCreateEventMethods(MethodToEvent):
data_dict["receive_debit"] = debit_type.id
data_dict["receive_debit_uu_id"] = str(debit_type.uu_id)
account_record = AccountRecords.find_or_create(**data_dict)
account_record.save()
account_record.update(is_confirmed=True)
account_record.save()
account_record = AccountRecords.insert_one(data_dict).data
return AlchemyJsonResponse(
completed=True,
message="Create Account record are successful",
result=account_record.get_dict(),
completed=True, message="Account record created successfully", result=account_record
)
@@ -299,10 +300,9 @@ class AccountRecordsUpdateEventMethods(MethodToEvent):
elif isinstance(token_dict, EmployeeTokenObject):
pass
account_record = AccountRecords.update_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Update Build record",
result=None,
completed=True, message="Account record updated successfully", result=account_record
)
@@ -326,10 +326,9 @@ class AccountRecordsPatchEventMethods(MethodToEvent):
data,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
account_record = AccountRecords.patch_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Patch Build record",
result=None,
completed=True, message="Account record patched successfully", result=account_record
)

View File

@@ -22,7 +22,7 @@ from api_validations.validations_request import (
UpdatePostCode,
SearchAddress,
)
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
@@ -77,9 +77,7 @@ class AddressListEventMethods(MethodToEvent):
Addresses.filter_attr = list_options
records = Addresses.filter_all().data
return AlchemyJsonResponse(
completed=True,
message="List Address records",
result=records,
completed=True, message="List Address records", result=records
)
@classmethod
@@ -89,13 +87,12 @@ class AddressListEventMethods(MethodToEvent):
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
Addresses.filter_attr = list_options
records = Addresses.list_via_employee(
token_dict=token_dict,
Addresses.pre_query = Addresses.filter_all(
Addresses.street_id.in_(get_street_ids),
)
records = Addresses.filter_all().data
return AlchemyJsonResponse(
completed=True,
message="List Address records",
result=records,
completed=True, message="List Address records", result=records
)
@@ -135,21 +132,20 @@ class AddressCreateEventMethods(MethodToEvent):
address.save()
address.update(is_confirmed=True)
address.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Address record",
"data": address.get_dict(),
},
status_code=200,
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 = ""
event_category = ""
event_description = "Search for addresses using text and filters"
event_category = "Address"
__event_keys__ = {
"e0ac1269-e9a7-4806-9962-219ac224b0d0": "search_address",
@@ -158,69 +154,132 @@ class AddressSearchEventMethods(MethodToEvent):
"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],
):
import databases.sql_models
from time import perf_counter
) -> 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:
HTTPException: If search fails
"""
try:
# Start performance measurement
start_time = perf_counter()
st = perf_counter()
# Get initial query
search_result = AddressStreet.search_address_text(search_text=data.search)
if not search_result:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No addresses found matching search criteria"
)
pre_query_first = AddressStreet.search_address_text(search_text=data.search)
query, schemas, new_data_list = (
pre_query_first.get("query"),
pre_query_first.get("schema"),
[],
)
filter_list = data.list_options.dump()
filter_table = AddressStreet
if filter_list.get("order_field") not in schemas:
filter_list["order_field"] = "uu_id"
else:
filter_table = getattr(
databases.sql_models, str(filter_list.get("order_field")).split(".")[0]
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()
)
filter_list["order_field"] = str(filter_list.get("order_field")).split(".")[
1
]
records = list(query.all())
order = (
getattr(filter_table, filter_list.get("order_field")).desc()
if str(filter_list.get("order_type"))[0] == "d"
else getattr(filter_table, filter_list.get("order_field")).asc()
)
# Format results
results = [cls._format_record(record, schemas) for record in records]
query = (
query.order_by(order)
.limit(int(filter_list.get("size")))
.offset(int((filter_list.get("page")) - 1) * int(filter_list.get("size")))
.populate_existing()
)
# Log performance
duration = perf_counter() - start_time
print(f"Address search completed in {duration:.3f}s")
records = list(query.all())
print(perf_counter() - st)
return AlchemyJsonResponse(
completed=True,
message="Address search results",
result=results
)
for item in records:
new_data_dict = {}
for index, schema in enumerate(schemas):
new_data_dict[schema] = str(item[index])
if "uu_id" in str(item[index]):
new_data_dict[schema] = str(new_data_dict.get(schema))
new_data_list.append(new_data_dict)
return JSONResponse(
content={
"completed": True,
"pagination": filter_list,
"count": len(new_data_list),
"data": new_data_list,
"message": "Search Address records",
},
status_code=200,
)
except HTTPException 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 HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to search addresses"
) from e
class AddressUpdateEventMethods(MethodToEvent):
@@ -256,13 +315,8 @@ class AddressUpdateEventMethods(MethodToEvent):
data_dict = data.excluded_dump()
updated_address = address.update(**data_dict)
updated_address.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Address record",
"data": updated_address.get_dict(),
},
status_code=200,
return AlchemyJsonResponse(
completed=True, message="Address updated successfully", result=updated_address.get_dict()
)
elif isinstance(token_dict, OccupantTokenObject):
raise HTTPException(
@@ -308,13 +362,8 @@ class AddressPatchEventMethods(MethodToEvent):
del data_dict["post_code_uu_id"]
patched_address = address.patch(**data_dict)
return JSONResponse(
content={
"completed": True,
"message": "Patch Address record",
"data": patched_address.get_dict(),
},
status_code=200,
return AlchemyJsonResponse(
completed=True, message="Address patched successfully", result=patched_address.get_dict()
)
@@ -361,13 +410,8 @@ class AddressPostCodeCreateEventMethods(MethodToEvent):
post_code.save()
relation_table.update(is_confirmed=True)
relation_table.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Post Code record",
"data": post_code.get_dict(),
},
status_code=200,
return AlchemyJsonResponse(
completed=True, message="Post code created successfully", result=post_code.get_dict()
)
@@ -407,26 +451,16 @@ class AddressPostCodeUpdateEventMethods(MethodToEvent):
data_dict = data.excluded_dump()
updated_post_code = post_code.update(**data_dict)
updated_post_code.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Post Code record",
"data": updated_post_code.get_dict(),
},
status_code=200,
return AlchemyJsonResponse(
completed=True, message="Post code updated successfully", result=updated_post_code.get_dict()
)
elif isinstance(token_dict, OccupantTokenObject):
raise HTTPException(
status_code=403,
detail="Occupant can not update post code.",
)
return JSONResponse(
content={
"completed": True,
"message": "Update Post Code record",
"data": {},
},
status_code=404,
return AlchemyJsonResponse(
completed=True, message="Update Post Code record", result={}
)
@@ -459,17 +493,10 @@ class AddressPostCodeListEventMethods(MethodToEvent):
detail="User has no post code registered or not yet any post code created.",
)
AddressPostcode.pre_query = AddressPostcode.filter_all(
AddressPostcode.id.in_(
[post_code.member_id for post_code in post_code_list]
),
).query
AddressPostcode.filter_attr = list_options
records = AddressPostcode.filter_all().data
post_codes = AddressPostcode.filter_all()
return AlchemyJsonResponse(
completed=True,
message="List Address records",
result=records,
completed=True, message="List Post code records", result=post_codes
)

View File

@@ -1,69 +1,45 @@
import datetime
import json
import typing
from typing import Union
import arrow
from fastapi import status
from fastapi.requests import Request
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from api_objects import OccupantTokenObject, EmployeeTokenObject
from api_services.token_service import TokenService
from api_services.redis.functions import RedisActions
from api_library.response_handlers import ResponseHandler
from api_library.logger import user_logger
from api_configs import Auth, ApiStatic
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from databases import (
Companies,
Staff,
Duties,
Departments,
Employees,
BuildLivingSpace,
BuildParts,
Build,
Duty,
Event2Occupant,
Event2Employee,
Users,
UsersTokens,
OccupantTypes,
RelationshipEmployee2Build,
Companies, Staff, Duties, Departments, Employees,
BuildLivingSpace, BuildParts, Build, Duty, Event2Occupant,
Event2Employee, Users, UsersTokens, OccupantTypes,
RelationshipEmployee2Build
)
from api_services import (
redis_cli,
send_email,
get_object_via_access_key,
get_object_via_user_uu_id,
save_access_token_to_redis,
update_selected_to_redis,
password_is_changed_template,
change_your_password_template,
)
from api_configs import ApiStatic, Auth
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects import (
OccupantToken,
CompanyToken,
EmployeeTokenObject,
OccupantTokenObject,
)
from api_library.date_time_actions.date_functions import system_arrow
from databases.no_sql_models.login_handlers import load_user_with_erp_details
from api_validations.validations_request import (
Login,
Logout,
ChangePassword,
Remember,
Forgot,
CreatePassword,
OccupantSelection,
Login, Logout, ChangePassword, Remember,
Forgot, CreatePassword, OccupantSelection,
EmployeeSelection,
)
from api_validations.validations_response.auth_responses import (
AuthenticationLoginResponse,
AuthenticationRefreshResponse,
AuthenticationUserInfoResponse
)
class AuthenticationLoginEventMethods(MethodToEvent):
event_type = "LOGIN"
event_description = "Login via domain and access key : [email] | [phone]"
event_category = "AUTHENTICATION"
@@ -72,37 +48,50 @@ class AuthenticationLoginEventMethods(MethodToEvent):
"e672846d-cc45-4d97-85d5-6f96747fac67": "authentication_login_with_domain_and_creds",
}
__event_validation__ = {
"e672846d-cc45-4d97-85d5-6f96747fac67": "authentication_login_with_domain_and_creds",
"e672846d-cc45-4d97-85d5-6f96747fac67": AuthenticationLoginResponse,
}
@classmethod
def authentication_login_with_domain_and_creds(
cls,
data: Login,
request,
):
access_dict = Users.login_user_with_credentials(data=data, request=request)
found_user = access_dict.get("user", None)
if not found_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials"
)
def authentication_login_with_domain_and_creds(cls, data: Login, request: Request):
try:
access_dict = Users.login_user_with_credentials(data=data, request=request)
found_user = access_dict.get("user")
if not found_user:
user_logger.log_login_attempt(
request, None, data.domain, data.access_key,
success=False, error="Invalid credentials"
)
return ResponseHandler.unauthorized("Invalid credentials")
return JSONResponse(
content={
"completed": True,
"message": "User is logged in successfully",
user_logger.log_login_attempt(
request, found_user.id, data.domain, data.access_key,
success=True
)
response_data = {
"access_token": access_dict.get("access_token"),
"refresh_token": access_dict.get("refresher_token"),
"access_object": access_dict.get("access_object"),
"user": found_user.get_dict(),
},
status_code=status.HTTP_200_OK,
)
}
return ResponseHandler.success(
message="User logged in successfully",
data=response_data,
response_model=AuthenticationLoginResponse
)
except Exception as e:
user_logger.log_login_attempt(
request, None, data.domain, data.access_key,
success=False, error=str(e)
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=str(e)
)
class AuthenticationSelectEventMethods(MethodToEvent):
event_type = "LOGIN"
event_description = "Select Employee Duty or Occupant Type"
event_category = "AUTHENTICATION"
@@ -114,6 +103,165 @@ class AuthenticationSelectEventMethods(MethodToEvent):
"cee96b9b-8487-4e9f-aaed-2e8c79687bf9": "authentication_select_company_or_occupant_type",
}
@classmethod
def _handle_employee_selection(
cls,
data: EmployeeSelection,
token_dict: EmployeeTokenObject,
request: Request
):
"""Handle employee company selection"""
if data.company_uu_id not in token_dict.companies_uu_id_list:
return ResponseHandler.unauthorized("Company not found in user's company list")
selected_company = Companies.filter_one(
Companies.uu_id == data.company_uu_id
).data
if not selected_company:
return ResponseHandler.not_found("Company not found")
# Get department IDs for the company
department_ids = [
dept.id for dept in Departments.filter_all(
Departments.company_id == selected_company.id
).data
]
# Get duties IDs for the company
duties_ids = [
duty.id for duty in Duties.filter_all(
Duties.company_id == selected_company.id
).data
]
# Get staff IDs
staff_ids = [
staff.id for staff in Staff.filter_all(
Staff.duties_id.in_(duties_ids)
).data
]
# Get employee
employee = Employees.filter_one(
Employees.people_id == token_dict.person_id,
Employees.staff_id.in_(staff_ids)
).data
if not employee:
return ResponseHandler.not_found("Employee not found")
# Get reachable events
reachable_event_list_id = Event2Employee.get_event_id_by_employee_id(
employee_id=employee.id
)
# Get staff and duties
staff = Staff.filter_one(Staff.id == employee.staff_id).data
duties = Duties.filter_one(Duties.id == staff.duties_id).data
department = Departments.filter_one(
Departments.id == duties.department_id
).data
# Get bulk duty
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK").data
bulk_duty_id = Duties.filter_by_one(
company_id=selected_company.id,
duties_id=bulk_id.id,
**Duties.valid_record_dict
).data
# Create company token
company_token = CompanyToken(
company_uu_id=selected_company.uu_id.__str__(),
company_id=selected_company.id,
department_id=department.id,
department_uu_id=department.uu_id.__str__(),
duty_id=duties.id,
duty_uu_id=duties.uu_id.__str__(),
bulk_duties_id=bulk_duty_id.id,
staff_id=staff.id,
staff_uu_id=staff.uu_id.__str__(),
employee_id=employee.id,
employee_uu_id=employee.uu_id.__str__(),
reachable_event_list_id=reachable_event_list_id
)
# Update Redis
update_selected_to_redis(request=request, add_payload=company_token)
return ResponseHandler.success("Company selected successfully")
@classmethod
def _handle_occupant_selection(
cls,
data: OccupantSelection,
token_dict: OccupantTokenObject,
request: Request
):
"""Handle occupant type selection"""
# Get occupant type
occupant_type = OccupantTypes.filter_by_one(
system=True,
uu_id=data.occupant_uu_id
).data
if not occupant_type:
return ResponseHandler.not_found("Occupant Type not found")
# Get build part
build_part = BuildParts.filter_by_one(
system=True,
uu_id=data.build_part_uu_id
).data
if not build_part:
return ResponseHandler.not_found("Build Part not found")
# Get build and company info
build = Build.filter_one(Build.id == build_part.build_id).data
related_company = RelationshipEmployee2Build.filter_one(
RelationshipEmployee2Build.member_id == build.id
).data
company_related = Companies.filter_one(
Companies.id == related_company.company_id
).data
responsible_employee = Employees.filter_one(
Employees.id == related_company.employee_id
).data
# Get selected occupant type
selected_occupant_type = BuildLivingSpace.filter_one(
BuildLivingSpace.occupant_type == occupant_type.id,
BuildLivingSpace.person_id == token_dict.person_id,
BuildLivingSpace.build_parts_id == build_part.id
).data
if not selected_occupant_type:
return ResponseHandler.not_found("Selected occupant type not found")
# Get reachable events
reachable_event_list_id = Event2Occupant.get_event_id_by_build_living_space_id(
build_living_space_id=selected_occupant_type.id
)
# Create occupant token
occupant_token = OccupantToken(
living_space_id=selected_occupant_type.id,
living_space_uu_id=selected_occupant_type.uu_id.__str__(),
occupant_type_id=occupant_type.id,
occupant_type_uu_id=occupant_type.uu_id.__str__(),
occupant_type=occupant_type.occupant_type,
build_id=build.id,
build_uuid=build.uu_id.__str__(),
build_part_id=build_part.id,
build_part_uuid=build_part.uu_id.__str__(),
responsible_employee_id=responsible_employee.id,
responsible_employee_uuid=responsible_employee.uu_id.__str__(),
responsible_company_id=company_related.id,
responsible_company_uuid=company_related.uu_id.__str__(),
reachable_event_list_id=reachable_event_list_id
)
# Update Redis
update_selected_to_redis(request=request, add_payload=occupant_token)
return ResponseHandler.success("Occupant selected successfully")
@classmethod
def authentication_select_company_or_occupant_type(
cls,
@@ -121,157 +269,24 @@ class AuthenticationSelectEventMethods(MethodToEvent):
data: Union[EmployeeSelection, OccupantSelection],
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
from api_objects import OccupantToken, CompanyToken
if isinstance(token_dict, EmployeeTokenObject):
if data.company_uu_id not in token_dict.companies_uu_id_list:
return JSONResponse(
content={
"completed": False,
"message": "Company is not found in users company list",
},
status_code=status.HTTP_401_UNAUTHORIZED,
)
if selected_company := Companies.filter_one(
Companies.uu_id == data.company_uu_id,
).data:
department_ids = [
department.id
for department in Departments.filter_all(
Departments.company_id == selected_company.id,
).data
]
duties_ids = [
duties.id
for duties in Duties.filter_all(
Duties.company_id == selected_company.id,
).data
]
staff_ids = [
staff.id
for staff in Staff.filter_all(
Staff.duties_id.in_(duties_ids),
).data
]
employee = Employees.filter_one(
Employees.people_id == token_dict.person_id,
Employees.staff_id.in_(staff_ids),
).data
reachable_event_list_id = Event2Employee.get_event_id_by_employee_id(
employee_id=employee.id
)
staff = Staff.filter_one(
Staff.id == employee.staff_id,
).data
duties = Duties.filter_one(
Duties.id == staff.duties_id,
).data
department = Departments.filter_one(
Departments.id == duties.department_id,
).data
bulk_id = Duty.filter_by_one(system=True, duty_code="BULK").data
bulk_duty_id = Duties.filter_by_one(
company_id=selected_company.id,
duties_id=bulk_id.id,
**Duties.valid_record_dict,
).data
update_selected_to_redis(
request=request,
add_payload=CompanyToken(
company_uu_id=selected_company.uu_id.__str__(),
company_id=selected_company.id,
department_id=department.id,
department_uu_id=department.uu_id.__str__(),
duty_id=duties.id,
duty_uu_id=duties.uu_id.__str__(),
bulk_duties_id=bulk_duty_id.id,
staff_id=staff.id,
staff_uu_id=staff.uu_id.__str__(),
employee_id=employee.id,
employee_uu_id=employee.uu_id.__str__(),
reachable_event_list_id=reachable_event_list_id,
),
)
return JSONResponse(
content={
"completed": True,
"message": "Company is selected successfully",
},
status_code=status.HTTP_200_OK,
)
elif isinstance(token_dict, OccupantTokenObject):
occupant_type = OccupantTypes.filter_by_one(
system=True, uu_id=data.occupant_uu_id
).data
if not occupant_type:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Occupant Type is not found",
)
build_part = BuildParts.filter_by_one(
system=True, uu_id=data.build_part_uu_id
).data
if not build_part:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Build Part is not found",
)
build = Build.filter_one(
Build.id == build_part.build_id,
).data
related_company = RelationshipEmployee2Build.filter_one(
RelationshipEmployee2Build.member_id == build.id,
).data
company_related = Companies.filter_one(
Companies.id == related_company.company_id,
).data
responsible_employee = Employees.filter_one(
Employees.id == related_company.employee_id,
).data
if selected_occupant_type := BuildLivingSpace.filter_one(
BuildLivingSpace.occupant_type == occupant_type.id,
BuildLivingSpace.person_id == token_dict.person_id,
BuildLivingSpace.build_parts_id == build_part.id,
).data:
reachable_event_list_id = (
Event2Occupant.get_event_id_by_build_living_space_id(
build_living_space_id=selected_occupant_type.id
)
)
update_selected_to_redis(
request=request,
add_payload=OccupantToken(
living_space_id=selected_occupant_type.id,
living_space_uu_id=selected_occupant_type.uu_id.__str__(),
occupant_type_id=occupant_type.id,
occupant_type_uu_id=occupant_type.uu_id.__str__(),
occupant_type=occupant_type.occupant_type,
build_id=build.id,
build_uuid=build.uu_id.__str__(),
build_part_id=build_part.id,
build_part_uuid=build_part.uu_id.__str__(),
responsible_employee_id=responsible_employee.id,
responsible_employee_uuid=responsible_employee.uu_id.__str__(),
responsible_company_id=company_related.id,
responsible_company_uuid=company_related.uu_id.__str__(),
reachable_event_list_id=reachable_event_list_id,
),
)
return JSONResponse(
content={
"completed": True,
"message": "Occupant is selected successfully",
},
status_code=status.HTTP_200_OK,
)
return JSONResponse(
content={"completed": False, "message": "Invalid data provided"},
status_code=status.HTTP_418_IM_A_TEAPOT,
)
"""Handle selection of company or occupant type"""
try:
if isinstance(token_dict, EmployeeTokenObject):
return cls._handle_employee_selection(data, token_dict, request)
elif isinstance(token_dict, OccupantTokenObject):
return cls._handle_occupant_selection(data, token_dict, request)
return ResponseHandler.error(
"Invalid token type",
status_code=status.HTTP_400_BAD_REQUEST
)
except Exception as e:
return ResponseHandler.error(
str(e),
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
)
class AuthenticationCheckTokenEventMethods(MethodToEvent):
event_type = "LOGIN"
event_description = "Check Token is valid for user"
event_category = "AUTHENTICATION"
@@ -284,74 +299,70 @@ class AuthenticationCheckTokenEventMethods(MethodToEvent):
}
@classmethod
def authentication_check_token_is_valid(
cls,
request,
):
if get_object_via_access_key(request=request):
return JSONResponse(
content={"completed": True, "message": "Access Token is valid"},
status_code=status.HTTP_200_OK,
)
return JSONResponse(
content={"completed": False, "message": "Access Token is NOT valid"},
status_code=status.HTTP_401_UNAUTHORIZED,
)
def authentication_check_token_is_valid(cls, request: Request):
try:
TokenService.validate_token(request)
return ResponseHandler.success("Access Token is valid")
except HTTPException:
return ResponseHandler.unauthorized("Access Token is NOT valid")
class AuthenticationRefreshEventMethods(MethodToEvent):
event_type = "LOGIN"
event_description = (
"Refresher Token for refreshing access token without credentials"
)
event_description = "Refresh user info using access token"
event_category = "AUTHENTICATION"
__event_keys__ = {
"48379bb2-ba81-4d8e-a9dd-58837cfcbf67": "authentication_refresh_user_info",
}
__event_validation__ = {
"48379bb2-ba81-4d8e-a9dd-58837cfcbf67": "authentication_refresh_user_info",
"48379bb2-ba81-4d8e-a9dd-58837cfcbf67": AuthenticationRefreshResponse,
}
@classmethod
def authentication_refresh_user_info(
cls,
request,
token_dict: typing.Union[EmployeeSelection, OccupantSelection],
request: Request,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
access_token = str(request.headers.get(Auth.ACCESS_TOKEN_TAG))
if token_user := get_object_via_access_key(request=request):
if found_user := Users.filter_one(
Users.uu_id == token_user.get("uu_id")
).data:
user_token = UsersTokens.filter_one(
UsersTokens.domain == found_user.domain_name,
UsersTokens.user_id == found_user.id,
UsersTokens.token_type == "RememberMe",
).data
access_dict = {
"access_token": access_token,
"refresh_token": getattr(user_token, "token", None),
}
return JSONResponse(
content={
"completed": True,
"message": "User is logged in successfully via refresh token",
"data": load_user_with_erp_details(found_user, access_dict),
},
status_code=status.HTTP_200_OK,
)
return JSONResponse(
content={"completed": False, "message": "Invalid data", "data": {}},
status_code=status.HTTP_401_UNAUTHORIZED,
)
try:
access_token = request.headers.get(Auth.ACCESS_TOKEN_TAG)
if not access_token:
return ResponseHandler.unauthorized()
# Get user and token info
found_user = Users.filter_one(
Users.uu_id == token_dict.user_uu_id
).data
if not found_user:
return ResponseHandler.not_found("User not found")
user_token = UsersTokens.filter_one(
UsersTokens.domain == found_user.domain_name,
UsersTokens.user_id == found_user.id,
UsersTokens.token_type == "RememberMe",
).data
# Update user metadata
TokenService.update_user_metadata(found_user, request)
response_data = {
"access_token": access_token,
"refresh_token": getattr(user_token, "token", None),
"user": found_user.get_dict()
}
return ResponseHandler.success(
"User info refreshed successfully",
data=response_data,
response_model=AuthenticationRefreshResponse
)
except Exception as e:
return ResponseHandler.error(str(e))
class AuthenticationChangePasswordEventMethods(MethodToEvent):
event_type = "LOGIN"
event_description = "Change password with access token implemented on request headers without password reset token"
event_description = "Change password with access token"
event_category = "AUTHENTICATION"
__event_keys__ = {
@@ -364,31 +375,38 @@ class AuthenticationChangePasswordEventMethods(MethodToEvent):
@classmethod
def authentication_change_password(
cls,
request: Request,
data: ChangePassword,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
if isinstance(token_dict, EmployeeTokenObject):
if found_user := Users.filter_one(Users.uu_id == token_dict.uu_id).data:
if found_user.check_password(data.old_password):
found_user.set_password(data.new_password)
return JSONResponse(
content={
"completed": True,
"message": "Password is changed successfully",
},
status_code=status.HTTP_200_OK,
)
return JSONResponse(
content={
"completed": False,
"message": "Old password is not correct",
},
status_code=status.HTTP_401_UNAUTHORIZED,
try:
if not isinstance(token_dict, EmployeeTokenObject):
return ResponseHandler.unauthorized("Only employees can change password")
found_user = Users.filter_one(Users.uu_id == token_dict.user_uu_id).data
if not found_user:
return ResponseHandler.not_found("User not found")
if not found_user.check_password(data.old_password):
user_logger.log_password_change(
request, found_user.id, "change",
success=False, error="Invalid old password"
)
return JSONResponse(
content={"completed": False, "message": "Invalid data"},
status_code=status.HTTP_401_UNAUTHORIZED,
)
return ResponseHandler.unauthorized("Old password is incorrect")
found_user.set_password(data.new_password)
user_logger.log_password_change(
request, found_user.id, "change",
success=True
)
return ResponseHandler.success("Password changed successfully")
except Exception as e:
user_logger.log_password_change(
request, found_user.id if found_user else None,
"change", success=False, error=str(e)
)
return ResponseHandler.error(str(e))
class AuthenticationCreatePasswordEventMethods(MethodToEvent):
@@ -426,22 +444,11 @@ class AuthenticationCreatePasswordEventMethods(MethodToEvent):
raise HTTPException(
status_code=400, detail="Email can not be sent. Try again later"
)
return JSONResponse(
content={
"completed": True,
"message": "Password is created successfully",
"data": found_user.get_dict(),
},
status_code=status.HTTP_200_OK,
return ResponseHandler.success(
"Password is created successfully",
data=found_user.get_dict(),
)
return JSONResponse(
content={
"completed": False,
"message": "Record not found",
"data": {},
},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Record not found")
class AuthenticationDisconnectUserEventMethods(MethodToEvent):
@@ -463,35 +470,21 @@ class AuthenticationDisconnectUserEventMethods(MethodToEvent):
):
found_user = Users.filter_one(Users.uu_id == token_dict.user_uu_id).data
if not found_user:
return JSONResponse(
content={
"completed": False,
"message": "Invalid data",
"data": None,
},
status_code=status.HTTP_202_ACCEPTED,
)
if already_tokens := get_object_via_user_uu_id(user_id=str(found_user.uu_id)):
return ResponseHandler.not_found("User not found")
if already_tokens := RedisActions.get_object_via_user_uu_id(user_id=str(found_user.uu_id)):
for key, token_user in already_tokens.items():
redis_cli.delete(key)
RedisActions.delete_key(key)
selected_user = Users.filter_one(
Users.uu_id == token_user.get("uu_id"),
).data
selected_user.remove_refresher_token(
domain=data.domain, disconnect=True
)
return JSONResponse(
content={
"completed": True,
"message": "All sessions are disconnected",
"data": selected_user.get_dict(),
},
status_code=status.HTTP_200_OK,
return ResponseHandler.success(
"All sessions are disconnected",
data=selected_user.get_dict(),
)
return JSONResponse(
content={"completed": False, "message": "Invalid data", "data": None},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Invalid data")
class AuthenticationLogoutEventMethods(MethodToEvent):
@@ -512,32 +505,21 @@ class AuthenticationLogoutEventMethods(MethodToEvent):
cls, request: Request, data: Logout, token_dict: dict = None
):
token_user = None
if already_tokens := get_object_via_access_key(request=request):
if already_tokens := RedisActions.get_object_via_access_key(request=request):
for key in already_tokens:
token_user = json.loads(redis_cli.get(key) or {})
token_user = json.loads(RedisActions.get_key(key) or {})
if token_user.get("domain") == data.domain:
redis_cli.delete(key)
RedisActions.delete_key(key)
selected_user = Users.filter_one(
Users.uu_id == token_user.get("uu_id"),
).data
selected_user.remove_refresher_token(domain=data.domain)
return JSONResponse(
content={
"completed": True,
"message": "Session is logged out",
"data": token_user,
},
status_code=status.HTTP_200_OK,
return ResponseHandler.success(
"Session is logged out",
data=token_user,
)
return JSONResponse(
content={
"completed": False,
"message": "Logout is not successfully completed",
"data": None,
},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Logout is not successfully completed")
class AuthenticationRefreshTokenEventMethods(MethodToEvent):
@@ -550,7 +532,7 @@ class AuthenticationRefreshTokenEventMethods(MethodToEvent):
"c90f3334-10c9-4181-b5ff-90d98a0287b2": "authentication_refresher_token",
}
__event_validation__ = {
"c90f3334-10c9-4181-b5ff-90d98a0287b2": "authentication_refresher_token",
"c90f3334-10c9-4181-b5ff-90d98a0287b2": AuthenticationRefreshResponse,
}
@classmethod
@@ -563,10 +545,7 @@ class AuthenticationRefreshTokenEventMethods(MethodToEvent):
**UsersTokens.valid_record_dict,
).data
if not token_refresher:
return JSONResponse(
content={"completed": False, "message": "Invalid data", "data": {}},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Invalid data")
if found_user := Users.filter_one(
Users.id == token_refresher.user_id,
).data:
@@ -580,24 +559,16 @@ class AuthenticationRefreshTokenEventMethods(MethodToEvent):
request, "remote_addr", None
) or request.headers.get("X-Forwarded-For", None)
found_user.last_seen = str(system_arrow.now())
return JSONResponse(
content={
"completed": True,
"message": "User is logged in successfully via refresher token",
"data": load_user_with_erp_details(
found_user,
{
"access_token": access_key,
"refresh_token": data.refresh_token,
},
),
},
status_code=status.HTTP_200_OK,
response_data = {
"access_token": access_key,
"refresh_token": data.refresh_token,
}
return ResponseHandler.success(
"User is logged in successfully via refresher token",
data=response_data,
response_model=AuthenticationRefreshResponse
)
return JSONResponse(
content={"completed": False, "message": "Invalid data", "data": {}},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Invalid data")
class AuthenticationForgotPasswordEventMethods(MethodToEvent):
@@ -641,13 +612,9 @@ class AuthenticationForgotPasswordEventMethods(MethodToEvent):
found_user.password_token_is_valid = str(system_arrow.shift(days=1))
found_user.save()
return JSONResponse(
content={
"completed": True,
"message": "Password is change link is sent to your email or phone",
"data": {},
},
status_code=status.HTTP_200_OK,
return ResponseHandler.success(
"Password is change link is sent to your email or phone",
data={},
)
@@ -687,13 +654,9 @@ class AuthenticationResetPasswordEventMethods(MethodToEvent):
raise found_user.raise_http_exception(
status_code=400, message="Email can not be sent. Try again later"
)
return JSONResponse(
content={
"completed": True,
"message": "Password change link is sent to your email or phone",
"data": found_user.get_dict(),
},
status_code=status.HTTP_200_OK,
return ResponseHandler.success(
"Password change link is sent to your email or phone",
data=found_user.get_dict(),
)
@@ -707,7 +670,7 @@ class AuthenticationDownloadAvatarEventMethods(MethodToEvent):
"c140cd5f-307f-4046-a93e-3ade032a57a7": "authentication_download_avatar",
}
__event_validation__ = {
"c140cd5f-307f-4046-a93e-3ade032a57a7": "authentication_download_avatar",
"c140cd5f-307f-4046-a93e-3ade032a57a7": AuthenticationUserInfoResponse,
}
@classmethod
@@ -722,26 +685,21 @@ class AuthenticationDownloadAvatarEventMethods(MethodToEvent):
system_arrow.now() - system_arrow.get(str(found_user.expiry_ends))
).days
return JSONResponse(
content={
"completed": True,
"message": "Avatar and profile is shared via user credentials",
"data": {
"lang": token_dict.lang,
"full_name": found_user.person.full_name,
"avatar": found_user.avatar,
"remember_me": found_user.remember_me,
"expiry_ends": str(found_user.expiry_ends),
"expired_str": expired_starts,
"expired_int": int(expired_int),
},
},
status_code=status.HTTP_200_OK,
user_info = {
"lang": token_dict.lang,
"full_name": found_user.person.full_name,
"avatar": found_user.avatar,
"remember_me": found_user.remember_me,
"expiry_ends": str(found_user.expiry_ends),
"expired_str": expired_starts,
"expired_int": int(expired_int),
}
return ResponseHandler.success(
"Avatar and profile is shared via user credentials",
data=user_info,
response_model=AuthenticationUserInfoResponse
)
return JSONResponse(
content={"completed": False, "message": "Invalid data", "data": {}},
status_code=status.HTTP_202_ACCEPTED,
)
return ResponseHandler.not_found("Invalid data")
AuthenticationLoginEventMethod = AuthenticationLoginEventMethods(
@@ -780,65 +738,3 @@ AuthenticationDownloadAvatarEventMethod = AuthenticationDownloadAvatarEventMetho
AuthenticationResetPasswordEventMethod = AuthenticationResetPasswordEventMethods(
action=ActionsSchema(endpoint="/authentication/reset_password")
)
# UserLogger.log_error(
# str(
# dict(
# user_id=found_user.id,
# domain=data.domain,
# access_key=token_user.get("access_input"),
# agent=request.headers.get("User-Agent", None),
# ip=getattr(request, "remote_addr", None)
# or request.headers.get("X-Forwarded-For", None),
# platform=request.headers.get("Origin", None),
# login_date=datetime.datetime.utcnow().__str__(),
# is_login=False,
# )
# )
# )
# UserLogger.log_error(
# str(
# dict(
# user_id=found_user.id,
# domain=data.domain,
# access_key=data.access_key,
# agent=request.headers.get("User-Agent", None),
# ip=getattr(request, "remote_addr", None)
# or request.headers.get("X-Forwarded-For", None),
# platform=request.headers.get("Origin", None),
# login_date=str(DateTimeLocal.now()),
# is_login=False,
# )
# )
# )
# UserLogger.log_error(
# str(
# dict(
# user_id=found_user.id,
# domain=data.domain,
# access_key="via_refresher",
# agent=request.headers.get("User-Agent", None),
# ip=getattr(request, "remote_addr", None)
# or request.headers.get("X-Forwarded-For", None),
# platform=request.headers.get("Origin", None),
# login_date=datetime.datetime.utcnow().__str__(),
# is_login=False,
# )
# )
# )
# UserLogger.log_error(
# str(
# dict(
# user_id=selected_user.id,
# domain=data.domain,
# access_key=token_user.get("access_input"),
# agent=request.headers.get("User-Agent", None),
# ip=getattr(request, "remote_addr", None)
# or request.headers.get("X-Forwarded-For", None),
# platform=request.headers.get("Origin", None),
# login_date=datetime.datetime.utcnow().__str__(),
# is_login=False,
# )
# )
# )

View File

@@ -21,7 +21,7 @@ from api_validations.validations_request import (
)
from api_validations.validations_response import ListBuildingResponse
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
@@ -57,9 +57,8 @@ class BuildListEventMethods(MethodToEvent):
records = Build.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Building Records are listed",
message="Building records listed successfully",
result=records,
response_model=ListBuildingResponse,
)
@@ -124,20 +123,17 @@ class BuildCreateEventMethods(MethodToEvent):
created_build.save()
man_build_part.update(is_confirmed=True)
man_build_part.save()
# created_build_relation = RelationshipEmployee2Build.find_or_create(
# company_id=token_dict.selected_company.company_id,
# member_id=created_build.id,
# employee_id=token_dict.selected_company.employee_id,
# )
# created_build_relation.update(is_confirmed=True)
# created_build_relation.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Build record completed. This build is assigned to you.",
"data": created_build.get_dict(),
},
status_code=status.HTTP_200_OK,
relationship = RelationshipEmployee2Build.find_or_create(
employee_id=token_dict.selected_company.employee_id,
build_id=created_build.id,
company_id=token_dict.selected_company.company_id,
)
relationship.save()
return AlchemyJsonResponse(
completed=True,
message="Building created successfully",
result=created_build.get_dict(),
)
@classmethod
@@ -166,20 +162,17 @@ class BuildCreateEventMethods(MethodToEvent):
)
created_build = Build.create_action(data=data, token=token_dict)
created_build_relation = RelationshipEmployee2Build.find_or_create(
company_id=token_dict.selected_company.company_id,
member_id=created_build.id,
relationship = RelationshipEmployee2Build.find_or_create(
employee_id=token_dict.selected_company.employee_id,
build_id=created_build.id,
company_id=token_dict.selected_company.company_id,
)
created_build.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Build record completed. This build is assigned to you.",
"data": created_build.get_dict(),
},
status_code=status.HTTP_200_OK,
relationship.save()
return AlchemyJsonResponse(
completed=True,
message="Building created successfully",
result=created_build.get_dict(),
)
@@ -205,44 +198,30 @@ class BuildUpdateEventMethods(MethodToEvent):
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
if isinstance(token_dict, OccupantTokenObject):
Build.pre_query = Build.select_action(
employee_id=token_dict.selected_company.employee_id
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Occupant cannot update building",
)
updated_build = Build.update_action(
data=data, token=token_dict, build_uu_id=build_uu_id
Build.pre_query = Build.select_action(
employee_id=token_dict.selected_company.employee_id
)
build = Build.filter_one(Build.uu_id == build_uu_id).data
if not build:
return AlchemyJsonResponse(
completed=False,
message="Building not found",
result={},
status_code="HTTP_404_NOT_FOUND"
)
Build.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Build record",
"data": updated_build.get_dict(),
},
status_code=status.HTTP_200_OK,
)
elif isinstance(token_dict, EmployeeTokenObject):
find_one_build = Build.filter_one(
Build.uu_id == build_uu_id,
).data
access_authorized_build = Build.select_action(
employee_id=token_dict.selected_company.employee_id,
filter_expr=[Build.id == find_one_build.id],
)
if access_authorized_build.count:
updated_build = Build.update_action(
data=data, token=token_dict, build_uu_id=build_uu_id
)
return JSONResponse(
content={
"completed": True,
"message": "Update Build record",
"data": updated_build.get_dict(),
},
status_code=status.HTTP_200_OK,
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"This user can not modify {build_uu_id} - building.",
build.update(**data.excluded_dump())
build.save()
return AlchemyJsonResponse(
completed=True,
message="Building updated successfully",
result=build.get_dict(),
)
@@ -261,36 +240,31 @@ class BuildPatchEventMethods(MethodToEvent):
@classmethod
def build_patch(cls, build_uu_id: str, data: PatchRecord, token_dict):
find_one_build = Build.filter_one(
Build.uu_id == build_uu_id,
)
access_authorized_build = Build.select_action(
employee_id=token_dict.selected_company.employee_id,
filter_expr=[Build.id == find_one_build.id],
)
if access_authorized_build.count:
action = data.excluded_dump()
find_one_build.active = bool(action.get("active", find_one_build.active))
find_one_build.is_confirmed = bool(
action.get("confirm", find_one_build.is_confirmed)
if isinstance(token_dict, OccupantTokenObject):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Occupant cannot patch building",
)
find_one_build.deleted = bool(action.get("delete", find_one_build.deleted))
find_one_build.save()
return JSONResponse(
content={
"completed": True,
"message": "Patch Build record completed",
"data": find_one_build.get_dict(),
},
status_code=status.HTTP_200_OK,
Build.pre_query = Build.select_action(
employee_id=token_dict.selected_company.employee_id
)
build = Build.filter_one(Build.uu_id == build_uu_id).data
if not build:
return AlchemyJsonResponse(
completed=False,
message="Building not found",
result={},
status_code="HTTP_404_NOT_FOUND"
)
return JSONResponse(
content={
"completed": False,
"message": "Patch Build record failed",
"data": {},
},
status_code=status.HTTP_200_OK,
build.update(**data.excluded_dump())
build.save()
return AlchemyJsonResponse(
completed=True,
message="Building patched successfully",
result=build.get_dict(),
)

View File

@@ -11,7 +11,9 @@ from api_validations.validations_request import (
ListOptions,
)
from api_validations.core_response import AlchemyJsonResponse
from api_validations.validations_response.building_responses import BuildAreaListResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
@@ -23,7 +25,7 @@ class BuildAreaListEventMethods(MethodToEvent):
"0bb51845-65a2-4340-8872-a3b5aad95468": "build_area_list",
}
__event_validation__ = {
"0bb51845-65a2-4340-8872-a3b5aad95468": None,
"0bb51845-65a2-4340-8872-a3b5aad95468": BuildAreaListResponse,
}
@classmethod
@@ -49,7 +51,12 @@ class BuildAreaListEventMethods(MethodToEvent):
BuildArea.filter_attr = list_options
records = BuildArea.filter_all()
return AlchemyJsonResponse(
completed=True, message="List of Build Area", result=records
completed=True,
message="Building areas listed successfully",
result=records,
cls_object=BuildArea,
filter_attributes=list_options,
response_model=BuildAreaListResponse
)
@@ -103,14 +110,11 @@ class BuildAreaCreateEventMethods(MethodToEvent):
data_dict["build_id"] = selected_build.id
data_dict["build_uu_id"] = str(selected_build.uu_id)
created_build_part = BuildArea.find_or_create(**data_dict)
created_build_part.save()
created_build_part.update(is_confirmed=True)
created_build_part.save()
area = BuildArea.insert_one(data_dict).data
return AlchemyJsonResponse(
completed=True,
message="Created Build Area",
result=created_build_part.get_dict(),
message="Building area created successfully",
result=area
)
@@ -131,10 +135,11 @@ class BuildAreaUpdateEventMethods(MethodToEvent):
data: UpdateBuildArea,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
area = BuildArea.update_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Update Build record",
result=None,
completed=True,
message="Building area updated successfully",
result=area
)
@@ -155,10 +160,11 @@ class BuildAreaPatchEventMethods(MethodToEvent):
data,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
area = BuildArea.patch_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Patch Build record",
result=None,
completed=True,
message="Building area patched successfully",
result=area
)

View File

@@ -10,7 +10,7 @@ from databases import (
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_validations.validations_request import (
InsertBuildParts,
@@ -46,11 +46,8 @@ class BuildingBuildPartsListEventMethods(MethodToEvent):
records = BuildParts.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Building Parts Records are listed",
message="Building parts listed successfully",
result=records,
cls_object=BuildParts,
response_model=BuildPartsListResponse,
filter_attributes=list_options,
)
@@ -72,13 +69,10 @@ class BuildingBuildPartsCreateEventMethods(MethodToEvent):
created_build.save()
created_build.update(is_confirmed=True)
created_build.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Build Parts record",
"data": created_build.get_dict(),
},
status_code=status.HTTP_200_OK,
return AlchemyJsonResponse(
completed=True,
message="Building part created successfully",
result=created_build,
)
@@ -98,13 +92,10 @@ class BuildingBuildPartsUpdateEventMethods(MethodToEvent):
):
updated_build = BuildParts.update_action(data=data, token=token_dict)
updated_build.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Build Parts record",
"data": updated_build,
},
status_code=status.HTTP_200_OK,
return AlchemyJsonResponse(
completed=True,
message="Building part updated successfully",
result=updated_build,
)
@@ -133,21 +124,15 @@ class BuildingBuildPartsPatchEventMethods(MethodToEvent):
)
find_one_build.deleted = bool(action.get("delete", find_one_build.deleted))
find_one_build.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Build Parts record",
"data": find_one_build.get_dict(),
},
status_code=status.HTTP_200_OK,
return AlchemyJsonResponse(
completed=True,
message="Building part patched successfully",
result=find_one_build,
)
return JSONResponse(
content={
"completed": False,
"message": "Update Build Parts record",
"data": {},
},
status_code=status.HTTP_200_OK,
return AlchemyJsonResponse(
completed=False,
message="Building part patched failed",
result={},
)

View File

@@ -11,10 +11,11 @@ from api_validations.validations_request import (
ListOptions,
)
from api_validations.core_response import AlchemyJsonResponse
from api_validations.validations_response.building_responses import BuildSitesListResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from databases.sql_models.identity.identity import Addresses
class BuildSitesListEventMethods(MethodToEvent):
@@ -24,7 +25,7 @@ class BuildSitesListEventMethods(MethodToEvent):
"6798414c-6c7d-47f0-9d8b-6935a0f51c2e": "build_sites_list",
}
__event_validation__ = {
"6798414c-6c7d-47f0-9d8b-6935a0f51c2e": None,
"6798414c-6c7d-47f0-9d8b-6935a0f51c2e": BuildSitesListResponse,
}
@classmethod
@@ -58,7 +59,12 @@ class BuildSitesListEventMethods(MethodToEvent):
BuildSites.filter_attr = list_options
records = BuildSites.filter_all()
return AlchemyJsonResponse(
completed=True, message="Update Build record", result=records
completed=True,
message="Building sites listed successfully",
result=records,
cls_object=BuildSites,
filter_attributes=list_options,
response_model=BuildSitesListResponse
)
@@ -102,14 +108,11 @@ class BuildSitesCreateEventMethods(MethodToEvent):
},
)
data_dict = data.excluded_dump()
created_build_part = BuildSites.find_or_create(**data_dict)
created_build_part.save()
created_build_part.update(is_confirmed=True)
created_build_part.save()
site = BuildSites.insert_one(data_dict).data
return AlchemyJsonResponse(
completed=True,
message="Update Build record",
result=created_build_part,
message="Building site created successfully",
result=site
)
@@ -130,10 +133,11 @@ class BuildSitesUpdateEventMethods(MethodToEvent):
data: UpdateBuildArea,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
site = BuildSites.update_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Update Build record",
result=None,
completed=True,
message="Building site updated successfully",
result=site
)
@@ -154,10 +158,11 @@ class BuildSitesPatchEventMethods(MethodToEvent):
data,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
site = BuildSites.patch_one(build_uu_id, data).data
return AlchemyJsonResponse(
completed=False,
message="Patch Build record",
result=None,
completed=True,
message="Building site patched successfully",
result=site
)

View File

@@ -2,10 +2,11 @@ from typing import Union
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_validations.validations_request import (
ListOptions,
)
from api_validations.validations_response.building_responses import BuildTypesListResponse
from databases.sql_models.building.build import BuildTypes
@@ -15,7 +16,9 @@ class BuildTypesListEventMethods(MethodToEvent):
__event_keys__ = {
"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": "build_types_list",
}
__event_validation__ = {"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": None}
__event_validation__ = {
"5344d03c-fc47-43ec-8c44-6c2acd7e5d9f": BuildTypesListResponse
}
@classmethod
def build_types_list(
@@ -30,16 +33,23 @@ class BuildTypesListEventMethods(MethodToEvent):
results = BuildTypes.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Building types listed successfully",
result=results,
message="Build Types are listed successfully",
cls_object=BuildTypes,
filter_attributes=list_options,
response_model=BuildTypesListResponse
)
elif isinstance(token_dict, OccupantTokenObject):
raise HTTPException(
status_code=403, detail="You are not authorized to access this endpoint"
return AlchemyJsonResponse(
completed=False,
message="You are not authorized to access this endpoint",
result=None
)
else:
raise HTTPException(
status_code=403, detail="You are not authorized to access this endpoint"
return AlchemyJsonResponse(
completed=False,
message="You are not authorized to access this endpoint",
result=None
)

View File

@@ -5,7 +5,6 @@ from api_events.events.events.events_bind_services import (
ServiceBindOccupantEventMethods,
)
from databases import (
Modules,
BuildParts,
Build,
BuildLivingSpace,
@@ -14,7 +13,7 @@ from databases import (
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_validations.validations_request import (
InsertBuildLivingSpace,
UpdateBuildLivingSpace,
@@ -71,6 +70,11 @@ class BuildingLivingSpacesListEventMethods(MethodToEvent):
).query
BuildLivingSpace.filter_attr = list_options
records = BuildLivingSpace.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Living spaces listed successfully",
result=records
)
elif isinstance(token_dict, EmployeeTokenObject):
build_id_list_query = Build.select_action(
employee_id=token_dict.selected_company.employee_id
@@ -101,14 +105,11 @@ class BuildingLivingSpacesListEventMethods(MethodToEvent):
).query
BuildLivingSpace.filter_attr = list_options
records = BuildLivingSpace.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Building Living Spaces are listed successfully",
result=records,
response_model=LivingSpaceListResponse,
cls_object=BuildLivingSpace,
filter_attributes=list_options,
)
return AlchemyJsonResponse(
completed=True,
message="Living spaces listed successfully",
result=records
)
class BuildingLivingSpacesCreateEventMethods(MethodToEvent):
@@ -210,7 +211,11 @@ class BuildingLivingSpacesCreateEventMethods(MethodToEvent):
build_living_space_id=created_living_space.id,
service_id=occupants_service.id,
)
return created_living_space
return AlchemyJsonResponse(
completed=True,
message="Living space created successfully",
result=created_living_space
)
class BuildingLivingSpacesUpdateEventMethods(MethodToEvent):
@@ -295,6 +300,13 @@ class BuildingLivingSpacesUpdateEventMethods(MethodToEvent):
data_dict["owner_person_id"] = life_person.id
del data_dict["build_parts_uu_id"], data_dict["life_person_uu_id"]
living_space = BuildLivingSpace.update_one(build_uu_id, data_dict).data
return AlchemyJsonResponse(
completed=True,
message="Living space updated successfully",
result=living_space
)
BuildingLivingSpacesListEventMethod = BuildingLivingSpacesListEventMethods(
action=ActionsSchema(endpoint="/building/living_space/list")

View File

@@ -12,9 +12,11 @@ from api_validations.validations_request import (
PatchRecord,
)
from api_validations.validations_response.company_responses import CompanyListResponse
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class CompanyListEventMethods(MethodToEvent):
@@ -23,7 +25,7 @@ class CompanyListEventMethods(MethodToEvent):
__event_keys__ = {
"f6900cb5-ac5b-478e-8e7c-fa87e65cd2e5": "company_list",
}
__event_validation__ = {"f6900cb5-ac5b-478e-8e7c-fa87e65cd2e5": None}
__event_validation__ = {"f6900cb5-ac5b-478e-8e7c-fa87e65cd2e5": CompanyListResponse}
@classmethod
def company_list(
@@ -46,8 +48,11 @@ class CompanyListEventMethods(MethodToEvent):
records = Companies.filter_all()
return AlchemyJsonResponse(
completed=True,
message="Building Living Spaces are listed successfully",
message="Companies listed successfully",
result=records,
cls_object=Companies,
filter_attributes=list_options,
response_model=CompanyListResponse
)
@@ -65,18 +70,15 @@ class CompanyCreateEventMethods(MethodToEvent):
data: InsertCompany,
token_dict: EmployeeTokenObject,
):
created_company = Companies.create_action(data=data, token=token_dict)
created_company = Companies.insert_one(data).data
created_company.update(
related_company=token_dict.selected_company.company_uu_id
)
created_company.save()
return JSONResponse(
content={
"completed": True,
"message": "Create Company record",
"data": created_company.get_dict(),
},
status_code=status.HTTP_200_OK,
return AlchemyJsonResponse(
completed=True,
message="Company created successfully",
result=created_company.get_dict(),
)
@@ -100,27 +102,19 @@ class CompanyUpdateEventMethods(MethodToEvent):
token_dict.selected_company.duty_id,
],
)
find_one_company = Companies.filter_one(
Companies.uu_id == company_uu_id,
).data
if not find_one_company:
return JSONResponse(
content={
"completed": True,
"message": "Update Company record",
"data": {},
},
status_code=200,
company = Companies.update_one(company_uu_id, data).data
if not company:
return AlchemyJsonResponse(
completed=False,
message="Company not found",
result={},
status_code="HTTP_404_NOT_FOUND"
)
updated_company = find_one_company.update(**data.excluded_dump())
Companies.save()
return JSONResponse(
content={
"completed": True,
"message": "Update Company record",
"data": updated_company,
},
status_code=200,
company.save()
return AlchemyJsonResponse(
completed=True,
message="Company updated successfully",
result=company.get_dict(),
)
@@ -136,42 +130,25 @@ class CompanyPatchEventMethods(MethodToEvent):
def company_patch(
cls, company_uu_id: str, data: PatchRecord, token_dict: EmployeeTokenObject
):
find_one_company = Companies.filter_one(
Companies.uu_id == company_uu_id,
).data
access_authorized_company = Companies.select_action(
Companies.pre_query = Companies.select_action(
duty_id_list=[
token_dict.selected_company.bulk_duties_id,
token_dict.selected_company.duty_id,
],
)
if access_authorized_company.count:
action = data.excluded_dump()
find_one_company.active = bool(
action.get("active", find_one_company.active)
company = Companies.patch_one(company_uu_id, data).data
if not company:
return AlchemyJsonResponse(
completed=False,
message="Company not found",
result={},
status_code="HTTP_404_NOT_FOUND"
)
find_one_company.is_confirmed = bool(
action.get("confirm", find_one_company.is_confirmed)
)
find_one_company.deleted = bool(
action.get("delete", find_one_company.deleted)
)
find_one_company.save()
return JSONResponse(
content={
"completed": True,
"message": "Patch Company record completed",
"data": find_one_company.get_dict(),
},
status_code=status.HTTP_200_OK,
)
return JSONResponse(
content={
"completed": False,
"message": "Patch Company record failed",
"data": {},
},
status_code=status.HTTP_200_OK,
company.save()
return AlchemyJsonResponse(
completed=True,
message="Company patched successfully",
result=company.get_dict(),
)

View File

@@ -13,7 +13,7 @@ from databases import Departments
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class DepartmentListEventMethods(MethodToEvent):

View File

@@ -1,7 +1,7 @@
from fastapi import status
from fastapi.responses import JSONResponse
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_validations.validations_request import (
InsertDuties,
UpdateDuties,

View File

@@ -10,8 +10,8 @@ from api_validations.validations_request import (
from databases import Duty
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_objects.auth.token_objects import EmployeeTokenObject
from ApiServices.api_handlers import AlchemyJsonResponse
class DutyListEventMethods(MethodToEvent):

View File

@@ -12,8 +12,8 @@ from api_validations.validations_request import (
from databases import Employees, Staff, People, EmployeeHistory
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_objects.auth.token_objects import EmployeeTokenObject
from ApiServices.api_handlers import AlchemyJsonResponse
class EmployeeListEventMethods(MethodToEvent):

View File

@@ -13,7 +13,7 @@ from databases import Staff, Duties
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class StaffListEventMethods(MethodToEvent):

View File

@@ -17,7 +17,7 @@ from api_validations.validations_request import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow

View File

@@ -23,13 +23,12 @@ from databases import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow, client_arrow
from ApiServices.api_handlers import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow
from api_validations.validations_request import (
InsertBuildDecisionBookItems,
ListOptions,
ListDecisionBook,
)
from databases.sql_models.event.event import Services

View File

@@ -1,24 +1,13 @@
import typing
from databases import (
Build,
BuildParts,
BuildDecisionBook,
BuildDecisionBookItems,
BuildDecisionBookPerson,
BuildDecisionBookPayments,
BuildDecisionBookProjects,
BuildDecisionBookProjectPerson,
ApiEnumDropdown,
OccupantTypes,
Companies,
BuildLivingSpace,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_events.events.abstract_class import MethodToEvent
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow, client_arrow
from ApiServices.api_handlers import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow
class DecisionBookDecisionBookItemsDebitsListEventMethods(MethodToEvent):

View File

@@ -11,7 +11,6 @@ from databases import (
BuildLivingSpace,
BuildParts,
BuildDecisionBookPersonOccupants,
People,
OccupantTypes,
)
@@ -25,7 +24,6 @@ from api_validations.validations_request import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
class DecisionBookPersonListEventMethods(MethodToEvent):

View File

@@ -13,7 +13,6 @@ from databases import (
BuildDecisionBookPersonOccupants,
OccupantTypes,
Users,
ApiEnumDropdown,
)
from api_validations.validations_request import (
@@ -22,7 +21,6 @@ from api_validations.validations_request import (
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_library.date_time_actions.date_functions import system_arrow

View File

@@ -1,20 +1,14 @@
from typing import Union
from fastapi.responses import JSONResponse
from fastapi import status
from api_validations.validations_response.parts import BuildPartsListResponse
from databases import (
Build,
BuildParts,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_events.events.abstract_class import MethodToEvent
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_validations.validations_request import (
InsertBuildParts,
UpdateBuildParts,
ListOptions,
)
from databases.sql_models.building.decision_book import BuildDecisionBookPayments

View File

@@ -16,10 +16,9 @@ from api_validations.validations_request import (
ApprovalsBuildDecisionBookProjects,
ListOptions,
)
from api_validations.core_response import AlchemyJsonResponse
from databases import Build, BuildLivingSpace, BuildParts, ApiEnumDropdown
from ApiServices.api_handlers import AlchemyJsonResponse
from databases import BuildLivingSpace, BuildParts, ApiEnumDropdown
from databases.sql_models.building.decision_book import (
BuildDecisionBookProjectItems,
BuildDecisionBookItems,
BuildDecisionBook,
)

View File

@@ -2,7 +2,6 @@ from typing import Union
from databases import (
BuildDecisionBookProjectItems,
BuildDecisionBookProjectPerson,
)
from api_validations.validations_request import (
@@ -13,7 +12,7 @@ from api_validations.validations_request import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from databases.sql_models.building.decision_book import BuildDecisionBookProjects

View File

@@ -13,7 +13,7 @@ from api_validations.validations_request import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class ProjectDecisionBookPersonListEventMethods(MethodToEvent):

View File

@@ -10,11 +10,7 @@ from api_validations.validations_request import (
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_events.events.events.events_bind_services import (
ServiceBindOccupantEventMethods,
)
from api_library.date_time_actions.date_functions import system_arrow
from api_validations.core_response import AlchemyJsonResponse
from databases.sql_models.company.employee import Employees
from databases.sql_models.event.event import Event2Occupant, Event2Employee

View File

@@ -6,7 +6,6 @@ from fastapi.exceptions import HTTPException
from api_library.date_time_actions.date_functions import system_arrow
from databases import (
Modules,
Employees,
BuildParts,
BuildLivingSpace,
@@ -21,10 +20,10 @@ from api_validations.validations_request import (
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
class ServiceBindOccupantEventMethods(MethodToEvent):
event_type = "UPDATE"
__event_keys__ = {
"0d2bc5c9-d4b1-4951-8305-69da4a687fdc": "bind_services_occupant",
@@ -70,7 +69,6 @@ class ServiceBindOccupantEventMethods(MethodToEvent):
data: RegisterServices2Occupant,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
):
from sqlalchemy.dialects.postgresql import insert
if isinstance(token_dict, EmployeeTokenObject):
raise HTTPException(

View File

@@ -2,7 +2,6 @@ from typing import Union
from fastapi.exceptions import HTTPException
from api_events.events.events.events_services import ServicesEvents
from databases import (
Events,
Employees,
@@ -20,7 +19,7 @@ from api_validations.validations_request import (
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class EventsListEventMethods(MethodToEvent):

View File

@@ -4,9 +4,7 @@ from api_validations.validations_request import (
ListOptions,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent
class ModelEvents(MethodToEvent):

View File

@@ -1,8 +1,6 @@
from api_validations.validations_request import DepartmentsPydantic, PatchRecord
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from api_events.events.abstract_class import MethodToEvent
class ModulesEvents(MethodToEvent):

View File

@@ -6,9 +6,8 @@ from api_validations.validations_request import (
ListOptions,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_events.events.abstract_class import MethodToEvent
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
class ServicesEvents(MethodToEvent):

View File

@@ -5,7 +5,6 @@ from fastapi.responses import JSONResponse
from api_validations.validations_response.people import PeopleListResponse
from databases import (
Build,
People,
Users,
Companies,
@@ -14,7 +13,7 @@ from databases import (
from api_validations.validations_request import InsertPerson, UpdateUsers
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
class PeopleListEventMethods(MethodToEvent):

View File

@@ -4,12 +4,12 @@ from fastapi import status
from fastapi.responses import JSONResponse
from api_configs import ApiStatic
from databases import MongoQueryIdentity, Users, Companies, People
from databases import MongoQueryIdentity, Users, Companies
from databases.no_sql_models.validations import DomainViaUser
from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import AlchemyJsonResponse
from ApiServices.api_handlers import AlchemyJsonResponse
from api_services.email.service import send_email
from api_services.templates.password_templates import change_your_password_template
from api_validations.validations_request import (
@@ -17,7 +17,6 @@ from api_validations.validations_request import (
UpdateUsers,
PatchRecord,
ListOptions,
RegisterServices2Occupant,
)