services are checked

This commit is contained in:
berkay 2024-11-08 17:14:02 +03:00
parent a5b1e0b2f4
commit c5b771e5cb
82 changed files with 1720 additions and 869 deletions

View File

@ -24,4 +24,4 @@ __all__ = [
"TestMongo", "TestMongo",
"RelationAccess", "RelationAccess",
"EmailConfig", "EmailConfig",
] ]

View File

@ -148,7 +148,7 @@ class EmailConfig:
EMAIL_USERNAME: str = "karatay@mehmetkaratay.com.tr" EMAIL_USERNAME: str = "karatay@mehmetkaratay.com.tr"
EMAIL_PASSWORD: str = "system" EMAIL_PASSWORD: str = "system"
class RelationAccess: class RelationAccess:
# 77 Evyos superuser of Superuser - 78 all company superuser - 98 Manager of 77 & 78 # 77 Evyos superuser of Superuser - 78 all company superuser - 98 Manager of 77 & 78
SuperAccessList = ["77", "78", "98"] SuperAccessList = ["77", "78", "98"]

View File

@ -50,9 +50,9 @@ class MethodToEvent(ABC, ActionsSchemaFactory):
@classmethod @classmethod
def ban_token_objects( def ban_token_objects(
cls, cls,
token: typing.Union[EmployeeTokenObject, OccupantTokenObject], token: typing.Union[EmployeeTokenObject, OccupantTokenObject],
ban_list: typing.Union[EmployeeTokenObject, OccupantTokenObject], ban_list: typing.Union[EmployeeTokenObject, OccupantTokenObject],
): ):
from fastapi import status from fastapi import status
from fastapi.exceptions import HTTPException from fastapi.exceptions import HTTPException

View File

@ -1,4 +1,5 @@
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
class ApiEvents(MethodToEvent): ... class ApiEvents(MethodToEvent): ...

View File

@ -13,7 +13,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
InsertAddress, InsertAddress,
InsertPostCode, InsertPostCode,
SearchAddress SearchAddress,
) )
from api_validations.core_response import return_json_response_from_alchemy from api_validations.core_response import return_json_response_from_alchemy
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
@ -224,7 +224,7 @@ class AddressPatchEventMethods(MethodToEvent):
def patch_address(cls, address_uu_id: str, data: InsertAddress, token_dict): def patch_address(cls, address_uu_id: str, data: InsertAddress, token_dict):
address = Addresses.find_one_or_abort(uu_id=address_uu_id) address = Addresses.find_one_or_abort(uu_id=address_uu_id)
post_code = RelationshipEmployee2PostCode.filter_one( post_code = RelationshipEmployee2PostCode.filter_one(
RelationshipEmployee2PostCode.member_id==address.post_code_id RelationshipEmployee2PostCode.member_id == address.post_code_id
) )
if not post_code: if not post_code:
raise HTTPException( raise HTTPException(

View File

@ -263,7 +263,6 @@ class AuthenticationRefreshEventMethods(MethodToEvent):
@classmethod @classmethod
def authentication_refresh_user_info(cls, request, token_dict: dict = None): def authentication_refresh_user_info(cls, request, token_dict: dict = None):
access_token = str(request.headers.get(Auth.ACCESS_TOKEN_TAG)) access_token = str(request.headers.get(Auth.ACCESS_TOKEN_TAG))
if token_user := get_object_via_access_key(request=request): if token_user := get_object_via_access_key(request=request):
if found_user := Users.find_one(uu_id=token_user.get("uu_id")): if found_user := Users.find_one(uu_id=token_user.get("uu_id")):
@ -620,7 +619,9 @@ class AuthenticationDownloadAvatarEventMethods(MethodToEvent):
found_user = Users.check_user_exits( found_user = Users.check_user_exits(
access_key=data.access_key, domain=data.domain access_key=data.access_key, domain=data.domain
) )
expired_str = str(system_arrow.now() - system_arrow.get(str(found_user.expiry_ends))) expired_str = str(
system_arrow.now() - system_arrow.get(str(found_user.expiry_ends))
)
expired_int = int( expired_int = int(
client_arrow.get( client_arrow.get(
system_arrow.now() - system_arrow.get(str(found_user.expiry_ends)) system_arrow.now() - system_arrow.get(str(found_user.expiry_ends))

View File

@ -17,7 +17,6 @@ from api_validations.validations_request import (
UpdateBuild, UpdateBuild,
PatchRecord, PatchRecord,
ListOptions, ListOptions,
) )
from api_validations.core_response import return_json_response_from_alchemy from api_validations.core_response import return_json_response_from_alchemy

View File

@ -147,7 +147,7 @@ class BuildingLivingSpacesPartsCreateEventMethods(MethodToEvent):
).first() ).first()
last_living_space = BuildLivingSpace.filter_one( last_living_space = BuildLivingSpace.filter_one(
BuildLivingSpace.id==living_space_id[0] if living_space_id else None BuildLivingSpace.id == living_space_id[0] if living_space_id else None
) )
data_dict["expiry_starts"] = str(system_arrow.now()) data_dict["expiry_starts"] = str(system_arrow.now())
@ -209,7 +209,9 @@ class BuildingLivingSpacesPartsUpdateEventMethods(MethodToEvent):
) )
living_space_id = BuildLivingSpace.session.execute(living_spaces).first() living_space_id = BuildLivingSpace.session.execute(living_spaces).first()
last_living_space = BuildLivingSpace.filter_one( last_living_space = BuildLivingSpace.filter_one(
BuildLivingSpace.id==getattr(living_space_id[0], "id", None) if living_space_id else None BuildLivingSpace.id == getattr(living_space_id[0], "id", None)
if living_space_id
else None
) )
data_dict["expiry_starts"] = str(system_arrow.now()) data_dict["expiry_starts"] = str(system_arrow.now())

View File

@ -93,7 +93,7 @@ class CompanyUpdateEventMethods(MethodToEvent):
@classmethod @classmethod
def company_update(cls, company_uu_id: str, data: UpdateCompany, token_dict): def company_update(cls, company_uu_id: str, data: UpdateCompany, token_dict):
find_one_company = Companies.filter_one(Companies.uu_id==company_uu_id) find_one_company = Companies.filter_one(Companies.uu_id == company_uu_id)
access_authorized_company = Companies.select_action( access_authorized_company = Companies.select_action(
duty_id=getattr(token_dict, "duty_id", 5), duty_id=getattr(token_dict, "duty_id", 5),
filter_expr=[Companies.id == token_dict.get("")], filter_expr=[Companies.id == token_dict.get("")],

View File

@ -25,12 +25,14 @@ class DepartmentListEventMethods(MethodToEvent):
@classmethod @classmethod
def department_list( def department_list(
cls, list_options: ListOptions, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
list_options: ListOptions,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
Departments.filter_attr = list_options Departments.filter_attr = list_options
records = Departments.filter_active( records = Departments.filter_active(
*Departments.get_smart_query(smart_query=list_options.query), *Departments.get_smart_query(smart_query=list_options.query),
Departments.company_id == token_dict.selected_company.company_id Departments.company_id == token_dict.selected_company.company_id,
) )
return return_json_response_from_alchemy( return return_json_response_from_alchemy(
response=records, pagination=list_options response=records, pagination=list_options
@ -81,7 +83,7 @@ class DepartmentUpdateEventMethods(MethodToEvent):
def department_update( def department_update(
cls, company_uu_id: str, data: DepartmentsPydantic, token_dict cls, company_uu_id: str, data: DepartmentsPydantic, token_dict
): ):
find_one_company = Departments.filter_one(Departments.uu_id==company_uu_id) find_one_company = Departments.filter_one(Departments.uu_id == company_uu_id)
access_authorized_company = Departments.select_action( access_authorized_company = Departments.select_action(
duty_id=getattr(token_dict, "duty_id", 5), duty_id=getattr(token_dict, "duty_id", 5),
filter_expr=[Departments.id == token_dict.get("")], filter_expr=[Departments.id == token_dict.get("")],

View File

@ -17,7 +17,6 @@ from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
class DutiesListEventMethods(MethodToEvent): class DutiesListEventMethods(MethodToEvent):
event_type = "SELECT" event_type = "SELECT"
@ -27,12 +26,14 @@ class DutiesListEventMethods(MethodToEvent):
@classmethod @classmethod
def duties_list( def duties_list(
cls, list_options: ListOptions, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
list_options: ListOptions,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
Duties.filter_attr = list_options Duties.filter_attr = list_options
records = Duties.filter_all( records = Duties.filter_all(
*Duties.get_smart_query(smart_query=list_options.query), *Duties.get_smart_query(smart_query=list_options.query),
Duties.company_id == token_dict.selected_company.company_id Duties.company_id == token_dict.selected_company.company_id,
) )
return { return {
"completed": True if records.count else False, "completed": True if records.count else False,
@ -50,10 +51,12 @@ class DutiesGetByUUIDEventMethods(MethodToEvent):
@classmethod @classmethod
def duties_get_by_uuid( def duties_get_by_uuid(
cls, data: SelectDuties, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: SelectDuties,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
duty = Duty.filter_one(Duty.uu_id==data.duty_uu_id).data duty = Duty.filter_one(Duty.uu_id == data.duty_uu_id).data
if not duty: if not duty:
return JSONResponse( return JSONResponse(
content={ content={
@ -93,10 +96,12 @@ class DutiesCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def duties_create( def duties_create(
cls, data: InsertDuties, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: InsertDuties,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
duty = Duty.filter_one(Duty.uu_id==data.duties_uu_id).data duty = Duty.filter_one(Duty.uu_id == data.duties_uu_id).data
department = Departments.filter_one(Duty.uu_id==data.department_uu_id).data department = Departments.filter_one(Duty.uu_id == data.department_uu_id).data
created_duties = Duties.find_or_create( created_duties = Duties.find_or_create(
company_id=token_dict.selected_company.company_id, company_id=token_dict.selected_company.company_id,

View File

@ -4,7 +4,9 @@ from fastapi import status
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
from api_validations.validations_request import ( from api_validations.validations_request import (
InsertCompanyDuty, PatchRecord, ListOptions InsertCompanyDuty,
PatchRecord,
ListOptions,
) )
from databases import Duty from databases import Duty
@ -23,7 +25,9 @@ class DutyListEventMethods(MethodToEvent):
@classmethod @classmethod
def duty_list( def duty_list(
cls, list_options: ListOptions, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
list_options: ListOptions,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
records = Duty.filter_active( records = Duty.filter_active(
*Duty.get_smart_query(list_options.query), *Duty.get_smart_query(list_options.query),
@ -42,7 +46,9 @@ class DutyCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def duty_create( def duty_create(
cls, data: InsertCompanyDuty, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: InsertCompanyDuty,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
created_duty = Duty.find_or_create(**data.excluded_dump()) created_duty = Duty.find_or_create(**data.excluded_dump())
Duty.save() Duty.save()
@ -64,7 +70,12 @@ class DutyUpdateEventMethods(MethodToEvent):
} }
@classmethod @classmethod
def duty_update(cls, company_uu_id: str, data, token_dict: Union[EmployeeTokenObject, OccupantTokenObject]): def duty_update(
cls,
company_uu_id: str,
data,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
find_one_company = Duty.find_one_or_abort(uu_id=company_uu_id) find_one_company = Duty.find_one_or_abort(uu_id=company_uu_id)
access_authorized_company = Duty.select_action( access_authorized_company = Duty.select_action(
duty_id=getattr(token_dict, "duty_id", 5), # ? duty_id=getattr(token_dict, "duty_id", 5), # ?
@ -104,9 +115,15 @@ class DutyPatchEventMethods(MethodToEvent):
) )
if access_authorized_company.count: if access_authorized_company.count:
action = data.excluded_dump() action = data.excluded_dump()
find_one_company.active = bool(action.get("active", find_one_company.active)) find_one_company.active = bool(
find_one_company.is_confirmed = bool(action.get("confirm", find_one_company.is_confirmed)) action.get("active", find_one_company.active)
find_one_company.deleted = bool(action.get("delete", find_one_company.deleted)) )
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() find_one_company.save()
return JSONResponse( return JSONResponse(
content={ content={

View File

@ -27,7 +27,9 @@ class EmployeeListEventMethods(MethodToEvent):
@classmethod @classmethod
def employee_list( def employee_list(
cls, list_options: ListOptions, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
list_options: ListOptions,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
Employees.filter_attr = list_options Employees.filter_attr = list_options
records = Employees.filter_active( records = Employees.filter_active(
@ -48,7 +50,9 @@ class EmployeeCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def employee_create( def employee_create(
cls, data: InsertEmployees, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: InsertEmployees,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
person = People.find_one(uu_id=data.people_uu_id) person = People.find_one(uu_id=data.people_uu_id)
staff = Staff.find_one(uu_id=data.staff_uu_id) staff = Staff.find_one(uu_id=data.staff_uu_id)
@ -124,7 +128,10 @@ class EmployeePatchEventMethods(MethodToEvent):
@classmethod @classmethod
def employee_patch( def employee_patch(
cls, employee_uu_id: str, data: PatchRecord, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
employee_uu_id: str,
data: PatchRecord,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
find_one_employee = Employees.find_one_or_abort(uu_id=employee_uu_id) find_one_employee = Employees.find_one_or_abort(uu_id=employee_uu_id)
access_authorized_employee = Employees.select_action( access_authorized_employee = Employees.select_action(

View File

@ -109,15 +109,15 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def iterate_over_build_parts( def iterate_over_build_parts(
cls, cls,
build_parts_list, build_parts_list,
payment_types, payment_types,
local_date, local_date,
end_date, end_date,
unit_price, unit_price,
unit_type, unit_type,
book_payment_dict, book_payment_dict,
unit_price_is_fixed unit_price_is_fixed,
): ):
start_date, payment_return_dict = local_date, {} start_date, payment_return_dict = local_date, {}
for build_part_single in build_parts_list: for build_part_single in build_parts_list:
@ -129,7 +129,9 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
unit_amount = str(build_part_single.due_part_key).replace(" ", "") unit_amount = str(build_part_single.due_part_key).replace(" ", "")
unit_amount = unit_amount.replace(str(unit_type).upper(), "") unit_amount = unit_amount.replace(str(unit_type).upper(), "")
payment_amount = abs(unit_price * float(unit_amount)) * -1 payment_amount = abs(unit_price * float(unit_amount)) * -1
payment_amount = -1 * (abs(payment_amount) + (50 - float(abs(payment_amount)) % 50)) payment_amount = -1 * (
abs(payment_amount) + (50 - float(abs(payment_amount)) % 50)
)
BuildDecisionBookPayments.create( BuildDecisionBookPayments.create(
build_parts_id=build_part_single.id, build_parts_id=build_part_single.id,
build_parts_uu_id=str(build_part_single.uu_id), build_parts_uu_id=str(build_part_single.uu_id),
@ -140,7 +142,7 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
process_date_m=int(local_date.month), process_date_m=int(local_date.month),
process_date_y=int(local_date.year), process_date_y=int(local_date.year),
period_time=f"{local_date.year}-{str(local_date.month).zfill(2)}", period_time=f"{local_date.year}-{str(local_date.month).zfill(2)}",
**book_payment_dict **book_payment_dict,
) )
local_date = local_date.shift(days=2) local_date = local_date.shift(days=2)
part_key = str(build_part_single.due_part_key).upper() part_key = str(build_part_single.due_part_key).upper()
@ -151,17 +153,17 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def create_payment_records_for_each_build_part( def create_payment_records_for_each_build_part(
cls, cls,
data_info_type, data_info_type,
build_id, build_id,
unit_price, unit_price,
unit_type, unit_type,
decision_book, decision_book,
decision_book_item, decision_book_item,
unit_price_is_fixed, unit_price_is_fixed,
currency, currency,
debit_start_date: str = None, debit_start_date: str = None,
debit_end_date: str = None, debit_end_date: str = None,
): ):
build_parts_list = BuildParts.filter_active( build_parts_list = BuildParts.filter_active(
BuildParts.human_livable == True, BuildParts.human_livable == True,
@ -176,8 +178,12 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
) )
payment_types = ApiEnumDropdown.get_debit_search(search_debit="DT-D") payment_types = ApiEnumDropdown.get_debit_search(search_debit="DT-D")
if data_info_type.key == "BDT-D": if data_info_type.key == "BDT-D":
local_date = system_arrow.get(system_arrow.get(decision_book.expiry_starts).date()) local_date = system_arrow.get(
end_date = system_arrow.get(system_arrow.get(decision_book.expiry_ends).date()) system_arrow.get(decision_book.expiry_starts).date()
)
end_date = system_arrow.get(
system_arrow.get(decision_book.expiry_ends).date()
)
cls.iterate_over_build_parts( cls.iterate_over_build_parts(
build_parts_list=build_parts_list.data, build_parts_list=build_parts_list.data,
payment_types=payment_types, payment_types=payment_types,
@ -212,8 +218,9 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
meeting_date = system_arrow.get(decision_book.meeting_date).date() meeting_date = system_arrow.get(decision_book.meeting_date).date()
already_book_projects = BuildDecisionBookProjects.filter_all( already_book_projects = BuildDecisionBookProjects.filter_all(
BuildDecisionBookProjects.build_decision_book_id==decision_book.id, BuildDecisionBookProjects.build_decision_book_id == decision_book.id,
BuildDecisionBookProjects.project_type==f"{decision_book.decision_type}_{data_info_type.key}", BuildDecisionBookProjects.project_type
== f"{decision_book.decision_type}_{data_info_type.key}",
) )
management_room = BuildParts.find_one( management_room = BuildParts.find_one(
build_id=build_id, part_no=0, active=True, is_confirmed=True build_id=build_id, part_no=0, active=True, is_confirmed=True
@ -222,7 +229,8 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
occupant_code="MT-VPR", occupant_category_type="MT" occupant_code="MT-VPR", occupant_category_type="MT"
) )
manager_living_space = BuildLivingSpace.filter_by_active( manager_living_space = BuildLivingSpace.filter_by_active(
build_parts_id=management_room.id, occupant_type=occupant_man.id, build_parts_id=management_room.id,
occupant_type=occupant_man.id,
) )
if not manager_living_space.data: if not manager_living_space.data:
raise HTTPException( raise HTTPException(
@ -245,10 +253,12 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
project_response_living_space_id=manager_living_space.id, project_response_living_space_id=manager_living_space.id,
project_response_living_space_uu_id=str(manager_living_space.uu_id), project_response_living_space_uu_id=str(manager_living_space.uu_id),
) )
book_project_created = BuildDecisionBookProjects.find_or_create(**book_project_dict) book_project_created = BuildDecisionBookProjects.find_or_create(
**book_project_dict
)
decision_book_item.update( decision_book_item.update(
item_comment=f"{book_project_created.project_no}_{book_project_created.project_name} " item_comment=f"{book_project_created.project_no}_{book_project_created.project_name} "
f"is assigned to {occupant_man.occupant_description}" f"is assigned to {occupant_man.occupant_description}"
) )
project_lead = ApiEnumDropdown.find_one( project_lead = ApiEnumDropdown.find_one(
key="PTT-LDR", enum_class="ProjectTeamTypes" key="PTT-LDR", enum_class="ProjectTeamTypes"
@ -332,13 +342,18 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, status_code=status.HTTP_400_BAD_REQUEST,
detail="Debit Start Date and Debit End Date is required for this payment type. " detail="Debit Start Date and Debit End Date is required for this payment type. "
"Check debit start date and debit end date and try again", "Check debit start date and debit end date and try again",
) )
data_dict["info_type_id"] = data_info_type.id data_dict["info_type_id"] = data_info_type.id
data_dict["info_type_uu_id"] = str(data_info_type.uu_id) data_dict["info_type_uu_id"] = str(data_info_type.uu_id)
unit_price, unit_type = float(data_dict["unit_price"]), str(data_dict["unit_type"]) unit_price, unit_type = float(data_dict["unit_price"]), str(
debit_start_date, debit_end_date = data_dict["debit_start_date"], data_dict["debit_end_date"] data_dict["unit_type"]
)
debit_start_date, debit_end_date = (
data_dict["debit_start_date"],
data_dict["debit_end_date"],
)
currency = data_dict["currency"] currency = data_dict["currency"]
del ( del (
data_dict["token"], data_dict["token"],
@ -347,10 +362,12 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
data_dict["unit_price_is_fixed"], data_dict["unit_price_is_fixed"],
data_dict["debit_start_date"], data_dict["debit_start_date"],
data_dict["debit_end_date"], data_dict["debit_end_date"],
data_dict["currency"] data_dict["currency"],
) )
if new_decision_book_item := BuildDecisionBookItems.find_or_create(**data_dict): if new_decision_book_item := BuildDecisionBookItems.find_or_create(
**data_dict
):
if new_decision_book_item.is_found: if new_decision_book_item.is_found:
return JSONResponse( return JSONResponse(
status_code=status.HTTP_200_OK, status_code=status.HTTP_200_OK,
@ -361,32 +378,32 @@ class DecisionBookDecisionBookItemsCreateEventMethods(MethodToEvent):
), ),
) )
if created_payment_records_dict := cls.create_payment_records_for_each_build_part( if created_payment_records_dict := cls.create_payment_records_for_each_build_part(
data_info_type=data_info_type, data_info_type=data_info_type,
build_id=decision_book.build_id, build_id=decision_book.build_id,
unit_price=unit_price, unit_price=unit_price,
unit_type=unit_type.upper(), unit_type=unit_type.upper(),
decision_book=decision_book, decision_book=decision_book,
decision_book_item=new_decision_book_item, decision_book_item=new_decision_book_item,
unit_price_is_fixed=data.unit_price_is_fixed, unit_price_is_fixed=data.unit_price_is_fixed,
debit_start_date=debit_start_date, debit_start_date=debit_start_date,
debit_end_date=debit_end_date, debit_end_date=debit_end_date,
currency=currency currency=currency,
): ):
if data_info_type.key == "BDT-A" or data_info_type.key == "BDT-D": if data_info_type.key == "BDT-A" or data_info_type.key == "BDT-D":
if data_info_type.key == "BDT-D": if data_info_type.key == "BDT-D":
item_comment = "Regular Payment Plan : " item_comment = "Regular Payment Plan : "
else: else:
item_comment = "Additional Payment Plan : " item_comment = "Additional Payment Plan : "
for key, value in dict(sorted( for key, value in dict(
sorted(
created_payment_records_dict.items(), created_payment_records_dict.items(),
key=lambda x: x[1], key=lambda x: x[1],
reverse=True reverse=True,
)).items(): )
).items():
item_comment += f" {key} | {abs(float(value))} {currency}, " item_comment += f" {key} | {abs(float(value))} {currency}, "
item_comment = item_comment[:-2] item_comment = item_comment[:-2]
new_decision_book_item.update( new_decision_book_item.update(item_comment=item_comment)
item_comment=item_comment
)
new_decision_book_item.update(is_payment_created=True) new_decision_book_item.update(is_payment_created=True)
return JSONResponse( return JSONResponse(
status_code=status.HTTP_200_OK, status_code=status.HTTP_200_OK,

View File

@ -26,7 +26,9 @@ class EventBindOccupantEventMethods(MethodToEvent):
@classmethod @classmethod
def bind_events_occupant_super_user( def bind_events_occupant_super_user(
cls, data: RegisterEvents2Occupant, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: RegisterEvents2Occupant,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
if not str(token_dict.user_type) == "1": if not str(token_dict.user_type) == "1":
@ -138,7 +140,9 @@ class EventBindEmployeeEventMethods(MethodToEvent):
@classmethod @classmethod
def bind_events_employee( def bind_events_employee(
cls, data: RegisterEvents2Occupant, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: RegisterEvents2Occupant,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
return token_dict.available_event(data=data, token_dict=token_dict) return token_dict.available_event(data=data, token_dict=token_dict)

View File

@ -4,10 +4,15 @@ from databases import (
Modules, Modules,
BuildLivingSpace, BuildLivingSpace,
) )
from api_validations.validations_request import RegisterModules2Occupant, RegisterModules2Employee from api_validations.validations_request import (
RegisterModules2Occupant,
RegisterModules2Employee,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_events.events.events.events_bind_services import ServiceBindOccupantEventMethods from api_events.events.events.events_bind_services import (
ServiceBindOccupantEventMethods,
)
from api_library.date_time_actions.date_functions import system_arrow from api_library.date_time_actions.date_functions import system_arrow
from api_validations.core_response import return_json_response_from_alchemy from api_validations.core_response import return_json_response_from_alchemy
@ -24,11 +29,15 @@ class ModulesBindOccupantEventMethods(MethodToEvent):
cls, build_living_space_id: int, modules_id: int, expires_at: str = None cls, build_living_space_id: int, modules_id: int, expires_at: str = None
): ):
living_space = BuildLivingSpace.filter_one(Modules.id==build_living_space_id).data living_space = BuildLivingSpace.filter_one(
modules = Modules.filter_one(Modules.id==modules_id).data Modules.id == build_living_space_id
).data
modules = Modules.filter_one(Modules.id == modules_id).data
service_build_dict = dict(build_living_space_id=living_space.id) service_build_dict = dict(build_living_space_id=living_space.id)
service_build_dict["expires_at"] = str(system_arrow.get(living_space.expiry_ends)) service_build_dict["expires_at"] = str(
system_arrow.get(living_space.expiry_ends)
)
if not expires_at: if not expires_at:
service_build_dict["expires_at"] = str(system_arrow.get(expires_at)) service_build_dict["expires_at"] = str(system_arrow.get(expires_at))
@ -71,4 +80,4 @@ ModulesBindOccupantEventMethod = ModulesBindOccupantEventMethods(
) )
ModulesBindEmployeeEventMethod = ModulesBindEmployeeEventMethods( ModulesBindEmployeeEventMethod = ModulesBindEmployeeEventMethods(
action=ActionsSchema(endpoint="/bind/modules/employee") action=ActionsSchema(endpoint="/bind/modules/employee")
) )

View File

@ -15,7 +15,10 @@ from databases import (
Event2Employee, Event2Employee,
Event2Occupant, Event2Occupant,
) )
from api_validations.validations_request import RegisterServices2Occupant, RegisterServices2Employee from api_validations.validations_request import (
RegisterServices2Occupant,
RegisterServices2Employee,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
from api_validations.core_response import return_json_response_from_alchemy from api_validations.core_response import return_json_response_from_alchemy
@ -33,9 +36,13 @@ class ServiceBindOccupantEventMethods(MethodToEvent):
): ):
from sqlalchemy.dialects.postgresql import insert from sqlalchemy.dialects.postgresql import insert
living_space = BuildLivingSpace.filter_one(BuildLivingSpace.id==build_living_space_id) living_space = BuildLivingSpace.filter_one(
service = Services.filter_one(Services.id==service_id) BuildLivingSpace.id == build_living_space_id
add_events_list = Service2Events.filter_all(Service2Events.service_id == service.id).data )
service = Services.filter_one(Services.id == service_id)
add_events_list = Service2Events.filter_all(
Service2Events.service_id == service.id
).data
if not add_events_list: if not add_events_list:
raise Exception( raise Exception(
"Service has no events registered. Please contact with your manager" "Service has no events registered. Please contact with your manager"

View File

@ -31,7 +31,11 @@ class EventsListEventMethods(MethodToEvent):
} }
@classmethod @classmethod
def events_list(cls, list_options: ListOptions, token_dict: Union[EmployeeTokenObject, OccupantTokenObject]): def events_list(
cls,
list_options: ListOptions,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
):
records = Events.filter_active( records = Events.filter_active(
*Events.get_smart_query(list_options.query), *Events.get_smart_query(list_options.query),
) )

View File

@ -1,4 +1,8 @@
from api_validations.validations_request import DepartmentsPydantic, PatchRecord, ListOptions from api_validations.validations_request import (
DepartmentsPydantic,
PatchRecord,
ListOptions,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject

View File

@ -1,4 +1,8 @@
from api_validations.validations_request import DepartmentsPydantic, PatchRecord, ListOptions from api_validations.validations_request import (
DepartmentsPydantic,
PatchRecord,
ListOptions,
)
from api_events.events.abstract_class import MethodToEvent, ActionsSchema from api_events.events.abstract_class import MethodToEvent, ActionsSchema
from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject

View File

@ -59,7 +59,9 @@ class PeopleCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def people_create( def people_create(
cls, data: InsertPerson, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: InsertPerson,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
created_user = People.create_action(data=data, token=token_dict) created_user = People.create_action(data=data, token=token_dict)
People.save() People.save()
@ -82,7 +84,10 @@ class PeopleUpdateEventMethods(MethodToEvent):
@classmethod @classmethod
def people_update( def people_update(
cls, data: UpdateUsers, user_uu_id: str, token_dict: Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: UpdateUsers,
user_uu_id: str,
token_dict: Union[EmployeeTokenObject, OccupantTokenObject],
): ):
find_one_user = Users.find_one_or_abort(uu_id=user_uu_id) find_one_user = Users.find_one_or_abort(uu_id=user_uu_id)
access_authorized_company = Companies.select_action( access_authorized_company = Companies.select_action(

View File

@ -15,7 +15,8 @@ from api_validations.validations_request import (
InsertUsers, InsertUsers,
UpdateUsers, UpdateUsers,
PatchRecord, PatchRecord,
ListOptions, RegisterServices2Occupant, ListOptions,
RegisterServices2Occupant,
) )
@ -61,7 +62,9 @@ class UserCreateEventMethods(MethodToEvent):
@classmethod @classmethod
def user_create( def user_create(
cls, data: InsertUsers, token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: InsertUsers,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
): ):
created_user = Users.create_action(create_user=data) created_user = Users.create_action(create_user=data)
created_user.related_company = token_dict.selected_company.company_uu_id created_user.related_company = token_dict.selected_company.company_uu_id
@ -99,7 +102,10 @@ class UserUpdateEventMethods(MethodToEvent):
@classmethod @classmethod
def user_update( def user_update(
cls, data: UpdateUsers, user_uu_id: str, token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject] cls,
data: UpdateUsers,
user_uu_id: str,
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
): ):
find_one_user = Users.find_one_or_abort(uu_id=user_uu_id) find_one_user = Users.find_one_or_abort(uu_id=user_uu_id)
access_authorized_company = Companies.select_action( access_authorized_company = Companies.select_action(

View File

@ -1,16 +1,20 @@
from tasks2events.common_tasks.default_user import AuthDefaultEventBlock from api_events.tasks2events.common_tasks.default_user import AuthDefaultEventBlock
from tasks2events.employee_tasks.super_user import SuperUserEventBlock from api_events.tasks2events.employee_tasks.super_user import SuperUserEventBlock
from tasks2events.occupant_tasks.build_manager import BuildManager from api_events.tasks2events.occupant_tasks.build_manager import BuildManager
from tasks2events.occupant_tasks.build_owner import BuildOwner from api_events.tasks2events.occupant_tasks.build_owner import BuildOwner
from tasks2events.occupant_tasks.build_resident import BuildResident from api_events.tasks2events.occupant_tasks.build_resident import BuildResident
from tasks2events.occupant_tasks.build_tenant import BuildTenant from api_events.tasks2events.occupant_tasks.build_tenant import BuildTenant
from tasks2events.occupant_tasks.build_represent import BuildRepresent from api_events.tasks2events.occupant_tasks.build_represent import BuildRepresent
from tasks2events.occupant_tasks.meeting_writer import BuildMeetingWriter from api_events.tasks2events.occupant_tasks.meeting_writer import BuildMeetingWriter
from tasks2events.occupant_tasks.meeting_advisor import BuildMeetingAdvisor from api_events.tasks2events.occupant_tasks.meeting_advisor import BuildMeetingAdvisor
from tasks2events.occupant_tasks.meeting_attendance import BuildMeetingAttendance from api_events.tasks2events.occupant_tasks.meeting_attendance import (
from tasks2events.occupant_tasks.meeting_president import BuildMeetingPresident BuildMeetingAttendance,
from tasks2events.occupant_tasks.meeting_voted_president import ( )
from api_events.tasks2events.occupant_tasks.meeting_president import (
BuildMeetingPresident,
)
from api_events.tasks2events.occupant_tasks.meeting_voted_president import (
BuildMeetingVotedPresident, BuildMeetingVotedPresident,
) )

View File

@ -1,7 +1,4 @@
from date_time_actions.date_functions import client_arrow, system_arrow from date_time_actions.date_functions import client_arrow, system_arrow
__all__ = [ __all__ = ["client_arrow", "system_arrow"]
"client_arrow",
"system_arrow"
]

View File

@ -9,7 +9,7 @@ class DateTimeLocal:
def __init__(self, timezone: str = "GMT+3", is_client: bool = True): def __init__(self, timezone: str = "GMT+3", is_client: bool = True):
self.timezone = self.__SYSTEM__ self.timezone = self.__SYSTEM__
if is_client: if is_client:
self.timezone = timezone.replace('-', '+') self.timezone = timezone.replace("-", "+")
def find_last_day_of_month(self, date_value): def find_last_day_of_month(self, date_value):
today = self.get(date_value).date() today = self.get(date_value).date()

View File

@ -22,4 +22,4 @@ __all__ = [
"update_selected_to_redis", "update_selected_to_redis",
"password_is_changed_template", "password_is_changed_template",
"change_your_password_template", "change_your_password_template",
] ]

View File

@ -22,7 +22,10 @@ from api_objects import (
) )
from api_services.redis.conn import redis_cli from api_services.redis.conn import redis_cli
from api_services.redis.functions import get_object_via_user_uu_id, get_object_via_access_key from api_services.redis.functions import (
get_object_via_user_uu_id,
get_object_via_access_key,
)
def save_object_to_redis( def save_object_to_redis(

View File

@ -20,4 +20,3 @@ class BaseModelRegular(BaseModel):
def dump(self): def dump(self):
return self.model_dump() return self.model_dump()

View File

@ -1,4 +1,3 @@
from .core_request_validations import ( from .core_request_validations import (
ListOptions, ListOptions,
PydanticBaseModel, PydanticBaseModel,
@ -6,11 +5,7 @@ from .core_request_validations import (
EndpointPydantic, EndpointPydantic,
BaseModelRegular, BaseModelRegular,
) )
from .address import ( from .address import InsertAddress, InsertPostCode, SearchAddress
InsertAddress,
InsertPostCode,
SearchAddress
)
from .application import ( from .application import (
SingleEnumUUID, SingleEnumUUID,
SingleEnumClassKey, SingleEnumClassKey,
@ -222,4 +217,4 @@ __all__ = [
"DeleteUsers", "DeleteUsers",
"RegisterModules2Occupant", "RegisterModules2Occupant",
"RegisterModules2Employee", "RegisterModules2Employee",
] ]

View File

@ -5,6 +5,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class InsertBuildArea(BaseModelRegular): class InsertBuildArea(BaseModelRegular):
build_uu_id: str build_uu_id: str
area_name: str area_name: str

View File

@ -6,6 +6,7 @@ from api_validations.validations_request import (
from typing import Optional from typing import Optional
from pydantic import BaseModel from pydantic import BaseModel
class ChangePassword(BaseModelRegular): class ChangePassword(BaseModelRegular):
domain_name: str domain_name: str
access_key: str access_key: str

View File

@ -5,6 +5,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class UpdateBuildTypes(PydanticBaseModel): ... class UpdateBuildTypes(PydanticBaseModel): ...

View File

@ -5,6 +5,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class InsertBuild(PydanticBaseModel): class InsertBuild(PydanticBaseModel):
gov_address_code: str gov_address_code: str
build_name: str build_name: str

View File

@ -5,6 +5,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class InsertCompany(PydanticBaseModel): class InsertCompany(PydanticBaseModel):
formal_name: str formal_name: str
company_type: str company_type: str

View File

@ -38,6 +38,7 @@ class ConvertField:
default_value = getattr(self.default_val, "field_default_value", None) default_value = getattr(self.default_val, "field_default_value", None)
return matches_with, default_value return matches_with, default_value
# #
# def create_model_from_database(model_id: typing.Union[int, str]): # def create_model_from_database(model_id: typing.Union[int, str]):
# if isinstance(model_id, int): # if isinstance(model_id, int):

View File

@ -4,6 +4,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class RegisterModules2Occupant(BaseModelRegular): class RegisterModules2Occupant(BaseModelRegular):
modules_uu_id: str modules_uu_id: str
occupant_uu_id: str occupant_uu_id: str
@ -13,6 +14,3 @@ class RegisterModules2Occupant(BaseModelRegular):
class RegisterModules2Employee(BaseModelRegular): class RegisterModules2Employee(BaseModelRegular):
modules_uu_id: str modules_uu_id: str
employee_uu_id: str employee_uu_id: str

View File

@ -4,6 +4,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class RegisterServices2Occupant(BaseModelRegular): class RegisterServices2Occupant(BaseModelRegular):
service_uu_id: str service_uu_id: str
occupant_uu_id: str occupant_uu_id: str

View File

@ -5,6 +5,7 @@ from api_validations.validations_request import (
ListOptions, ListOptions,
) )
class InsertUsers(PydanticBaseModel): class InsertUsers(PydanticBaseModel):
people_uu_id: str people_uu_id: str
user_tag: str user_tag: str

View File

@ -11,9 +11,7 @@ from databases.sql_models.account.iban import (
BuildIbans, BuildIbans,
BuildIbanDescription, BuildIbanDescription,
) )
from databases.sql_models.api.encrypter import ( from databases.sql_models.api.encrypter import CrypterEngine
CrypterEngine
)
from databases.sql_models.building.build import ( from databases.sql_models.building.build import (
Build, Build,
BuildTypes, BuildTypes,
@ -86,7 +84,7 @@ from databases.sql_models.rules.rules import (
EndpointRestriction, EndpointRestriction,
) )
#NO-SQL Models # NO-SQL Models
from databases.no_sql_models.mongo_database import ( from databases.no_sql_models.mongo_database import (
MongoQuery, MongoQuery,
) )
@ -161,5 +159,3 @@ __all__ = [
"MongoQuery", "MongoQuery",
"MongoQueryIdentity", "MongoQueryIdentity",
] ]

View File

@ -0,0 +1,11 @@
from .selector_classes import (
Explanation,
SelectActionWithEmployee,
SelectAction,
)
__all__ = [
"Explanation",
"SelectAction",
"SelectActionWithEmployee",
]

View File

@ -0,0 +1,351 @@
import uuid
import secrets
import hashlib
import requests
from sqlalchemy import or_
from datetime import timedelta
from fastapi.exceptions import HTTPException
from fastapi import status
from databases import (
Users,
People,
Companies,
UsersTokens,
MongoQueryIdentity,
)
from databases.no_sql_models.validations import (
PasswordHistoryViaUser,
AccessHistoryViaUser,
)
from api_library.date_time_actions.date_functions import system_arrow, client_arrow
from api_configs import ApiStatic, Auth
from api_services.redis.auth_actions.auth import save_access_token_to_redis
class PasswordModule:
@classmethod
def generate_token(cls, length):
return secrets.token_urlsafe(length)
@classmethod
def create_hashed_password(cls, domain, id_, password):
salted_password = f"{domain}-{id_}-{password}"
return hashlib.sha256(salted_password.encode()).hexdigest()
@classmethod
def check_hashed_password(cls, domain, id_, password, password_hashed):
return cls.create_hashed_password(domain, id_, password) == password_hashed
class AuthModule(PasswordModule):
@classmethod
def check_user_exits(cls, access_key, domain):
found_user: Users = cls.filter_active(
or_(
cls.email == str(access_key).lower(),
cls.phone_number == str(access_key).replace(" ", ""),
),
filter_records=False,
)
if not found_user.data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Given access key or domain is not matching with the any user record.",
)
found_user = found_user.data[0]
other_domains_list = found_user.get_main_domain_and_other_domains(
get_main_domain=False
)
if domain not in other_domains_list:
raise HTTPException(
status_code=401,
detail=dict(message="Unauthorized User attempts to connect api"),
)
if not found_user:
raise HTTPException(
status_code=401,
detail="Given access key or domain is not matching with the any user record.",
)
return found_user
def generate_access_token(self):
return self.generate_token(Auth.ACCESS_TOKEN_LENGTH)
def remove_refresher_token(self, domain, disconnect: bool = False):
registered_tokens = ([], 0)
if disconnect:
registered_tokens = UsersTokens.filter_by(user_id=self.id)
else:
registered_tokens = UsersTokens.filter_by(domain=domain, user_id=self.id)
for token in registered_tokens[0]:
token.session.delete(token)
token.session.commit()
token.session.flush()
def check_password(self, password):
main_domain = self.get_main_domain_and_other_domains(get_main_domain=True)
if check_password := self.check_hashed_password(
domain=main_domain,
id_=self.uu_id,
password_hashed=self.hash_password,
password=password,
):
return check_password
raise HTTPException(
status_code=401,
detail="Password is not correct.",
)
def check_password_is_different(self, password):
main_domain = self.get_main_domain_and_other_domains(get_main_domain=True)
if self.hash_password == self.create_hashed_password(
domain=main_domain, id_=self.uu_id, password=password
):
raise HTTPException(
status_code=401,
detail="New password is same with old password.",
)
def create_password(self, password, password_token=None):
if self.password_token:
replace_day = 0
try:
replace_day = int(
str(self.password_expires_day or 0)
.split(",")[0]
.replace(" days", "")
)
except Exception as e:
err = e
token_is_expired = system_arrow.now() >= system_arrow.get(
self.password_expiry_begins
).shift(days=replace_day)
if not password_token == self.password_token and token_is_expired:
raise HTTPException(
status_code=401,
detail="Password token is not valid. Please request a new password token.",
)
query_engine = MongoQueryIdentity(company_uuid=self.related_company)
domain_via_user = query_engine.get_domain_via_user(user_uu_id=str(self.uu_id))[
"main_domain"
]
new_password_dict = {
"password": self.create_hashed_password(
domain=domain_via_user, id_=self.uu_id, password=password
),
"date": str(system_arrow.now()),
}
history_dict = PasswordHistoryViaUser(
user_uu_id=str(self.uu_id),
password_add=new_password_dict,
access_history_detail={
"request": "",
"ip": "",
},
)
query_engine.refresh_password_history_via_user(payload=history_dict)
self.password_expiry_begins = str(system_arrow.now())
self.hash_password = new_password_dict.get("password")
if self.password_token:
self.password_token = None
self.save()
def reset_password_token(self):
self.password_expiry_begins = str(system_arrow.now())
self.password_token = self.generate_token(127)
self.save()
def generate_refresher_token(self, domain: str, remember_me=False):
if remember_me:
refresh_token = self.generate_token(Auth.REFRESHER_TOKEN_LENGTH)
if already_token := UsersTokens.find_one(
user_id=self.id, token_type="RememberMe", domain=domain
):
already_token.update(token=refresh_token)
already_token.expires_at = system_arrow.shift(days=3)
already_token.save()
return refresh_token
UsersTokens.create(
user_id=self.id,
token_type="RememberMe",
token=refresh_token,
domain=domain,
)
return refresh_token
return None
def remainder_day(self):
return float(
timedelta(
days=int(
"".join(
[
_
for _ in str(self.password_expires_day).split(",")[0]
if _.isdigit()
]
)
)
).seconds
)
class UserLoginModule(AuthModule):
@classmethod
def login_user_with_credentials(cls, data, request):
found_user = Users.check_user_exits(
access_key=data.access_key, domain=data.domain
)
access_token = found_user.generate_access_token()
query_engine = MongoQueryIdentity(company_uuid=found_user.related_company)
if found_user.check_password(password=data.password):
access_object_to_redis = save_access_token_to_redis(
request=request,
found_user=found_user,
domain=data.domain,
access_token=access_token,
)
refresher_token = found_user.generate_refresher_token(
domain=data.domain, remember_me=data.remember_me
)
headers_request = request.headers
headers_request = dict(headers_request)
headers_request["evyos-user-agent"] = headers_request.get("user-agent")
headers_request["evyos-platform"] = headers_request.get("user-agent")
headers_request["evyos-ip-ext"] = "94.54.68.158"
found_user.last_agent = headers_request.get("evyos-user-agent", None)
found_user.last_platform = headers_request.get("evyos-platform", None)
found_user.last_remote_addr = headers_request.get("evyos-ip-ext", None)
found_user.last_seen = str(system_arrow.now())
if ext_ip := headers_request.get("evyos-ip-ext"):
agent = headers_request.get("evyos-user-agent", "")
platform = headers_request.get("evyos-platform", "")
address = requests.get(f"http://ip-api.com/json/{ext_ip}").json()
address_package = {
"city": address["city"],
"zip": address["zip"],
"country": address["country"],
"countryCode": address["countryCode"],
"region": address["region"],
"regionName": address["regionName"],
}
mongo_db = MongoQueryIdentity(
company_uuid=str(found_user.related_company).replace(" ", ""),
storage_reasoning="AccessHistory",
)
filter_query = {
"agent": agent,
"platform": platform,
"address": address_package,
"user_id": found_user.id,
}
already_exits = mongo_db.mongo_engine.filter_by(filter_query) or None
no_address_validates = mongo_db.mongo_engine.get_all()[0] == 0
record_id = uuid.uuid4().__str__()
notice_link = ApiStatic.blacklist_login(record_id=record_id)
found_people = People.find_one(id=found_user.person_id)
access_via_user = query_engine.update_access_history_via_user(
AccessHistoryViaUser(
**{
"user_uu_id": found_user.uu_id.__str__(),
"access_history": {
"record_id": record_id,
"agent": agent,
"platform": platform,
"address": address_package,
"ip": ext_ip,
"access_token": access_token,
"created_at": system_arrow.now().timestamp(),
# "is_confirmed": True if no_address_validates else False,
# "is_first": True if no_address_validates else False,
},
}
)
)
if already_exits:
update_mongo = mongo_db.mongo_engine.table.update_one(
filter=filter_query,
update={
"$set": {
"ip": ext_ip,
"access_token": access_token,
"created_at": system_arrow.now().timestamp(),
}
},
)
else:
mongo_db.mongo_engine.insert(
payload={
"user_id": found_user.id,
"record_id": record_id,
"agent": agent,
"platform": platform,
"address": address_package,
"ip": ext_ip,
"access_token": access_token,
"created_at": system_arrow.now().timestamp(),
"is_confirmed": True if no_address_validates else False,
"is_first": True if no_address_validates else False,
}
)
found_user.remember_me = bool(data.remember_me)
found_user.save()
return {
"access_token": access_token,
"refresher_token": refresher_token,
"user": found_user,
"access_object": access_object_to_redis,
}
raise HTTPException(
status_code=401,
detail="Login is not successful. Please check your credentials.",
)
# UserLogger.log_error(
# dict(
# user_id=found_user.id,
# domain=data.domain,
# access_key=data.access_key,
# agent=found_user.last_agent,
# ip=getattr(request, "remote_addr", None)
# or request.headers.get("X-Forwarded-For", None),
# platform=found_user.last_platform,
# login_date=str(DateTimeLocal.now()),
# is_login=True,
# )
# )
# if (
# not str(found_people.country_code).lower()
# == str(address_package.get("countryCode")).lower()
# ):
# send_email_completed = send_email(
# subject=f"Dear {found_user.nick_name}, your password has been changed.",
# receivers=[str(found_user.email)],
# html=invalid_ip_or_address_found(
# user_name=found_user.nick_name,
# address=address_package,
# notice_link=notice_link,
# ),
# )
# if not send_email_completed:
# raise HTTPException(
# status_code=400,
# detail="An error occured at sending email. Please contact with support team.",
# )

View File

@ -0,0 +1,79 @@
class Explanation: ...
class SelectorsBase:
@classmethod
def add_confirmed_filter(cls, first_table, second_table) -> tuple:
return (
first_table.active == True,
first_table.is_confirmed == True,
first_table.deleted == False,
second_table.active == True,
second_table.is_confirmed == True,
second_table.deleted == False,
)
class SelectActionWithEmployee:
@classmethod
def select_action(cls, employee_id, filter_expr: list = None):
if filter_expr is not None:
filter_expr = (cls.__many__table__.employee_id == employee_id, *filter_expr)
data = (
cls.session.query(cls.id)
.select_from(cls)
.join(cls.__many__table__, cls.__many__table__.member_id == cls.id)
.filter(
*filter_expr,
*SelectorsBase.add_confirmed_filter(
first_table=cls, second_table=cls.__many__table__
),
)
)
return cls.query.filter(cls.id.in_([comp[0] for comp in data.all()]))
data = (
cls.session.query(cls.id)
.select_from(cls)
.join(cls.__many__table__, cls.__many__table__.member_id == cls.id)
.filter(
cls.__many__table__.employee_id == employee_id,
*SelectorsBase.add_confirmed_filter(
first_table=cls, second_table=cls.__many__table__
),
)
)
return cls.query.filter(cls.id.in_([comp[0] for comp in data.all()]))
class SelectAction:
@classmethod
def select_action(cls, duty_id_list: list, filter_expr: list = None):
if filter_expr is not None:
data = (
cls.session.query(cls.id)
.select_from(cls)
.join(cls.__many__table__, cls.__many__table__.member_id == cls.id)
.filter(
cls.__many__table__.duties_id.in_(duty_id_list),
*SelectorsBase.add_confirmed_filter(
first_table=cls, second_table=cls.__many__table__
),
*filter_expr,
)
)
return cls.query.filter(cls.id.in_([comp[0] for comp in data.all()]))
data = (
cls.session.query(cls.id)
.select_from(cls)
.join(cls.__many__table__, cls.__many__table__.member_id == cls.id)
.filter(
cls.__many__table__.duties_id.in_(duty_id_list)
* SelectorsBase.add_confirmed_filter(
first_table=cls, second_table=cls.__many__table__
),
)
)
return cls.query.filter(cls.id.in_([comp[0] for comp in data.all()]))

View File

@ -36,8 +36,7 @@ def load_user_with_erp_details(found_user, access_dict: dict = None):
# } # }
# ) # )
err = e err = e
print('MongoQuery load_user_with_erp_details', err) print("MongoQuery load_user_with_erp_details", err)
for building in list(set(employee.duty.department.company.response_buildings)): for building in list(set(employee.duty.department.company.response_buildings)):
build_parts = [] build_parts = []

View File

@ -8,6 +8,7 @@ from api_configs import MongoConfig
from pymongo import MongoClient from pymongo import MongoClient
from pymongo.collection import Collection from pymongo.collection import Collection
from pymongo.results import InsertManyResult from pymongo.results import InsertManyResult
# from configs import TestMongo as MongoConfig # from configs import TestMongo as MongoConfig

View File

@ -1,6 +1,6 @@
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
from sqlalchemy import ( from sqlalchemy import (
String, String,
Integer, Integer,
@ -10,6 +10,8 @@ from sqlalchemy import (
Boolean, Boolean,
TIMESTAMP, TIMESTAMP,
Numeric, Numeric,
Identity,
UUID,
) )
@ -18,15 +20,15 @@ class AccountBooks(CrudCollection):
__tablename__ = "account_books" __tablename__ = "account_books"
__exclude__fields__ = [] __exclude__fields__ = []
country = mapped_column(String, nullable=False) country: Mapped[str] = mapped_column(String, nullable=False)
branch_type = mapped_column(SmallInteger, server_default="0") branch_type: Mapped[str] = mapped_column(SmallInteger, server_default="0")
# start_date = mapped_column(TIMESTAMP, nullable=False, comment="Account Start Date")
# stop_date = mapped_column(TIMESTAMP, server_default="2900-01-01 00:00:00")
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) company_id: Mapped[Identity] = mapped_column(
company_uu_id = mapped_column(String, nullable=False) ForeignKey("companies.id"), nullable=False
branch_id = mapped_column(ForeignKey("companies.id")) )
branch_uu_id = mapped_column(String, comment="Branch UU ID") company_uu_id: Mapped[UUID] = mapped_column(String, nullable=False)
branch_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
branch_uu_id: Mapped[UUID] = mapped_column(String, comment="Branch UU ID")
# company: Mapped["Companies"] = relationship( # company: Mapped["Companies"] = relationship(
# "Company", back_populates="company_account_books", foreign_keys=[company_id] # "Company", back_populates="company_account_books", foreign_keys=[company_id]
@ -58,24 +60,34 @@ class AccountCodes(CrudCollection):
__tablename__ = "account_codes" __tablename__ = "account_codes"
__exclude__fields__ = [] __exclude__fields__ = []
account_code = mapped_column(String(48), nullable=False, comment="Account Code") account_code: Mapped[str] = mapped_column(
comment_line = mapped_column(String(128), nullable=False, comment="Comment Line") String(48), nullable=False, comment="Account Code"
)
comment_line: Mapped[str] = mapped_column(
String(128), nullable=False, comment="Comment Line"
)
is_receive_or_debit = mapped_column(Boolean) is_receive_or_debit: Mapped[bool] = mapped_column(Boolean)
product_id = mapped_column(Integer, server_default="0") product_id: Mapped[Identity] = mapped_column(Integer, server_default="0")
nvi_id = mapped_column(String(48), server_default="") nvi_id: Mapped[str] = mapped_column(String(48), server_default="")
status_id = mapped_column(SmallInteger, server_default="0") status_id: Mapped[int] = mapped_column(SmallInteger, server_default="0")
account_code_seperator = mapped_column(String(1), server_default=".") account_code_seperator: Mapped[str] = mapped_column(String(1), server_default=".")
system_id = mapped_column(SmallInteger, server_default="0") system_id: Mapped[int] = mapped_column(SmallInteger, server_default="0")
locked = mapped_column(SmallInteger, server_default="0") locked: Mapped[bool] = mapped_column(SmallInteger, server_default="0")
company_id = mapped_column(ForeignKey("companies.id")) company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
company_uu_id = mapped_column(String, nullable=False, comment="Company UU ID") company_uu_id: Mapped[UUID] = mapped_column(
customer_id = mapped_column(ForeignKey("companies.id")) String, nullable=False, comment="Company UU ID"
customer_uu_id = mapped_column(String, nullable=False, comment="Customer UU ID") )
person_id = mapped_column(ForeignKey("people.id")) customer_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
person_uu_id = mapped_column(String, nullable=False, comment="Person UU ID") customer_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Customer UU ID"
)
person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
person_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Person UU ID"
)
# company: Mapped["Companies"] = relationship( # company: Mapped["Companies"] = relationship(
# "Company", back_populates="account_codes", foreign_keys=[company_id] # "Company", back_populates="account_codes", foreign_keys=[company_id]
@ -104,15 +116,17 @@ class AccountCodeParser(CrudCollection):
__tablename__ = "account_code_parser" __tablename__ = "account_code_parser"
__exclude__fields__ = [] __exclude__fields__ = []
account_code_1 = mapped_column(String, nullable=False, comment="Order") account_code_1: Mapped[str] = mapped_column(String, nullable=False, comment="Order")
account_code_2 = mapped_column(String, nullable=False, comment="Order") account_code_2: Mapped[str] = mapped_column(String, nullable=False, comment="Order")
account_code_3 = mapped_column(String, nullable=False, comment="Order") account_code_3: Mapped[str] = mapped_column(String, nullable=False, comment="Order")
account_code_4 = mapped_column(String, server_default="") account_code_4: Mapped[str] = mapped_column(String, server_default="")
account_code_5 = mapped_column(String, server_default="") account_code_5: Mapped[str] = mapped_column(String, server_default="")
account_code_6 = mapped_column(String, server_default="") account_code_6: Mapped[str] = mapped_column(String, server_default="")
account_code_id = mapped_column(ForeignKey("account_codes.id"), nullable=False) account_code_id: Mapped[Identity] = mapped_column(
account_code_uu_id = mapped_column( ForeignKey("account_codes.id"), nullable=False
)
account_code_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Account Code UU ID" String, nullable=False, comment="Account Code UU ID"
) )
@ -146,51 +160,61 @@ class AccountMaster(CrudCollection):
__tablename__ = "account_master" __tablename__ = "account_master"
__exclude__fields__ = [] __exclude__fields__ = []
doc_date = mapped_column(TIMESTAMP, nullable=False, comment="Document Date") doc_date: Mapped[TIMESTAMP] = mapped_column(
plug_type = mapped_column(String, nullable=False, comment="Plug Type") TIMESTAMP, nullable=False, comment="Document Date"
plug_number = mapped_column(Integer, nullable=False, comment="Plug Number") )
plug_type: Mapped[str] = mapped_column(String, nullable=False, comment="Plug Type")
plug_number: Mapped[int] = mapped_column(
Integer, nullable=False, comment="Plug Number"
)
special_code = mapped_column(String(12), server_default="") special_code: Mapped[str] = mapped_column(String(12), server_default="")
authorization_code = mapped_column(String(12), server_default="") authorization_code: Mapped[str] = mapped_column(String(12), server_default="")
doc_code = mapped_column(String(12), server_default="") doc_code: Mapped[str] = mapped_column(String(12), server_default="")
doc_type = mapped_column(SmallInteger, server_default="0") doc_type: Mapped[int] = mapped_column(SmallInteger, server_default="0")
comment_line1 = mapped_column(String, server_default="") comment_line1: Mapped[str] = mapped_column(String, server_default="")
comment_line2 = mapped_column(String, server_default="") comment_line2: Mapped[str] = mapped_column(String, server_default="")
comment_line3 = mapped_column(String, server_default="") comment_line3: Mapped[str] = mapped_column(String, server_default="")
comment_line4 = mapped_column(String, server_default="") comment_line4: Mapped[str] = mapped_column(String, server_default="")
comment_line5 = mapped_column(String, server_default="") comment_line5: Mapped[str] = mapped_column(String, server_default="")
comment_line6 = mapped_column(String, server_default="") comment_line6: Mapped[str] = mapped_column(String, server_default="")
project_code = mapped_column(String(12), server_default="") project_code: Mapped[str] = mapped_column(String(12), server_default="")
module_no = mapped_column(String, server_default="") module_no: Mapped[str] = mapped_column(String, server_default="")
journal_no = mapped_column(Integer, server_default="0") journal_no: Mapped[int] = mapped_column(Integer, server_default="0")
status_id = mapped_column(SmallInteger, server_default="0") status_id: Mapped[int] = mapped_column(SmallInteger, server_default="0")
canceled = mapped_column(Boolean, server_default="0") canceled: Mapped[bool] = mapped_column(Boolean, server_default="0")
print_count = mapped_column(SmallInteger, server_default="0") print_count: Mapped[int] = mapped_column(SmallInteger, server_default="0")
total_active = mapped_column(Numeric(20, 6), server_default="0") total_active: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_passive = mapped_column(Numeric(20, 6), server_default="0") total_passive: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_active_1 = mapped_column(Numeric(20, 6), server_default="0") total_active_1: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_passive_1 = mapped_column(Numeric(20, 6), server_default="0") total_passive_1: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_active_2 = mapped_column(Numeric(20, 6), server_default="0") total_active_2: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_passive_2 = mapped_column(Numeric(20, 6), server_default="0") total_passive_2: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_active_3 = mapped_column(Numeric(20, 6), server_default="0") total_active_3: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_passive_3 = mapped_column(Numeric(20, 6), server_default="0") total_passive_3: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_active_4 = mapped_column(Numeric(20, 6), server_default="0") total_active_4: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
total_passive_4 = mapped_column(Numeric(20, 6), server_default="0") total_passive_4: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
cross_ref = mapped_column(Integer, server_default="0") cross_ref: Mapped[int] = mapped_column(Integer, server_default="0")
data_center_id = mapped_column(String, server_default="") data_center_id: Mapped[str] = mapped_column(String, server_default="")
data_center_rec_num = mapped_column(Integer, server_default="0") data_center_rec_num: Mapped[int] = mapped_column(Integer, server_default="0")
account_header_id = mapped_column(ForeignKey("account_books.id"), nullable=False) account_header_id: Mapped[Identity] = mapped_column(
account_header_uu_id = mapped_column( ForeignKey("account_books.id"), nullable=False
)
account_header_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Account Header UU ID" String, nullable=False, comment="Account Header UU ID"
) )
project_item_id = mapped_column(ForeignKey("build_decision_book_projects.id")) project_item_id: Mapped[Identity] = mapped_column(
project_item_uu_id = mapped_column(String, comment="Project Item UU ID") ForeignKey("build_decision_book_projects.id")
department_id = mapped_column(ForeignKey("departments.id")) )
department_uu_id = mapped_column(String, comment="Department UU ID") project_item_uu_id: Mapped[UUID] = mapped_column(
String, comment="Project Item UU ID"
)
department_id: Mapped[Identity] = mapped_column(ForeignKey("departments.id"))
department_uu_id: Mapped[UUID] = mapped_column(String, comment="Department UU ID")
# account_header: Mapped["AccountBooks"] = relationship( # account_header: Mapped["AccountBooks"] = relationship(
# "AccountBooks", # "AccountBooks",
@ -223,59 +247,77 @@ class AccountDetail(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__enum_list__ = [("plug_type", "AccountingReceiptTypes", "M")] __enum_list__ = [("plug_type", "AccountingReceiptTypes", "M")]
doc_date = mapped_column(TIMESTAMP, nullable=False, comment="Document Date") doc_date: Mapped[TIMESTAMP] = mapped_column(
line_no = mapped_column(SmallInteger, nullable=False, comment="Line Number") TIMESTAMP, nullable=False, comment="Document Date"
receive_debit = mapped_column(String(1), nullable=False, comment="Receive Debit") )
debit = mapped_column(Numeric(20, 6), nullable=False, comment="Debit") line_no: Mapped[int] = mapped_column(
SmallInteger, nullable=False, comment="Line Number"
)
receive_debit: Mapped[str] = mapped_column(
String(1), nullable=False, comment="Receive Debit"
)
debit: Mapped[float] = mapped_column(
Numeric(20, 6), nullable=False, comment="Debit"
)
department = mapped_column(String(24), server_default="") department: Mapped[str] = mapped_column(String(24), server_default="")
special_code = mapped_column(String(12), server_default="") special_code: Mapped[str] = mapped_column(String(12), server_default="")
account_ref = mapped_column(Integer, server_default="0") account_ref: Mapped[int] = mapped_column(Integer, server_default="0")
account_fiche_ref = mapped_column(Integer, server_default="0") account_fiche_ref: Mapped[int] = mapped_column(Integer, server_default="0")
center_ref = mapped_column(Integer, server_default="0") center_ref: Mapped[int] = mapped_column(Integer, server_default="0")
general_code = mapped_column(String(32), server_default="") general_code: Mapped[str] = mapped_column(String(32), server_default="")
credit = mapped_column(Numeric(20, 6), server_default="0") credit: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
currency_type = mapped_column(String(4), server_default="TL") currency_type: Mapped[str] = mapped_column(String(4), server_default="TL")
exchange_rate = mapped_column(Numeric(20, 6), server_default="0") exchange_rate: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
debit_cur = mapped_column(Numeric(20, 6), server_default="0") debit_cur: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
credit_cur = mapped_column(Numeric(20, 6), server_default="0") credit_cur: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
discount_cur = mapped_column(Numeric(20, 6), server_default="0") discount_cur: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
amount = mapped_column(Numeric(20, 6), server_default="0") amount: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
cross_account_code = mapped_column(String(32), server_default="") cross_account_code: Mapped[float] = mapped_column(String(32), server_default="")
inf_index = mapped_column(Numeric(20, 6), server_default="0") inf_index: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
not_inflated = mapped_column(SmallInteger, server_default="0") not_inflated: Mapped[int] = mapped_column(SmallInteger, server_default="0")
not_calculated = mapped_column(SmallInteger, server_default="0") not_calculated: Mapped[int] = mapped_column(SmallInteger, server_default="0")
comment_line1 = mapped_column(String(64), server_default="") comment_line1: Mapped[str] = mapped_column(String(64), server_default="")
comment_line2 = mapped_column(String(64), server_default="") comment_line2: Mapped[str] = mapped_column(String(64), server_default="")
comment_line3 = mapped_column(String(64), server_default="") comment_line3: Mapped[str] = mapped_column(String(64), server_default="")
comment_line4 = mapped_column(String(64), server_default="") comment_line4: Mapped[str] = mapped_column(String(64), server_default="")
comment_line5 = mapped_column(String(64), server_default="") comment_line5: Mapped[str] = mapped_column(String(64), server_default="")
comment_line6 = mapped_column(String(64), server_default="") comment_line6: Mapped[str] = mapped_column(String(64), server_default="")
owner_acc_ref = mapped_column(Integer, server_default="0") owner_acc_ref: Mapped[int] = mapped_column(Integer, server_default="0")
from_where = mapped_column(Integer, server_default="0") from_where: Mapped[int] = mapped_column(Integer, server_default="0")
orj_eid = mapped_column(Integer, server_default="0") orj_eid: Mapped[int] = mapped_column(Integer, server_default="0")
canceled = mapped_column(SmallInteger, server_default="0") canceled: Mapped[int] = mapped_column(SmallInteger, server_default="0")
cross_ref = mapped_column(Integer, server_default="0") cross_ref: Mapped[int] = mapped_column(Integer, server_default="0")
data_center_id = mapped_column(String, server_default="") data_center_id: Mapped[str] = mapped_column(String, server_default="")
data_center_rec_num = mapped_column(Integer, server_default="0") data_center_rec_num: Mapped[str] = mapped_column(Integer, server_default="0")
status_id = mapped_column(SmallInteger, server_default="0") status_id: Mapped[int] = mapped_column(SmallInteger, server_default="0")
plug_type_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) plug_type_id: Mapped[Identity] = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True
)
plug_type_uu_id = mapped_column(String, nullable=False, comment="Plug Type UU ID") plug_type_uu_id = mapped_column(String, nullable=False, comment="Plug Type UU ID")
account_header_id = mapped_column(ForeignKey("account_books.id"), nullable=False) account_header_id: Mapped[Identity] = mapped_column(
account_header_uu_id = mapped_column( ForeignKey("account_books.id"), nullable=False
)
account_header_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Account Header UU ID" String, nullable=False, comment="Account Header UU ID"
) )
account_code_id = mapped_column(ForeignKey("account_codes.id"), nullable=False) account_code_id: Mapped[Identity] = mapped_column(
account_code_uu_id = mapped_column( ForeignKey("account_codes.id"), nullable=False
)
account_code_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Account Code UU ID" String, nullable=False, comment="Account Code UU ID"
) )
account_master_id = mapped_column(ForeignKey("account_master.id"), nullable=False) account_master_id: Mapped[Identity] = mapped_column(
account_master_uu_id = mapped_column( ForeignKey("account_master.id"), nullable=False
)
account_master_uu_id: Mapped[UUID] = mapped_column(
String, nullable=False, comment="Account Master UU ID" String, nullable=False, comment="Account Master UU ID"
) )
project_id = mapped_column(ForeignKey("build_decision_book_projects.id")) project_id: Mapped[Identity] = mapped_column(
project_uu_id = mapped_column(String, comment="Project UU ID") ForeignKey("build_decision_book_projects.id")
)
project_uu_id: Mapped[UUID] = mapped_column(String, comment="Project UU ID")
# account_header: Mapped["AccountBooks"] = relationship( # account_header: Mapped["AccountBooks"] = relationship(
# "AccountBooks", # "AccountBooks",
@ -342,87 +384,102 @@ class AccountRecords(CrudCollection):
build_decision_book_id = kaydın sorumlu olduğu karar defteri build_decision_book_id = kaydın sorumlu olduğu karar defteri
send_company_id = kaydı gönderen firma, send_person_id = gönderen kişi send_company_id = kaydı gönderen firma, send_person_id = gönderen kişi
customer_id = sorumlu kullanıcı bilgisi, company_id = sorumlu firma customer_id = sorumlu kullanıcı bilgisi, company_id = sorumlu firma
""" """
iban = mapped_column(String(64), nullable=False, comment="IBAN Number of Bank") iban: Mapped[str] = mapped_column(
bank_date = mapped_column( String(64), nullable=False, comment="IBAN Number of Bank"
)
bank_date: Mapped[TIMESTAMP] = mapped_column(
TIMESTAMP, nullable=False, comment="Bank Transaction Date" TIMESTAMP, nullable=False, comment="Bank Transaction Date"
) )
currency_value = mapped_column( currency_value: Mapped[float] = mapped_column(
Numeric(20, 6), nullable=False, comment="Currency Value" Numeric(20, 6), nullable=False, comment="Currency Value"
) )
bank_balance = mapped_column(Numeric(20, 6), nullable=False, comment="Bank Balance") bank_balance: Mapped[float] = mapped_column(
currency = mapped_column(String(5), nullable=False, comment="Unit of Currency") Numeric(20, 6), nullable=False, comment="Bank Balance"
additional_balance = mapped_column( )
currency: Mapped[str] = mapped_column(
String(5), nullable=False, comment="Unit of Currency"
)
additional_balance: Mapped[float] = mapped_column(
Numeric(20, 6), nullable=False, comment="Additional Balance" Numeric(20, 6), nullable=False, comment="Additional Balance"
) )
channel_branch = mapped_column(String(120), nullable=False, comment="Branch Bank") channel_branch: Mapped[str] = mapped_column(
process_name = mapped_column( String(120), nullable=False, comment="Branch Bank"
)
process_name: Mapped[str] = mapped_column(
String, nullable=False, comment="Bank Process Type Name" String, nullable=False, comment="Bank Process Type Name"
) )
process_type = mapped_column( process_type: Mapped[str] = mapped_column(
String, nullable=False, comment="Bank Process Type" String, nullable=False, comment="Bank Process Type"
) )
process_comment = mapped_column( process_comment: Mapped[str] = mapped_column(
String, nullable=False, comment="Transaction Record Comment" String, nullable=False, comment="Transaction Record Comment"
) )
bank_reference_code = mapped_column( bank_reference_code: Mapped[str] = mapped_column(
String, nullable=False, comment="Bank Reference Code" String, nullable=False, comment="Bank Reference Code"
) )
add_comment_note = mapped_column(String, server_default="") add_comment_note: Mapped[str] = mapped_column(String, server_default="")
is_receipt_mail_send = mapped_column(Boolean, server_default="0") is_receipt_mail_send: Mapped[bool] = mapped_column(Boolean, server_default="0")
found_from = mapped_column(String, server_default="") found_from = mapped_column(String, server_default="")
similarity = mapped_column(Numeric(20, 6), server_default="0") similarity: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
remainder_balance = mapped_column(Numeric(20, 6), server_default="0") remainder_balance: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
bank_date_y = mapped_column(Integer) bank_date_y: Mapped[int] = mapped_column(Integer)
bank_date_m = mapped_column(SmallInteger) bank_date_m: Mapped[int] = mapped_column(SmallInteger)
bank_date_w = mapped_column(SmallInteger) bank_date_w: Mapped[int] = mapped_column(SmallInteger)
bank_date_d = mapped_column(SmallInteger) bank_date_d: Mapped[int] = mapped_column(SmallInteger)
approving_accounting_record = mapped_column(Boolean, server_default="0") approving_accounting_record: Mapped[bool] = mapped_column(
Boolean, server_default="0"
)
accounting_receipt_date = mapped_column( accounting_receipt_date = mapped_column(
TIMESTAMP, server_default="1900-01-01 00:00:00" TIMESTAMP, server_default="1900-01-01 00:00:00"
) )
accounting_receipt_number = mapped_column(Integer, server_default="0") accounting_receipt_number = mapped_column(Integer, server_default="0")
status_id = mapped_column(SmallInteger, server_default="0") status_id = mapped_column(SmallInteger, server_default="0")
approved_record = mapped_column(Boolean, server_default="0") approved_record: Mapped[bool] = mapped_column(Boolean, server_default="0")
import_file_name = mapped_column(String, nullable=True, comment="XLS Key") import_file_name = mapped_column(String, nullable=True, comment="XLS Key")
receive_debit = mapped_column(ForeignKey("api_enum_dropdown.id")) receive_debit: Mapped[Identity] = mapped_column(ForeignKey("api_enum_dropdown.id"))
receive_debit_uu_id = mapped_column(String, nullable=True, comment="Debit UU ID") receive_debit_uu_id = mapped_column(String, nullable=True, comment="Debit UU ID")
budget_type = mapped_column(ForeignKey("api_enum_dropdown.uu_id"), nullable=True) budget_type: Mapped[Identity] = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True
)
budget_type_uu_id = mapped_column( budget_type_uu_id = mapped_column(
String, nullable=True, comment="Budget Type UU ID" String, nullable=True, comment="Budget Type UU ID"
) )
company_id = mapped_column(ForeignKey("companies.id")) company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
company_uu_id = mapped_column(String, nullable=True, comment="Company UU ID") company_uu_id = mapped_column(String, nullable=True, comment="Company UU ID")
send_company_id = mapped_column(ForeignKey("companies.id")) send_company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
send_company_uu_id = mapped_column( send_company_uu_id = mapped_column(
String, nullable=True, comment="Send Company UU ID" String, nullable=True, comment="Send Company UU ID"
) )
customer_id = mapped_column(ForeignKey("people.id")) customer_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
customer_uu_id = mapped_column(String, nullable=True, comment="Customer UU ID") customer_uu_id = mapped_column(String, nullable=True, comment="Customer UU ID")
send_person_id = mapped_column(ForeignKey("people.id")) send_person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
send_person_uu_id = mapped_column( send_person_uu_id = mapped_column(
String, nullable=True, comment="Send Person UU ID" String, nullable=True, comment="Send Person UU ID"
) )
approving_accounting_person = mapped_column(ForeignKey("people.id")) approving_accounting_person: Mapped[Identity] = mapped_column(
ForeignKey("people.id")
)
approving_accounting_person_uu_id = mapped_column( approving_accounting_person_uu_id = mapped_column(
String, nullable=True, comment="Approving Accounting Person UU ID" String, nullable=True, comment="Approving Accounting Person UU ID"
) )
# build_id = mapped_column(ForeignKey("build.id"), nullable=True) # build_id: Mapped[Identity] = mapped_column(ForeignKey("build.id"), nullable=True)
build_parts_id = mapped_column(ForeignKey("build_parts.id")) build_parts_id: Mapped[Identity] = mapped_column(ForeignKey("build_parts.id"))
build_parts_uu_id = mapped_column( build_parts_uu_id = mapped_column(
String, nullable=True, comment="Build Parts UU ID" String, nullable=True, comment="Build Parts UU ID"
) )
build_decision_book_id = mapped_column(ForeignKey("build_decision_book.id")) build_decision_book_id: Mapped[Identity] = mapped_column(
ForeignKey("build_decision_book.id")
)
build_decision_book_uu_id = mapped_column( build_decision_book_uu_id = mapped_column(
String, nullable=True, comment="Build Decision Book UU ID" String, nullable=True, comment="Build Decision Book UU ID"
) )

View File

@ -1,5 +1,5 @@
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
from sqlalchemy import String, ForeignKey, Index, TIMESTAMP, SmallInteger from sqlalchemy import String, ForeignKey, Index, TIMESTAMP, SmallInteger, Identity
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
@ -12,21 +12,23 @@ class BuildIbans(CrudCollection):
__tablename__ = "build_ibans" __tablename__ = "build_ibans"
__exclude__fields__ = [] __exclude__fields__ = []
iban = mapped_column( iban: Mapped[str] = mapped_column(
String(40), server_default="", nullable=False, comment="IBAN number" String(40), server_default="", nullable=False, comment="IBAN number"
) )
start_date = mapped_column( start_date: Mapped[TIMESTAMP] = mapped_column(
TIMESTAMP, nullable=False, comment="Bank Transaction Start Date" TIMESTAMP, nullable=False, comment="Bank Transaction Start Date"
) )
stop_date = mapped_column(TIMESTAMP, server_default="2900-01-01 00:00:00") stop_date: Mapped[TIMESTAMP] = mapped_column(
bank_code = mapped_column(String(24), server_default="TR0000000000000") TIMESTAMP, server_default="2900-01-01 00:00:00"
xcomment = mapped_column(String(64), server_default="????") )
bank_code: Mapped[str] = mapped_column(String(24), server_default="TR0000000000000")
xcomment: Mapped[str] = mapped_column(String(64), server_default="????")
build_id = mapped_column( build_id: Mapped[Identity] = mapped_column(
ForeignKey("build.id"), nullable=False, comment="Building ID" ForeignKey("build.id"), nullable=False, comment="Building ID"
) )
build_uu_id = mapped_column( build_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Building UUID", index=True String, nullable=False, comment="Building UUID", index=True
) )
# building: Mapped["Build"] = relationship( # building: Mapped["Build"] = relationship(
@ -57,22 +59,30 @@ class BuildIbanDescription(CrudCollection):
__tablename__ = "build_iban_description" __tablename__ = "build_iban_description"
__exclude__fields__ = [] __exclude__fields__ = []
iban = mapped_column(String, nullable=False, comment="IBAN Number") iban: Mapped[str] = mapped_column(String, nullable=False, comment="IBAN Number")
group_id = mapped_column(SmallInteger, nullable=False, comment="Group ID") group_id: Mapped[int] = mapped_column(
search_word = mapped_column( SmallInteger, nullable=False, comment="Group ID"
)
search_word: Mapped[str] = mapped_column(
String, nullable=False, comment="Search Word", index=True String, nullable=False, comment="Search Word", index=True
) )
decision_book_project_id = mapped_column(ForeignKey("build_decision_book_projects.id")) decision_book_project_id: Mapped[Identity] = mapped_column(
decision_book_project_uu_id = mapped_column( ForeignKey("build_decision_book_projects.id")
)
decision_book_project_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Decision Book Project UUID" String, nullable=False, comment="Decision Book Project UUID"
) )
customer_id = mapped_column(ForeignKey("people.id")) customer_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
customer_uu_id = mapped_column(String, nullable=False, comment="Customer UUID") customer_uu_id: Mapped[str] = mapped_column(
company_id = mapped_column(ForeignKey("companies.id")) String, nullable=False, comment="Customer UUID"
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID") )
build_parts_id = mapped_column(ForeignKey("build_parts.id")) company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
build_parts_uu_id = mapped_column( company_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Company UUID"
)
build_parts_id: Mapped[Identity] = mapped_column(ForeignKey("build_parts.id"))
build_parts_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Build Parts UUID" String, nullable=False, comment="Build Parts UUID"
) )

View File

@ -16,18 +16,19 @@ from sqlalchemy import (
TIMESTAMP, TIMESTAMP,
Text, Text,
Numeric, Numeric,
Identity,
) )
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from databases import ApiEnumDropdown from databases import ApiEnumDropdown
from application.shared_classes import SelectActionWithEmployee, Explanation from databases.extensions.selector_classes import SelectActionWithEmployee, Explanation
from validations import ( from api_validations.validations_request import (
InsertBuildParts, InsertBuildParts,
InsertBuild, InsertBuild,
UpdateBuild, UpdateBuild,
) )
from valids.auth.token_validations import EmployeeTokenObject, OccupantTokenObject from api_objects.auth.token_objects import EmployeeTokenObject, OccupantTokenObject
class AbstractBuild: class AbstractBuild:
@ -119,16 +120,16 @@ class BuildTypes(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__include__fields__ = [] __include__fields__ = []
function_code = mapped_column( function_code: Mapped[str] = mapped_column(
String(12), server_default="", nullable=False, comment="Function Code" String(12), server_default="", nullable=False, comment="Function Code"
) )
type_code = mapped_column( type_code: Mapped[str] = mapped_column(
String(12), server_default="", nullable=False, comment="Structure Type Code" String(12), server_default="", nullable=False, comment="Structure Type Code"
) )
lang = mapped_column( lang: Mapped[str] = mapped_column(
String(4), server_default="TR", nullable=False, comment="Language" String(4), server_default="TR", nullable=False, comment="Language"
) )
type_name = mapped_column( type_name: Mapped[str] = mapped_column(
String(48), server_default="", nullable=False, comment="Type Name" String(48), server_default="", nullable=False, comment="Type Name"
) )
@ -148,11 +149,11 @@ class Part2Employee(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__include__fields__ = [] __include__fields__ = []
build_id = mapped_column(Integer, comment="Building ID") build_id: Mapped[int] = mapped_column(Integer, comment="Building ID")
part_id = mapped_column( part_id: Mapped[Identity] = mapped_column(
ForeignKey("build_parts.id"), nullable=False, comment="Part ID" ForeignKey("build_parts.id"), nullable=False, comment="Part ID"
) )
employee_id = mapped_column( employee_id: Mapped[Identity] = mapped_column(
ForeignKey("employees.id"), nullable=False, comment="Employee ID" ForeignKey("employees.id"), nullable=False, comment="Employee ID"
) )
@ -172,16 +173,20 @@ class RelationshipEmployee2Build(CrudCollection):
__tablename__ = "relationship_employee2build" __tablename__ = "relationship_employee2build"
__exclude__fields__ = [] __exclude__fields__ = []
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1, 2, 3 company_id: Mapped[Identity] = mapped_column(
employee_id = mapped_column( ForeignKey("companies.id"), nullable=False
) # 1, 2, 3
employee_id: Mapped[Identity] = mapped_column(
ForeignKey("employees.id"), nullable=False ForeignKey("employees.id"), nullable=False
) # employee -> (n)person Evyos LTD ) # employee -> (n)person Evyos LTD
member_id = mapped_column(ForeignKey("build.id"), nullable=False) # 2, 3, 4 member_id: Mapped[Identity] = mapped_column(
ForeignKey("build.id"), nullable=False
) # 2, 3, 4
relationship_type = mapped_column( relationship_type: Mapped[str] = mapped_column(
String, nullable=True, server_default="Employee" String, nullable=True, server_default="Employee"
) # Commercial ) # Commercial
show_only = mapped_column(Boolean, server_default="False") show_only: Mapped[bool] = mapped_column(Boolean, server_default="False")
__table_args__ = ( __table_args__ = (
Index( Index(
@ -208,44 +213,56 @@ class Build(CrudCollection, SelectActionWithEmployee):
__many__table__ = RelationshipEmployee2Build __many__table__ = RelationshipEmployee2Build
__explain__ = AbstractBuild() __explain__ = AbstractBuild()
gov_address_code = mapped_column(String, server_default="", unique=True) gov_address_code: Mapped[str] = mapped_column(
build_name = mapped_column(String, nullable=False, comment="Building Name") String, server_default="", unique=True
build_no = mapped_column(String(8), nullable=False, comment="Building Number") )
build_name: Mapped[str] = mapped_column(
String, nullable=False, comment="Building Name"
)
build_no: Mapped[str] = mapped_column(
String(8), nullable=False, comment="Building Number"
)
max_floor = mapped_column( max_floor: Mapped[int] = mapped_column(
SmallInteger, server_default="1", nullable=False, comment="Max Floor" SmallInteger, server_default="1", nullable=False, comment="Max Floor"
) )
underground_floor = mapped_column( underground_floor: Mapped[int] = mapped_column(
SmallInteger, server_default="0", nullable=False, comment="Underground Floor" SmallInteger, server_default="0", nullable=False, comment="Underground Floor"
) )
build_date = mapped_column(TIMESTAMP, server_default="1900-01-01") build_date: Mapped[TIMESTAMP] = mapped_column(
decision_period_date = mapped_column( TIMESTAMP, server_default="1900-01-01"
)
decision_period_date: Mapped[TIMESTAMP] = mapped_column(
TIMESTAMP, TIMESTAMP,
server_default="1900-01-01", server_default="1900-01-01",
comment="Building annual ordinary meeting period", comment="Building annual ordinary meeting period",
) )
tax_no = mapped_column(String(24), server_default="") tax_no: Mapped[str] = mapped_column(String(24), server_default="")
lift_count = mapped_column(SmallInteger, server_default="0") lift_count: Mapped[int] = mapped_column(SmallInteger, server_default="0")
heating_system = mapped_column(Boolean, server_default="True") heating_system: Mapped[bool] = mapped_column(Boolean, server_default="True")
cooling_system = mapped_column(Boolean, server_default="False") cooling_system: Mapped[bool] = mapped_column(Boolean, server_default="False")
hot_water_system = mapped_column(Boolean, server_default="False") hot_water_system: Mapped[bool] = mapped_column(Boolean, server_default="False")
block_service_man_count = mapped_column(SmallInteger, server_default="0") block_service_man_count: Mapped[int] = mapped_column(
security_service_man_count = mapped_column(SmallInteger, server_default="0") SmallInteger, server_default="0"
garage_count = mapped_column( )
security_service_man_count: Mapped[int] = mapped_column(
SmallInteger, server_default="0"
)
garage_count: Mapped[int] = mapped_column(
SmallInteger, server_default="0", comment="Garage Count" SmallInteger, server_default="0", comment="Garage Count"
) )
management_room_id = mapped_column( management_room_id: Mapped[int] = mapped_column(
Integer, nullable=True, comment="Management Room ID" Integer, nullable=True, comment="Management Room ID"
) )
site_id = mapped_column(ForeignKey("build_sites.id")) site_id: Mapped[Identity] = mapped_column(ForeignKey("build_sites.id"))
site_uu_id = mapped_column(String, comment="Site UUID") site_uu_id: Mapped[str] = mapped_column(String, comment="Site UUID")
address_id = mapped_column(ForeignKey("addresses.id")) address_id: Mapped[Identity] = mapped_column(ForeignKey("addresses.id"))
address_uu_id = mapped_column(String, comment="Address UUID") address_uu_id: Mapped[str] = mapped_column(String, comment="Address UUID")
build_types_id = mapped_column( build_types_id = mapped_column(
ForeignKey("build_types.id"), nullable=False, comment="Building Type" ForeignKey("build_types.id"), nullable=False, comment="Building Type"
) )
build_types_uu_id = mapped_column(String, comment="Building Type UUID") build_types_uu_id: Mapped[str] = mapped_column(String, comment="Building Type UUID")
parts: Mapped[List["BuildParts"]] = relationship( parts: Mapped[List["BuildParts"]] = relationship(
"BuildParts", back_populates="buildings", foreign_keys="BuildParts.build_id" "BuildParts", back_populates="buildings", foreign_keys="BuildParts.build_id"
@ -296,7 +313,7 @@ class Build(CrudCollection, SelectActionWithEmployee):
@classmethod @classmethod
def create_action(cls, data: InsertBuild, token): def create_action(cls, data: InsertBuild, token):
from database_sql_models import Addresses from databases import Addresses
data_dict = data.excluded_dump() data_dict = data.excluded_dump()
data_dict["address_id"] = None data_dict["address_id"] = None
@ -325,7 +342,7 @@ class Build(CrudCollection, SelectActionWithEmployee):
@classmethod @classmethod
def update_action(cls, data: UpdateBuild, build_uu_id: str, token): def update_action(cls, data: UpdateBuild, build_uu_id: str, token):
from database_sql_models import Addresses from databases import Addresses
data_dict = data.excluded_dump() data_dict = data.excluded_dump()
if data.official_address_uu_id: if data.official_address_uu_id:
@ -405,7 +422,7 @@ class BuildParts(CrudCollection):
address_gov_code = mapped_column( address_gov_code = mapped_column(
String, nullable=False, comment="Goverment Door Code" String, nullable=False, comment="Goverment Door Code"
) )
# part_name = mapped_column(String(24), server_default="", nullable=False, comment="Part Name") # part_name: Mapped[str] = mapped_column(String(24), server_default="", nullable=False, comment="Part Name")
part_no = mapped_column( part_no = mapped_column(
SmallInteger, server_default="0", nullable=False, comment="Part Number" SmallInteger, server_default="0", nullable=False, comment="Part Number"
) )
@ -422,7 +439,9 @@ class BuildParts(CrudCollection):
default_accessory = mapped_column( default_accessory = mapped_column(
Text, server_default="0", comment="Default Accessory" Text, server_default="0", comment="Default Accessory"
) )
human_livable = mapped_column(Boolean, server_default="1", comment="Human Livable") human_livable: Mapped[bool] = mapped_column(
Boolean, server_default="1", comment="Human Livable"
)
due_part_key = mapped_column( due_part_key = mapped_column(
String, server_default="", nullable=False, comment="Constant Payment Group" String, server_default="", nullable=False, comment="Constant Payment Group"
) )
@ -430,8 +449,12 @@ class BuildParts(CrudCollection):
build_id = mapped_column( build_id = mapped_column(
ForeignKey("build.id"), nullable=False, comment="Building ID" ForeignKey("build.id"), nullable=False, comment="Building ID"
) )
build_uu_id = mapped_column(String, nullable=False, comment="Building UUID") build_uu_id: Mapped[str] = mapped_column(
part_direction_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) String, nullable=False, comment="Building UUID"
)
part_direction_id: Mapped[Identity] = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True
)
part_direction_uu_id = mapped_column( part_direction_uu_id = mapped_column(
String, nullable=True, comment="Part Direction UUID" String, nullable=True, comment="Part Direction UUID"
) )
@ -541,11 +564,15 @@ class BuildLivingSpace(CrudCollection):
comment="Fixed percent is deducted from debit.", comment="Fixed percent is deducted from debit.",
) )
agreement_no = mapped_column(String, server_default="", comment="Agreement No") agreement_no: Mapped[str] = mapped_column(
marketing_process = mapped_column(Boolean, server_default="False") String, server_default="", comment="Agreement No"
)
marketing_process: Mapped[bool] = mapped_column(Boolean, server_default="False")
marketing_layer = mapped_column(SmallInteger, server_default="0") marketing_layer = mapped_column(SmallInteger, server_default="0")
discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22 discounted_percentage: Mapped[float] = mapped_column(
Numeric(6, 2), server_default="0.00"
) # %22
discounted_price = mapped_column( discounted_price = mapped_column(
Numeric(20, 2), server_default="0.00" Numeric(20, 2), server_default="0.00"
) # Normal: 78.00 TL ) # Normal: 78.00 TL
@ -559,7 +586,9 @@ class BuildLivingSpace(CrudCollection):
index=True, index=True,
comment="Build Part ID", comment="Build Part ID",
) )
build_parts_uu_id = mapped_column(String, nullable=False, comment="Build Part UUID") build_parts_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Build Part UUID"
)
person_id = mapped_column( person_id = mapped_column(
ForeignKey("people.id"), ForeignKey("people.id"),
nullable=False, nullable=False,
@ -588,7 +617,9 @@ class BuildLivingSpace(CrudCollection):
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject], token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
): ):
from databases import Services, OccupantTypes from databases import Services, OccupantTypes
from api_events.events.events.events_bind_services import ServiceBindOccupantEventMethods from api_events.events.events.events_bind_services import (
ServiceBindOccupantEventMethods,
)
created_living_space = BuildLivingSpace.find_or_create(**data) created_living_space = BuildLivingSpace.find_or_create(**data)
occupant_type = OccupantTypes.find_one( occupant_type = OccupantTypes.find_one(
@ -632,16 +663,16 @@ class BuildArea(CrudCollection):
__tablename__ = "build_area" __tablename__ = "build_area"
area_name = mapped_column(String, server_default="") area_name: Mapped[str] = mapped_column(String, server_default="")
area_code = mapped_column(String, server_default="") area_code: Mapped[str] = mapped_column(String, server_default="")
area_type = mapped_column(String, server_default="GREEN") area_type: Mapped[str] = mapped_column(String, server_default="GREEN")
area_direction = mapped_column(String(2), server_default="NN") area_direction: Mapped[str] = mapped_column(String(2), server_default="NN")
area_gross_size = mapped_column(Numeric(20, 6), server_default="0") area_gross_size: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
area_net_size = mapped_column(Numeric(20, 6), server_default="0") area_net_size: Mapped[float] = mapped_column(Numeric(20, 6), server_default="0")
width = mapped_column(Integer, server_default="0") width = mapped_column(Integer, server_default="0")
size = mapped_column(Integer, server_default="0") size = mapped_column(Integer, server_default="0")
build_id = mapped_column(ForeignKey("build.id")) build_id: Mapped[Identity] = mapped_column(ForeignKey("build.id"))
build_uu_id = mapped_column(String, comment="Building UUID") build_uu_id = mapped_column(String, comment="Building UUID")
part_type_id = mapped_column( part_type_id = mapped_column(
ForeignKey("build_types.id"), nullable=True, comment="Building Part Type" ForeignKey("build_types.id"), nullable=True, comment="Building Part Type"
@ -671,7 +702,7 @@ class BuildSites(CrudCollection):
site_name = mapped_column(String(24), nullable=False) site_name = mapped_column(String(24), nullable=False)
site_no = mapped_column(String(8), nullable=False) site_no = mapped_column(String(8), nullable=False)
address_id = mapped_column(ForeignKey("addresses.id")) address_id: Mapped[Identity] = mapped_column(ForeignKey("addresses.id"))
address_uu_id = mapped_column(String, comment="Address UUID") address_uu_id = mapped_column(String, comment="Address UUID")
# addresses: Mapped["Address"] = relationship( # addresses: Mapped["Address"] = relationship(
@ -688,47 +719,63 @@ class BuildSites(CrudCollection):
class BuildCompaniesProviding(CrudCollection): class BuildCompaniesProviding(CrudCollection):
""" """ """
"""
__tablename__ = "build_companies_providing" __tablename__ = "build_companies_providing"
__exclude__fields__ = [] __exclude__fields__ = []
__include__fields__ = [] __include__fields__ = []
build_id = mapped_column(ForeignKey("build.id"), nullable=False, comment="Building ID") build_id = mapped_column(
ForeignKey("build.id"), nullable=False, comment="Building ID"
)
build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID") build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
company_id = mapped_column(ForeignKey("companies.id")) company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
company_uu_id = mapped_column(String, nullable=True, comment="Providing UUID") company_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
provide_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) provide_id: Mapped[Identity] = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True
)
provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID") provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
contract_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True) contract_id = mapped_column(Integer, ForeignKey("companies.id"), nullable=True)
__table_args__ = ( __table_args__ = (
Index("_build_companies_providing_ndx_00", build_id, company_id, provide_id , unique=True), Index(
"_build_companies_providing_ndx_00",
build_id,
company_id,
provide_id,
unique=True,
),
{"comment": "Companies providing services for building"}, {"comment": "Companies providing services for building"},
) )
class BuildPersonProviding(CrudCollection): class BuildPersonProviding(CrudCollection):
""" """ """
"""
__tablename__ = "build_person_providing" __tablename__ = "build_person_providing"
__exclude__fields__ = [] __exclude__fields__ = []
__include__fields__ = [] __include__fields__ = []
build_id = mapped_column(ForeignKey("build.id"), nullable=False, comment="Building ID") build_id = mapped_column(
ForeignKey("build.id"), nullable=False, comment="Building ID"
)
build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID") build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
people_id = mapped_column(ForeignKey("people.id")) people_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
people_uu_id = mapped_column(String, nullable=True, comment="People UUID") people_uu_id = mapped_column(String, nullable=True, comment="People UUID")
provide_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) provide_id: Mapped[Identity] = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True
)
provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID") provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
contract_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True) contract_id = mapped_column(Integer, ForeignKey("companies.id"), nullable=True)
__table_args__ = ( __table_args__ = (
Index("_build_person_providing_ndx_00", build_id, people_id, provide_id , unique=True), Index(
"_build_person_providing_ndx_00",
build_id,
people_id,
provide_id,
unique=True,
),
{"comment": "People providing services for building"}, {"comment": "People providing services for building"},
) )
@ -789,9 +836,9 @@ class BuildPersonProviding(CrudCollection):
# life_people: Mapped["People"] = relationship( # life_people: Mapped["People"] = relationship(
# "People", back_populates="life_living_spaces", foreign_keys=[life_person_id] # "People", back_populates="life_living_spaces", foreign_keys=[life_person_id]
# ) # )
# company_id = mapped_column(ForeignKey("companies.id")) # company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
# response_company_id = mapped_column(ForeignKey("companies.id")) # response_company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
# person_id = mapped_column(ForeignKey("people.id")) # person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
# companies: Mapped["Companies"] = relationship( # companies: Mapped["Companies"] = relationship(
# "Companies", back_populates="buildings", foreign_keys=[company_id] # "Companies", back_populates="buildings", foreign_keys=[company_id]

View File

@ -8,11 +8,13 @@ from databases.sql_models.core_mixin import CrudCollection
from databases import ( from databases import (
Build, Build,
BuildLivingSpace, BuildLivingSpace,
BuildIbans,
People, People,
BuildParts, Companies,
OccupantTypes, OccupantTypes,
Services,
) )
from api_library.date_time_actions.date_functions import DateTimeLocal from api_library.date_time_actions.date_functions import system_arrow, client_arrow
from sqlalchemy import ( from sqlalchemy import (
String, String,
@ -24,10 +26,11 @@ from sqlalchemy import (
Text, Text,
Numeric, Numeric,
Integer, Integer,
Identity,
) )
from sqlalchemy.orm import mapped_column, Mapped, relationship from sqlalchemy.orm import mapped_column, Mapped, relationship
from validations import ( from api_validations.validations_request import (
InsertDecisionBook, InsertDecisionBook,
InsertBuildDecisionBookItems, InsertBuildDecisionBookItems,
InsertBuildDecisionBookItemDebits, InsertBuildDecisionBookItemDebits,
@ -52,24 +55,34 @@ class BuildDecisionBook(CrudCollection):
__tablename__ = "build_decision_book" __tablename__ = "build_decision_book"
__exclude__fields__ = [] __exclude__fields__ = []
decision_book_pdf_path = mapped_column(String) decision_book_pdf_path: Mapped[str] = mapped_column(String)
resp_company_fix_wage = mapped_column(Numeric(10, 2), server_default="0") # resp_company_fix_wage: Mapped[float] = mapped_column(
is_out_sourced = mapped_column(Boolean, server_default="0") Numeric(10, 2), server_default="0"
contact_id = mapped_column(ForeignKey("contracts.id"), nullable=True, comment="Contract id") ) #
contact_uu_id = mapped_column(String, nullable=True, comment="Contract UUID") is_out_sourced: Mapped[bool] = mapped_column(Boolean, server_default="0")
meeting_date = mapped_column(TIMESTAMP, server_default="1900-01-01") meeting_date: Mapped[TIMESTAMP] = mapped_column(
decision_type = mapped_column(String(3), server_default="RBM") TIMESTAMP, server_default="1900-01-01"
)
decision_type: Mapped[str] = mapped_column(String(3), server_default="RBM")
meeting_is_completed = mapped_column(Boolean, server_default="0") meeting_is_completed: Mapped[bool] = mapped_column(Boolean, server_default="0")
meeting_completed_date = mapped_column( meeting_completed_date: Mapped[TIMESTAMP] = mapped_column(
TIMESTAMP, nullable=True, comment="Meeting Completed Date" TIMESTAMP, nullable=True, comment="Meeting Completed Date"
) )
build_id = mapped_column(ForeignKey("build.id"), nullable=False) build_id: Mapped[Identity] = mapped_column(ForeignKey("build.id"), nullable=False)
build_uu_id = mapped_column(String, nullable=True, comment="Build UUID") build_uu_id: Mapped[str] = mapped_column(
resp_company_id = mapped_column(ForeignKey("companies.id")) String, nullable=True, comment="Build UUID"
resp_company_uu_id = mapped_column(String, nullable=True, comment="Company UUID") )
resp_company_id: Mapped[Identity] = mapped_column(ForeignKey("companies.id"))
resp_company_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Company UUID"
)
contact_id: Mapped[Identity] = mapped_column(
ForeignKey("contracts.id"), nullable=True, comment="Contract id"
)
contact_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Contract UUID"
)
buildings: Mapped["Build"] = relationship( buildings: Mapped["Build"] = relationship(
"Build", "Build",
@ -93,11 +106,11 @@ class BuildDecisionBook(CrudCollection):
@classmethod @classmethod
def retrieve_active_rbm(cls): def retrieve_active_rbm(cls):
related_build = Build.find_one(id=cls.build_id) related_build = Build.find_one(id=cls.build_id)
related_date = DateTimeLocal.get(str(related_build.build_date)) related_date = system_arrow.get(related_build.build_date)
date_processed = related_date.replace( date_processed = related_date.replace(
year=DateTimeLocal.now().date().year, month=related_date.month, day=1 year=system_arrow.now().date().year, month=related_date.month, day=1
) )
if DateTimeLocal.now().date() <= date_processed: if system_arrow.now().date() <= date_processed:
book = cls.filter_active( book = cls.filter_active(
cls.expiry_ends <= date_processed, cls.expiry_ends <= date_processed,
cls.decision_type == "RBM", cls.decision_type == "RBM",
@ -111,7 +124,6 @@ class BuildDecisionBook(CrudCollection):
@classmethod @classmethod
def select_action(cls, duty_id, token=None): def select_action(cls, duty_id, token=None):
from database_sql_models import Companies
related_companies = Companies.select_action(duty_id=duty_id) related_companies = Companies.select_action(duty_id=duty_id)
related_companies_ids = list( related_companies_ids = list(
@ -123,7 +135,6 @@ class BuildDecisionBook(CrudCollection):
@classmethod @classmethod
def create_action(cls, data: InsertDecisionBook, token=None): def create_action(cls, data: InsertDecisionBook, token=None):
from database_sql_models import Build, Companies
data_dict = data.model_dump() data_dict = data.model_dump()
if building := Build.find_one(uu_id=data.build_uu_id): if building := Build.find_one(uu_id=data.build_uu_id):
@ -137,25 +148,33 @@ class BuildDecisionBook(CrudCollection):
status_code=status.HTTP_406_NOT_ACCEPTABLE, status_code=status.HTTP_406_NOT_ACCEPTABLE,
detail="Building must be given to create decision book.", detail="Building must be given to create decision book.",
) )
expiry_starts = datetime.strptime( expiry_starts = system_arrow.get(str(data_dict.get("expiry_starts"))).format(
str(data_dict.get("expiry_starts")), "%Y-%m-%d" "%Y-%m-%d"
) )
expiry_ends = datetime.strptime(str(data_dict.get("expiry_ends")), "%Y-%m-%d") data_dict["expiry_starts"] = str(expiry_starts)
data_dict["expiry_ends"] = expiry_ends.replace( expiry_ends = system_arrow.get(str(data_dict.get("expiry_ends"))).format(
month=expiry_ends.month + 1, day=1 "%Y-%m-%d"
) - timedelta(days=1) )
decision_book = BuildDecisionBook.filter_active( data_dict["expiry_ends"] = str(
expiry_ends.replace(month=expiry_ends.month + 1, day=1) - timedelta(days=1)
)
if decision_book := BuildDecisionBook.filter_all(
BuildDecisionBook.build_id == building.id, BuildDecisionBook.build_id == building.id,
BuildDecisionBook.expiry_ends > data_dict["expiry_starts"], BuildDecisionBook.expiry_ends > data_dict["expiry_starts"],
BuildDecisionBook.decision_type == data_dict.get("decision_type"), BuildDecisionBook.decision_type == data_dict.get("decision_type"),
) # Decision book is already exist ).count: # Decision book is already exist:
if decision_book.count: cls.raise_http_exception(
return status_code=status.HTTP_409_CONFLICT,
error_case="RECORDEXITS",
message="Decision Book is already exist.",
data=decision_book.get_dict(),
)
data_dict["expiry_starts"] = expiry_starts.replace(day=1) data_dict["expiry_starts"] = str(expiry_starts.replace(day=1))
data_dict["expiry_ends"] = expiry_ends.replace( data_dict["expiry_ends"] = str(
month=expiry_ends.month + 1, day=1 expiry_ends.replace(month=expiry_ends.month + 1, day=1) - timedelta(days=1)
) - timedelta(days=1) )
del data_dict["build_uu_id"], data_dict["resp_company_uu_id"] del data_dict["build_uu_id"], data_dict["resp_company_uu_id"]
return cls.find_or_create(**data_dict) return cls.find_or_create(**data_dict)
@ -174,13 +193,15 @@ class BuildDecisionBook(CrudCollection):
[True if letter in str(bank_date) else False for letter in ["-", " ", ":"]] [True if letter in str(bank_date) else False for letter in ["-", " ", ":"]]
): ):
bank_date = datetime.strptime(str(bank_date), "%Y-%m-%d %H:%M:%S") bank_date = datetime.strptime(str(bank_date), "%Y-%m-%d %H:%M:%S")
date_valid = self.expiry_starts < bank_date < self.expiry_ends date_valid = (
system_arrow.get(self.expiry_starts)
< system_arrow.get(bank_date)
< system_arrow.get(self.expiry_ends)
)
return date_valid and self.active and not self.deleted return date_valid and self.active and not self.deleted
@classmethod @classmethod
def retrieve_valid_book(cls, bank_date, iban): def retrieve_valid_book(cls, bank_date, iban):
from database_sql_models import BuildIbans
if all( if all(
[True if letter in str(bank_date) else False for letter in ["-", " ", ":"]] [True if letter in str(bank_date) else False for letter in ["-", " ", ":"]]
): ):
@ -206,19 +227,25 @@ class BuildDecisionBookInvitations(CrudCollection):
__tablename__ = "build_decision_book_invitations" __tablename__ = "build_decision_book_invitations"
__exclude__fields__ = [] __exclude__fields__ = []
build_id = mapped_column(Integer, nullable=False) build_id: Mapped[int] = mapped_column(Integer, nullable=False)
build_uu_id = mapped_column(String, nullable=True, comment="Build UUID") build_uu_id: Mapped[str] = mapped_column(
decision_book_id = mapped_column( String, nullable=True, comment="Build UUID"
)
decision_book_id: Mapped[Identity] = mapped_column(
ForeignKey("build_decision_book.id"), nullable=False ForeignKey("build_decision_book.id"), nullable=False
) )
decision_book_uu_id = mapped_column( decision_book_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Decision Book UUID" String, nullable=True, comment="Decision Book UUID"
) )
invitation_type = mapped_column(String, nullable=False, comment="Invite Type") invitation_type: Mapped[str] = mapped_column(
invitation_attempt = mapped_column(SmallInteger, server_default="1") String, nullable=False, comment="Invite Type"
living_part_count = mapped_column(SmallInteger, server_default="1") )
living_part_percentage = mapped_column(Numeric(10, 2), server_default="0.51") invitation_attempt: Mapped[int] = mapped_column(SmallInteger, server_default="1")
living_part_count: Mapped[int] = mapped_column(SmallInteger, server_default="1")
living_part_percentage: Mapped[float] = mapped_column(
Numeric(10, 2), server_default="0.51"
)
message = mapped_column(Text, nullable=True, comment="Invitation Message") message = mapped_column(Text, nullable=True, comment="Invitation Message")
planned_date = mapped_column( planned_date = mapped_column(
@ -299,7 +326,7 @@ class BuildDecisionBookPerson(CrudCollection):
__enum_list__ = [("management_typecode", "BuildManagementType", "bm")] __enum_list__ = [("management_typecode", "BuildManagementType", "bm")]
dues_percent_discount = mapped_column(SmallInteger, server_default="0") dues_percent_discount = mapped_column(SmallInteger, server_default="0")
dues_fix_discount = mapped_column(Numeric(10, 2), server_default="0") dues_fix_discount: Mapped[float] = mapped_column(Numeric(10, 2), server_default="0")
dues_discount_approval_date = mapped_column( dues_discount_approval_date = mapped_column(
TIMESTAMP, server_default="1900-01-01 00:00:00" TIMESTAMP, server_default="1900-01-01 00:00:00"
) )
@ -310,7 +337,9 @@ class BuildDecisionBookPerson(CrudCollection):
confirmed_date = mapped_column( confirmed_date = mapped_column(
TIMESTAMP, nullable=True, comment="Confirmation Date" TIMESTAMP, nullable=True, comment="Confirmation Date"
) )
token = mapped_column(String, server_default="", comment="Invitation Token") token: Mapped[str] = mapped_column(
String, server_default="", comment="Invitation Token"
)
vicarious_person_id = mapped_column( vicarious_person_id = mapped_column(
ForeignKey("people.id"), nullable=True, comment="Vicarious Person ID" ForeignKey("people.id"), nullable=True, comment="Vicarious Person ID"
@ -322,7 +351,9 @@ class BuildDecisionBookPerson(CrudCollection):
invite_id = mapped_column( invite_id = mapped_column(
ForeignKey("build_decision_book_invitations.id"), nullable=False ForeignKey("build_decision_book_invitations.id"), nullable=False
) )
invite_uu_id = mapped_column(String, nullable=False, comment="Invite UUID") invite_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Invite UUID"
)
build_decision_book_id = mapped_column( build_decision_book_id = mapped_column(
ForeignKey("build_decision_book.id"), nullable=False ForeignKey("build_decision_book.id"), nullable=False
@ -336,8 +367,8 @@ class BuildDecisionBookPerson(CrudCollection):
build_living_space_uu_id = mapped_column( build_living_space_uu_id = mapped_column(
String, nullable=True, comment="Living Space UUID" String, nullable=True, comment="Living Space UUID"
) )
person_id = mapped_column(ForeignKey("people.id"), nullable=False) person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"), nullable=False)
# person_uu_id = mapped_column(String, nullable=False, comment="Person UUID") # person_uu_id: Mapped[str] = mapped_column(String, nullable=False, comment="Person UUID")
__table_args__ = ( __table_args__ = (
Index( Index(
@ -359,8 +390,9 @@ class BuildDecisionBookPerson(CrudCollection):
return BuildDecisionBookPersonOccupants.filter_active(filter_records=False) return BuildDecisionBookPersonOccupants.filter_active(filter_records=False)
def add_occupant_type(self, occupant_type, build_living_space_id: int = None): def add_occupant_type(self, occupant_type, build_living_space_id: int = None):
from database_sql_models import Services from api_events.events.events.events_bind_services import (
from events.events_bind_services import ServiceBindOccupantEventMethods ServiceBindOccupantEventMethods,
)
book_dict = dict( book_dict = dict(
build_decision_book_person_id=self.id, build_decision_book_person_id=self.id,
@ -413,10 +445,10 @@ class BuildDecisionBookPerson(CrudCollection):
occupant_type_uu_id=str(occupant_type.uu_id), occupant_type_uu_id=str(occupant_type.uu_id),
person_id=living_space.person_id, person_id=living_space.person_id,
person_uu_id=str(living_space.person_uu_id), person_uu_id=str(living_space.person_uu_id),
expiry_starts=DateTimeLocal.get( expiry_starts=system_arrow.get(
decision_book.meeting_date decision_book.meeting_date
).__str__(), ).__str__(),
expiry_ends=DateTimeLocal.get(decision_book.meeting_date) expiry_ends=system_arrow.get(decision_book.meeting_date)
.shift(hours=23) .shift(hours=23)
.__str__(), .__str__(),
is_confirmed=True, is_confirmed=True,
@ -426,9 +458,7 @@ class BuildDecisionBookPerson(CrudCollection):
build_living_space_id=related_living_space.id, build_living_space_id=related_living_space.id,
service_id=related_service.id, service_id=related_service.id,
expires_at=str( expires_at=str(
DateTimeLocal.get(decision_book.meeting_date).shift( system_arrow.get(decision_book.meeting_date).shift(days=15)
days=15
)
), ),
) )
return person_occupants return person_occupants
@ -474,10 +504,16 @@ class BuildDecisionBookPersonOccupants(CrudCollection):
invite_id = mapped_column( invite_id = mapped_column(
ForeignKey("build_decision_book_invitations.id"), nullable=True ForeignKey("build_decision_book_invitations.id"), nullable=True
) )
invite_uu_id = mapped_column(String, nullable=True, comment="Invite UUID") invite_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Invite UUID"
)
occupant_type_id = mapped_column(ForeignKey("occupant_types.id"), nullable=False) occupant_type_id: Mapped[Identity] = mapped_column(
occupant_type_uu_id = mapped_column(String, nullable=True, comment="Occupant UUID") ForeignKey("occupant_types.id"), nullable=False
)
occupant_type_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Occupant UUID"
)
__table_args__ = ( __table_args__ = (
Index( Index(
@ -513,8 +549,12 @@ class BuildDecisionBookItems(CrudCollection):
Boolean, server_default="0", comment="Are payment Records Created" Boolean, server_default="0", comment="Are payment Records Created"
) )
info_type_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) info_type_id: Mapped[Identity] = mapped_column(
info_type_uu_id = mapped_column(String, nullable=True, comment="Info Type UUID") ForeignKey("api_enum_dropdown.id"), nullable=True
)
info_type_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Info Type UUID"
)
build_decision_book_id = mapped_column( build_decision_book_id = mapped_column(
ForeignKey("build_decision_book.id"), nullable=False ForeignKey("build_decision_book.id"), nullable=False
@ -536,7 +576,6 @@ class BuildDecisionBookItems(CrudCollection):
@classmethod @classmethod
def select_action(cls, duty_id, token=None): def select_action(cls, duty_id, token=None):
from database_sql_models import Companies
related_companies = Companies.select_action(duty_id=duty_id) related_companies = Companies.select_action(duty_id=duty_id)
related_companies_ids = list( related_companies_ids = list(
@ -579,7 +618,6 @@ class BuildDecisionBookItems(CrudCollection):
@classmethod @classmethod
def check_meeting_is_valid_to_start_add_attendance(cls, decision_book, token_dict): def check_meeting_is_valid_to_start_add_attendance(cls, decision_book, token_dict):
from database_sql_models import OccupantTypes
active_invite = ( active_invite = (
BuildDecisionBookInvitations.check_invites_are_ready_for_meeting( BuildDecisionBookInvitations.check_invites_are_ready_for_meeting(
@ -728,8 +766,10 @@ class BuildDecisionBookItemsUnapproved(CrudCollection):
decision_book_item_uu_id = mapped_column( decision_book_item_uu_id = mapped_column(
String, nullable=True, comment="Decision Book Item" String, nullable=True, comment="Decision Book Item"
) )
person_id = mapped_column(ForeignKey("people.id"), nullable=False) person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"), nullable=False)
person_uu_id = mapped_column(String, nullable=True, comment="Person UUID") person_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Person UUID"
)
build_decision_book_item = mapped_column( build_decision_book_item = mapped_column(
ForeignKey("build_decision_book_items.id"), nullable=False ForeignKey("build_decision_book_items.id"), nullable=False
) )
@ -762,14 +802,18 @@ class BuildDecisionBookPayments(CrudCollection):
payment_amount = mapped_column( payment_amount = mapped_column(
Numeric(16, 2), nullable=False, comment="Payment Amount" Numeric(16, 2), nullable=False, comment="Payment Amount"
) )
currency = mapped_column(String(8), server_default="TRY") currency: Mapped[str] = mapped_column(String(8), server_default="TRY")
payment_types_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) payment_types_id: Mapped[Identity] = mapped_column(
payment_types_uu_id = mapped_column(String, nullable=True, comment="Dues Type UUID") ForeignKey("api_enum_dropdown.id"), nullable=True
)
payment_types_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Dues Type UUID"
)
period_time = mapped_column(String(12)) period_time: Mapped[str] = mapped_column(String(12))
process_date_y = mapped_column(SmallInteger) process_date_y: Mapped[int] = mapped_column(SmallInteger)
process_date_m = mapped_column(SmallInteger) process_date_m: Mapped[int] = mapped_column(SmallInteger)
build_decision_book_item_id = mapped_column( build_decision_book_item_id = mapped_column(
ForeignKey("build_decision_book_items.id"), ForeignKey("build_decision_book_items.id"),
@ -780,21 +824,33 @@ class BuildDecisionBookPayments(CrudCollection):
String, nullable=True, comment="Decision Book Item UUID" String, nullable=True, comment="Decision Book Item UUID"
) )
decision_book_project_id = mapped_column( decision_book_project_id = mapped_column(
ForeignKey("build_decision_book_projects.id"), nullable=True, comment="Decision Book Project ID" ForeignKey("build_decision_book_projects.id"),
nullable=True,
comment="Decision Book Project ID",
) )
decision_book_project_uu_id = mapped_column( decision_book_project_uu_id = mapped_column(
String, nullable=True, comment="Decision Book Project UUID" String, nullable=True, comment="Decision Book Project UUID"
) )
build_parts_id = mapped_column(ForeignKey("build_parts.id"), nullable=False) build_parts_id: Mapped[Identity] = mapped_column(
build_parts_uu_id = mapped_column(String, nullable=True, comment="Build Part UUID") ForeignKey("build_parts.id"), nullable=False
)
build_parts_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Build Part UUID"
)
budget_records_id = mapped_column(ForeignKey("account_records.id")) budget_records_id: Mapped[Identity] = mapped_column(
budget_records_uu_id = mapped_column(String, nullable=True, comment="Budget UUID") ForeignKey("account_records.id")
accounting_id = mapped_column(ForeignKey("account_detail.id")) )
accounting_uu_id = mapped_column(String, nullable=True, comment="Accounting UUID") budget_records_uu_id: Mapped[str] = mapped_column(
# receive_debit_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) String, nullable=True, comment="Budget UUID"
# receive_debit_uu_id = mapped_column(String, nullable=True, comment="Debit UUID") )
accounting_id: Mapped[Identity] = mapped_column(ForeignKey("account_detail.id"))
accounting_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Accounting UUID"
)
# receive_debit_id: Mapped[Identity] = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
# receive_debit_uu_id: Mapped[str] = mapped_column(String, nullable=True, comment="Debit UUID")
# accounting: Mapped["AccountDetail"] = relationship( # accounting: Mapped["AccountDetail"] = relationship(
# "AccountDetail", # "AccountDetail",
@ -851,8 +907,10 @@ class BuildDecisionBookLegal(CrudCollection):
) )
period_stop_date = mapped_column(TIMESTAMP, server_default="2099-12-31 23:59:59") period_stop_date = mapped_column(TIMESTAMP, server_default="2099-12-31 23:59:59")
decision_book_pdf_path = mapped_column(String(128)) decision_book_pdf_path: Mapped[str] = mapped_column(String(128))
resp_company_total_wage = mapped_column(Numeric(10, 2), server_default="0") resp_company_total_wage: Mapped[float] = mapped_column(
Numeric(10, 2), server_default="0"
)
contact_agreement_path = mapped_column(String(128)) contact_agreement_path = mapped_column(String(128))
contact_agreement_date = mapped_column( contact_agreement_date = mapped_column(
TIMESTAMP, server_default="1900-01-01 00:00:00" TIMESTAMP, server_default="1900-01-01 00:00:00"
@ -861,12 +919,12 @@ class BuildDecisionBookLegal(CrudCollection):
lawsuits_type = mapped_column(String(1), server_default="C") lawsuits_type = mapped_column(String(1), server_default="C")
lawsuits_name = mapped_column(String(128)) lawsuits_name = mapped_column(String(128))
lawsuits_note = mapped_column(String(512)) lawsuits_note = mapped_column(String(512))
lawyer_cost = mapped_column(Numeric(20, 2)) lawyer_cost: Mapped[float] = mapped_column(Numeric(20, 2))
mediator_lawyer_cost = mapped_column(Numeric(20, 2)) mediator_lawyer_cost: Mapped[float] = mapped_column(Numeric(20, 2))
other_cost = mapped_column(Numeric(20, 2)) other_cost: Mapped[float] = mapped_column(Numeric(20, 2))
legal_cost = mapped_column(Numeric(20, 2)) legal_cost: Mapped[float] = mapped_column(Numeric(20, 2))
approved_cost = mapped_column(Numeric(20, 2)) approved_cost: Mapped[float] = mapped_column(Numeric(20, 2))
total_price = mapped_column(Numeric(20, 2)) total_price: Mapped[float] = mapped_column(Numeric(20, 2))
build_db_item_id = mapped_column( build_db_item_id = mapped_column(
ForeignKey("build_decision_book_items.id"), nullable=False ForeignKey("build_decision_book_items.id"), nullable=False
@ -874,13 +932,17 @@ class BuildDecisionBookLegal(CrudCollection):
build_db_item_uu_id = mapped_column( build_db_item_uu_id = mapped_column(
String, nullable=True, comment="Decision Book Item UUID" String, nullable=True, comment="Decision Book Item UUID"
) )
resp_attorney_id = mapped_column(ForeignKey("people.id"), nullable=False) resp_attorney_id: Mapped[Identity] = mapped_column(
ForeignKey("people.id"), nullable=False
)
resp_attorney_uu_id = mapped_column(String, nullable=True, comment="Attorney UUID") resp_attorney_uu_id = mapped_column(String, nullable=True, comment="Attorney UUID")
resp_attorney_company_id = mapped_column(ForeignKey("companies.id")) resp_attorney_company_id: Mapped[Identity] = mapped_column(
ForeignKey("companies.id")
)
resp_attorney_company_uu_id = mapped_column( resp_attorney_company_uu_id = mapped_column(
String, nullable=True, comment="Company UUID" String, nullable=True, comment="Company UUID"
) )
mediator_lawyer_person_id = mapped_column(ForeignKey("people.id")) mediator_lawyer_person_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"))
mediator_lawyer_person_uu_id = mapped_column( mediator_lawyer_person_uu_id = mapped_column(
String, nullable=True, comment="Mediator Lawyer UUID" String, nullable=True, comment="Mediator Lawyer UUID"
) )
@ -902,7 +964,9 @@ class BuildDecisionBookProjects(CrudCollection):
__tablename__ = "build_decision_book_projects" __tablename__ = "build_decision_book_projects"
__exclude__fields__ = [] __exclude__fields__ = []
project_no = mapped_column(String(12), nullable=True, comment="Project Number of Decision Book") project_no = mapped_column(
String(12), nullable=True, comment="Project Number of Decision Book"
)
project_name = mapped_column(String, nullable=False, comment="Project Name") project_name = mapped_column(String, nullable=False, comment="Project Name")
project_start_date = mapped_column( project_start_date = mapped_column(
TIMESTAMP, nullable=False, comment="Project Start Date" TIMESTAMP, nullable=False, comment="Project Start Date"
@ -914,33 +978,45 @@ class BuildDecisionBookProjects(CrudCollection):
decision_book_pdf_path = mapped_column(String) decision_book_pdf_path = mapped_column(String)
resp_company_fix_wage = mapped_column(Numeric(10, 2), server_default="0") resp_company_fix_wage: Mapped[float] = mapped_column(
is_out_sourced = mapped_column(Boolean, server_default="0") Numeric(10, 2), server_default="0"
contact_id = mapped_column(ForeignKey("contracts.id"), nullable=True, comment="Contract id") )
is_out_sourced: Mapped[bool] = mapped_column(Boolean, server_default="0")
contact_id = mapped_column(
ForeignKey("contracts.id"), nullable=True, comment="Contract id"
)
contact_uu_id = mapped_column(String, nullable=True, comment="Contract UUID") contact_uu_id = mapped_column(String, nullable=True, comment="Contract UUID")
meeting_date = mapped_column( meeting_date = mapped_column(
TIMESTAMP, server_default="1900-01-01 00:00:00", index=True TIMESTAMP, server_default="1900-01-01 00:00:00", index=True
) )
currency = mapped_column(String(8), server_default="TRY") currency = mapped_column(String(8), server_default="TRY")
bid_price = mapped_column(Numeric(16, 4), server_default="0") bid_price: Mapped[float] = mapped_column(Numeric(16, 4), server_default="0")
approved_price = mapped_column(Numeric(16, 4), server_default="0") approved_price: Mapped[float] = mapped_column(Numeric(16, 4), server_default="0")
final_price = mapped_column(Numeric(16, 4), server_default="0") final_price: Mapped[float] = mapped_column(Numeric(16, 4), server_default="0")
build_decision_book_id = mapped_column(ForeignKey("build_decision_book.id"), nullable=False) build_decision_book_id = mapped_column(
ForeignKey("build_decision_book.id"), nullable=False
)
build_decision_book_uu_id = mapped_column( build_decision_book_uu_id = mapped_column(
String, nullable=True, comment="Decision Book UUID" String, nullable=True, comment="Decision Book UUID"
) )
build_decision_book_item_id = mapped_column(ForeignKey("build_decision_book_items.id"), nullable=False) build_decision_book_item_id = mapped_column(
ForeignKey("build_decision_book_items.id"), nullable=False
)
build_decision_book_item_uu_id = mapped_column( build_decision_book_item_uu_id = mapped_column(
String, nullable=True, comment="Decision Book Item UUID" String, nullable=True, comment="Decision Book Item UUID"
) )
project_response_living_space_id = mapped_column( project_response_living_space_id = mapped_column(
ForeignKey("build_living_space.id"), nullable=True, comment="Project Response Person ID" ForeignKey("build_living_space.id"),
nullable=True,
comment="Project Response Person ID",
) )
project_response_living_space_uu_id = mapped_column( project_response_living_space_uu_id = mapped_column(
String, nullable=True, comment="Project Response Person UUID" String, nullable=True, comment="Project Response Person UUID"
) )
resp_company_id = mapped_column(ForeignKey("companies.id"), nullable=True) resp_company_id: Mapped[Identity] = mapped_column(
ForeignKey("companies.id"), nullable=True
)
resp_company_uu_id = mapped_column(String, nullable=True, comment="Company UUID") resp_company_uu_id = mapped_column(String, nullable=True, comment="Company UUID")
build_decision_book_item: Mapped["BuildDecisionBookItems"] = relationship( build_decision_book_item: Mapped["BuildDecisionBookItems"] = relationship(
@ -951,11 +1027,6 @@ class BuildDecisionBookProjects(CrudCollection):
@classmethod @classmethod
def select_action(cls, duty_id, token=None): def select_action(cls, duty_id, token=None):
from database_sql_models import (
Companies,
BuildDecisionBook,
BuildDecisionBookItems,
)
related_companies = Companies.select_action(duty_id=duty_id) related_companies = Companies.select_action(duty_id=duty_id)
related_companies_ids = list( related_companies_ids = list(
@ -983,8 +1054,6 @@ class BuildDecisionBookProjects(CrudCollection):
@classmethod @classmethod
def create_action(cls, data: InsertBuildDecisionBookProjects, token=None): def create_action(cls, data: InsertBuildDecisionBookProjects, token=None):
from database_sql_models import People, BuildDecisionBookItems, Companies
data_dict = data.dump() data_dict = data.dump()
BuildDecisionBookItems.pre_query = BuildDecisionBookItems.select_action( BuildDecisionBookItems.pre_query = BuildDecisionBookItems.select_action(
duty_id=token.duty_list["duty_id"] duty_id=token.duty_list["duty_id"]
@ -1040,9 +1109,9 @@ class BuildDecisionBookProjectPerson(CrudCollection):
__enum_list__ = [("management_typecode", "ProjectTeamTypes", "PTT-EMP")] __enum_list__ = [("management_typecode", "ProjectTeamTypes", "PTT-EMP")]
dues_percent_discount = mapped_column(SmallInteger, server_default="0") dues_percent_discount = mapped_column(SmallInteger, server_default="0")
job_fix_wage = mapped_column(Numeric(10, 2), server_default="0") job_fix_wage: Mapped[float] = mapped_column(Numeric(10, 2), server_default="0")
bid_price = mapped_column(Numeric(10, 2), server_default="0") bid_price: Mapped[float] = mapped_column(Numeric(10, 2), server_default="0")
decision_price = mapped_column(Numeric(10, 2), server_default="0") decision_price: Mapped[float] = mapped_column(Numeric(10, 2), server_default="0")
build_decision_book_project_id = mapped_column( build_decision_book_project_id = mapped_column(
ForeignKey("build_decision_book_projects.id"), nullable=False ForeignKey("build_decision_book_projects.id"), nullable=False
@ -1050,8 +1119,12 @@ class BuildDecisionBookProjectPerson(CrudCollection):
build_decision_book_project_uu_id = mapped_column( build_decision_book_project_uu_id = mapped_column(
String, nullable=True, comment="Decision Book Project UUID" String, nullable=True, comment="Decision Book Project UUID"
) )
living_space_id = mapped_column(ForeignKey("build_living_space.id"), nullable=False) living_space_id: Mapped[Identity] = mapped_column(
living_space_uu_id = mapped_column(String, nullable=True, comment="Living Space UUID") ForeignKey("build_living_space.id"), nullable=False
)
living_space_uu_id = mapped_column(
String, nullable=True, comment="Living Space UUID"
)
project_team_type_id = mapped_column( project_team_type_id = mapped_column(
ForeignKey("api_enum_dropdown.id"), nullable=True ForeignKey("api_enum_dropdown.id"), nullable=True
@ -1082,7 +1155,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# Numeric(20, 2), nullable=False, comment="Default Payment Amount" # Numeric(20, 2), nullable=False, comment="Default Payment Amount"
# ) # )
# #
# dues_types_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) # dues_types_id: Mapped[Identity] = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
# dues_types_uu_id = mapped_column(String, nullable=True, comment="Dues Type UUID") # dues_types_uu_id = mapped_column(String, nullable=True, comment="Dues Type UUID")
# build_decision_book_item_debits_id = mapped_column( # build_decision_book_item_debits_id = mapped_column(
# ForeignKey("build_decision_book_item_debits.id"), nullable=False # ForeignKey("build_decision_book_item_debits.id"), nullable=False
@ -1090,7 +1163,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# build_decision_book_item_debits_uu_id = mapped_column( # build_decision_book_item_debits_uu_id = mapped_column(
# String, nullable=True, comment="Decision Book Item Debit UUID" # String, nullable=True, comment="Decision Book Item Debit UUID"
# ) # )
# build_parts_id = mapped_column(ForeignKey("build_parts.id"), nullable=False) # build_parts_id: Mapped[Identity] = mapped_column(ForeignKey("build_parts.id"), nullable=False)
# build_parts_uu_id = mapped_column(String, nullable=True, comment="Build Part UUID") # build_parts_uu_id = mapped_column(String, nullable=True, comment="Build Part UUID")
# #
# # decision_books_item_debits: Mapped["BuildDecisionBookItemDebits"] = relationship( # # decision_books_item_debits: Mapped["BuildDecisionBookItemDebits"] = relationship(
@ -1219,7 +1292,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# __exclude__fields__ = [] # __exclude__fields__ = []
# __enum_list__ = [("dues_types", "BuildDuesTypes", "D")] # __enum_list__ = [("dues_types", "BuildDuesTypes", "D")]
# #
# dues_types_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True) # dues_types_id: Mapped[Identity] = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
# dues_types_uu_id = mapped_column(String, nullable=True, comment="Dues Type UUID") # dues_types_uu_id = mapped_column(String, nullable=True, comment="Dues Type UUID")
# # dues_values = mapped_column( # # dues_values = mapped_column(
# # MutableDict.as_mutable(JSONB()), # # MutableDict.as_mutable(JSONB()),
@ -1232,7 +1305,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# flat_payment = mapped_column( # flat_payment = mapped_column(
# Numeric(20, 2), nullable=True, comment="Flat Payment Amount" # Numeric(20, 2), nullable=True, comment="Flat Payment Amount"
# ) # )
# decision_taken = mapped_column(Boolean, server_default="0") # decision_taken: Mapped[bool] = mapped_column(Boolean, server_default="0")
# #
# build_decision_book_item_id = mapped_column( # build_decision_book_item_id = mapped_column(
# ForeignKey("build_decision_book_items.id"), nullable=False # ForeignKey("build_decision_book_items.id"), nullable=False
@ -1350,15 +1423,15 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# #
# item_order = mapped_column(SmallInteger, nullable=False, comment="Order Number") # item_order = mapped_column(SmallInteger, nullable=False, comment="Order Number")
# budget_type = mapped_column(String, nullable=False, comment="Budget Type") # budget_type = mapped_column(String, nullable=False, comment="Budget Type")
# plan_value = mapped_column(Numeric(10, 2), nullable=False, comment="Plan Value") # plan_value: Mapped[float] = mapped_column(Numeric(10, 2), nullable=False, comment="Plan Value")
# #
# line_comment = mapped_column(String(32), server_default="") # line_comment = mapped_column(String(32), server_default="")
# process_date_y = mapped_column(SmallInteger) # process_date_y: Mapped[int] = mapped_column(SmallInteger)
# process_date_m = mapped_column(SmallInteger) # process_date_m: Mapped[int] = mapped_column(SmallInteger)
# process_date_w = mapped_column(SmallInteger) # process_date_w: Mapped[int] = mapped_column(SmallInteger)
# period_time = mapped_column(String(12), server_default="") # period_time = mapped_column(String(12), server_default="")
# #
# build_decision_book_id = mapped_column(ForeignKey("build_decision_book.id")) # build_decision_book_id: Mapped[Identity] = mapped_column(ForeignKey("build_decision_book.id"))
# accounting_id = mapped_column(ForeignKey("account_detail.id")) # accounting_id = mapped_column(ForeignKey("account_detail.id"))
# #
# __table_args__ = ( # __table_args__ = (
@ -1377,7 +1450,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# #
# paid_date = mapped_column(TIMESTAMP, nullable=False, comment="Payment Due Date") # paid_date = mapped_column(TIMESTAMP, nullable=False, comment="Payment Due Date")
# period_time = mapped_column(String(12), server_default="") # period_time = mapped_column(String(12), server_default="")
# paid_value = mapped_column(Numeric(10, 2), server_default="0") # paid_value: Mapped[float] = mapped_column(Numeric(10, 2), server_default="0")
# #
# build_decision_book_budget_id = mapped_column( # build_decision_book_budget_id = mapped_column(
# ForeignKey("build_decision_book_budget.id"), nullable=False # ForeignKey("build_decision_book_budget.id"), nullable=False
@ -1566,7 +1639,7 @@ class BuildDecisionBookProjectPerson(CrudCollection):
# person_uu_id = mapped_column(String, nullable=False, comment="Person UUID") # person_uu_id = mapped_column(String, nullable=False, comment="Person UUID")
# #
# send_date = mapped_column(TIMESTAMP, nullable=False, comment="Confirmation Date") # send_date = mapped_column(TIMESTAMP, nullable=False, comment="Confirmation Date")
# is_confirmed = mapped_column(Boolean, server_default="0", comment="Message is Confirmed") # is_confirmed: Mapped[bool] = mapped_column(Boolean, server_default="0", comment="Message is Confirmed")
# confirmed_date = mapped_column(TIMESTAMP, nullable=True, comment="Confirmation Date") # confirmed_date = mapped_column(TIMESTAMP, nullable=True, comment="Confirmation Date")
# token = mapped_column(String, server_default="", comment="Invitation Token") # token = mapped_column(String, server_default="", comment="Invitation Token")
# #

View File

@ -1,14 +1,22 @@
from fastapi.exceptions import HTTPException from fastapi.exceptions import HTTPException
from databases import (
Addresses,
Duties,
)
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from sqlalchemy import String, Integer, Boolean, ForeignKey, Index from sqlalchemy import String, Integer, Boolean, ForeignKey, Index, Identity
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
from api_configs import RelationAccess from api_configs import RelationAccess
from application.shared_classes import SelectAction, Explanation from databases.extensions import SelectAction, Explanation
from validations import InsertCompany, UpdateCompany from api_validations.validations_request import (
from validations.company import MatchCompany2Company InsertCompany,
from valids.auth.token_validations import EmployeeTokenObject UpdateCompany,
MatchCompany2Company,
)
from api_objects.auth.token_objects import EmployeeTokenObject
class RelationshipDutyCompany(CrudCollection): class RelationshipDutyCompany(CrudCollection):
@ -28,19 +36,25 @@ class RelationshipDutyCompany(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__access_by__ = RelationAccess.SuperAccessList __access_by__ = RelationAccess.SuperAccessList
owner_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1 owner_id: Mapped[Identity] = mapped_column(
duties_id = mapped_column( ForeignKey("companies.id"), nullable=False
) # 1
duties_id: Mapped[Identity] = mapped_column(
ForeignKey("duties.id"), nullable=False ForeignKey("duties.id"), nullable=False
) # duty -> (n)employee Evyos LTD ) # duty -> (n)employee Evyos LTD
member_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 2, 3, 4 member_id: Mapped[Identity] = mapped_column(
parent_id = mapped_column(ForeignKey("companies.id"), nullable=True) # None ForeignKey("companies.id"), nullable=False
) # 2, 3, 4
parent_id: Mapped[Identity] = mapped_column(
ForeignKey("companies.id"), nullable=True
) # None
relationship_type = mapped_column( relationship_type: Mapped[str] = mapped_column(
String, nullable=True, server_default="Commercial" String, nullable=True, server_default="Commercial"
) # Commercial, Organization # Bulk ) # Commercial, Organization # Bulk
child_count = mapped_column(Integer) # 0 child_count: Mapped[int] = mapped_column(Integer) # 0
show_only = mapped_column(Boolean, server_default="0") show_only: Mapped[bool] = mapped_column(Boolean, server_default="0")
# related_company: Mapped[List["Companies"]] = relationship( # related_company: Mapped[List["Companies"]] = relationship(
# "Companies", # "Companies",
@ -50,7 +64,6 @@ class RelationshipDutyCompany(CrudCollection):
@classmethod @classmethod
def match_company_to_company_commercial(cls, data: MatchCompany2Company, token): def match_company_to_company_commercial(cls, data: MatchCompany2Company, token):
from database_sql_models import Companies, Duties
token_duties_id, token_company_id = token.get("duty_id"), token.get( token_duties_id, token_company_id = token.get("duty_id"), token.get(
"company_id" "company_id"
@ -90,7 +103,6 @@ class RelationshipDutyCompany(CrudCollection):
@classmethod @classmethod
def match_company_to_company_organization(cls, data: MatchCompany2Company, token): def match_company_to_company_organization(cls, data: MatchCompany2Company, token):
from database_sql_models import Companies, Duties
token_duties_id, token_company_id = token.get("duty_id"), token.get( token_duties_id, token_company_id = token.get("duty_id"), token.get(
"company_id" "company_id"
@ -119,7 +131,10 @@ class RelationshipDutyCompany(CrudCollection):
list_match_company_id.append(bulk_company) list_match_company_id.append(bulk_company)
for match_company_id in list_match_company_id: for match_company_id in list_match_company_id:
Duties.init_a_company_default_duties(company_id=match_company_id.id) Duties.init_a_company_default_duties(
company_id=match_company_id.id,
company_uu_id=str(match_company_id.uu_id),
)
RelationshipDutyCompany.find_or_create( RelationshipDutyCompany.find_or_create(
owner_id=token_company_id, owner_id=token_company_id,
duties_id=send_user_duties.id, duties_id=send_user_duties.id,
@ -303,23 +318,29 @@ class Companies(CrudCollection, SelectAction):
__many__table__ = RelationshipDutyCompany __many__table__ = RelationshipDutyCompany
__explain__ = AbstractCompany() __explain__ = AbstractCompany()
formal_name = mapped_column(String, nullable=False, comment="Formal Name") formal_name: Mapped[str] = mapped_column(
company_type = mapped_column(String, nullable=False, comment="Company Type") String, nullable=False, comment="Formal Name"
commercial_type = mapped_column(String, nullable=False, comment="Commercial Type") )
tax_no = mapped_column( company_type: Mapped[str] = mapped_column(
String, nullable=False, comment="Company Type"
)
commercial_type: Mapped[str] = mapped_column(
String, nullable=False, comment="Commercial Type"
)
tax_no: Mapped[str] = mapped_column(
String, index=True, unique=True, nullable=False, comment="Tax No" String, index=True, unique=True, nullable=False, comment="Tax No"
) )
public_name = mapped_column(String, comment="Public Name of a company") public_name: Mapped[str] = mapped_column(String, comment="Public Name of a company")
company_tag = mapped_column(String, comment="Company Tag") company_tag: Mapped[str] = mapped_column(String, comment="Company Tag")
default_lang_type = mapped_column(String, server_default="TR") default_lang_type: Mapped[str] = mapped_column(String, server_default="TR")
default_money_type = mapped_column(String, server_default="TL") default_money_type: Mapped[str] = mapped_column(String, server_default="TL")
is_commercial = mapped_column(Boolean, server_default="False") is_commercial: Mapped[bool] = mapped_column(Boolean, server_default="False")
is_blacklist = mapped_column(Boolean, server_default="False") is_blacklist: Mapped[bool] = mapped_column(Boolean, server_default="False")
parent_id = mapped_column(Integer, nullable=True) parent_id = mapped_column(Integer, nullable=True)
workplace_no = mapped_column(String, nullable=True) workplace_no: Mapped[str] = mapped_column(String, nullable=True)
official_address_id = mapped_column(ForeignKey("addresses.id")) official_address_id: Mapped[Identity] = mapped_column(ForeignKey("addresses.id"))
official_address_uu_id = mapped_column( official_address_uu_id = mapped_column(
String, nullable=True, comment="Official Address UUID" String, nullable=True, comment="Official Address UUID"
) )
@ -347,13 +368,13 @@ class Companies(CrudCollection, SelectAction):
from databases import Addresses, Duties from databases import Addresses, Duties
data_dict = data.model_dump() data_dict = data.model_dump()
if cls.filter_one(cls.tax_no==str(data.tax_no).strip()): if cls.filter_one(cls.tax_no == str(data.tax_no).strip()):
raise Exception( raise Exception(
"Company already exists. Please ask supervisor to make company visible for your duty." "Company already exists. Please ask supervisor to make company visible for your duty."
) )
official_address = Addresses.filter_one( official_address = Addresses.filter_one(
Addresses.uu_id==data.official_address_uu_id Addresses.uu_id == data.official_address_uu_id
) )
if not official_address: if not official_address:
raise HTTPException( raise HTTPException(
@ -402,8 +423,6 @@ class Companies(CrudCollection, SelectAction):
@classmethod @classmethod
def update_action(cls, data: UpdateCompany, token): def update_action(cls, data: UpdateCompany, token):
from database_sql_models import Addresses
data_dict = data.excluded_dump() data_dict = data.excluded_dump()
duty_id = token.get("duty_id") duty_id = token.get("duty_id")
company_id = token.get("company_id") company_id = token.get("company_id")
@ -412,7 +431,7 @@ class Companies(CrudCollection, SelectAction):
data_dict["official_address_id"] = official_address.id data_dict["official_address_id"] = official_address.id
del data_dict["official_address_uu_id"], data_dict["company_uu_id"] del data_dict["official_address_uu_id"], data_dict["company_uu_id"]
company_to_update = cls.select_action( company_to_update = cls.select_action(
duty_id=duty_id, duty_id_list=[duty_id],
filter_expr=[ filter_expr=[
cls.uu_id == data.company_uu_id, cls.uu_id == data.company_uu_id,
RelationshipDutyCompany.parent_id == company_id, RelationshipDutyCompany.parent_id == company_id,

View File

@ -1,5 +1,5 @@
from sqlalchemy import String, Integer, ForeignKey, Index, Boolean from sqlalchemy import String, Integer, ForeignKey, Index, Boolean, Identity
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
@ -13,13 +13,17 @@ class Departments(CrudCollection):
department_code = mapped_column( department_code = mapped_column(
String(16), nullable=False, index=True, comment="Department Code" String(16), nullable=False, index=True, comment="Department Code"
) )
department_name = mapped_column( department_name: Mapped[str] = mapped_column(
String(128), nullable=False, comment="Department Name" String(128), nullable=False, comment="Department Name"
) )
department_description = mapped_column(String, server_default="") department_description: Mapped[str] = mapped_column(String, server_default="")
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) company_id: Mapped[Identity] = mapped_column(
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID") ForeignKey("companies.id"), nullable=False
)
company_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Company UUID"
)
# @classmethod # @classmethod
# def create_action(cls, data: DepartmentsPydantic, token): # def create_action(cls, data: DepartmentsPydantic, token):
@ -35,9 +39,11 @@ class Duty(CrudCollection):
__tablename__ = "duty" __tablename__ = "duty"
__exclude__fields__ = [] __exclude__fields__ = []
duty_name = mapped_column(String, unique=True, nullable=False, comment="Duty Name") duty_name: Mapped[str] = mapped_column(
duty_code = mapped_column(String, nullable=False, comment="Duty Code") String, unique=True, nullable=False, comment="Duty Name"
duty_description = mapped_column(String, comment="Duty Description") )
duty_code: Mapped[str] = mapped_column(String, nullable=False, comment="Duty Code")
duty_description: Mapped[str] = mapped_column(String, comment="Duty Description")
# @classmethod # @classmethod
# def create_action(cls, data: InsertCompanyDuty, token): # def create_action(cls, data: InsertCompanyDuty, token):
@ -60,15 +66,21 @@ class Duties(CrudCollection):
users_default_duty = mapped_column( users_default_duty = mapped_column(
ForeignKey("duty.id"), nullable=True, comment="Default Duty for Users" ForeignKey("duty.id"), nullable=True, comment="Default Duty for Users"
) )
company_id = mapped_column(Integer) company_id: Mapped[int] = mapped_column(Integer)
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID") company_uu_id: Mapped[str] = mapped_column(
duties_id = mapped_column(ForeignKey("duty.id"), nullable=False) String, nullable=False, comment="Company UUID"
duties_uu_id = mapped_column(String, nullable=False, comment="Duty UUID") )
duties_id: Mapped[Identity] = mapped_column(ForeignKey("duty.id"), nullable=False)
duties_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Duty UUID"
)
department_id = mapped_column( department_id = mapped_column(
ForeignKey("departments.id"), nullable=False, comment="Department ID" ForeignKey("departments.id"), nullable=False, comment="Department ID"
) )
department_uu_id = mapped_column(String, nullable=False, comment="Department UUID") department_uu_id: Mapped[str] = mapped_column(
# priority_id = mapped_column(ForeignKey("priority.id"), nullable=True) String, nullable=False, comment="Department UUID"
)
# priority_id: Mapped[Identity] = mapped_column(ForeignKey("priority.id"), nullable=True)
management_duty = mapped_column( management_duty = mapped_column(
Boolean, server_default="0" Boolean, server_default="0"
) # is this a prime Company Duty ??? ) # is this a prime Company Duty ???

View File

@ -3,11 +3,12 @@ from sqlalchemy import (
ForeignKey, ForeignKey,
Index, Index,
Numeric, Numeric,
Identity,
) )
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from validations import InsertCompanyEmployees from api_validations.validations_request import InsertCompanyEmployees
class Staff(CrudCollection): class Staff(CrudCollection):
@ -15,14 +16,20 @@ class Staff(CrudCollection):
__tablename__ = "staff" __tablename__ = "staff"
__exclude__fields__ = [] __exclude__fields__ = []
staff_description = mapped_column( staff_description: Mapped[str] = mapped_column(
String, server_default="", comment="Staff Description" String, server_default="", comment="Staff Description"
) )
staff_name = mapped_column(String, nullable=False, comment="Staff Name") staff_name: Mapped[str] = mapped_column(
staff_code = mapped_column(String, nullable=False, comment="Staff Code") String, nullable=False, comment="Staff Name"
)
staff_code: Mapped[str] = mapped_column(
String, nullable=False, comment="Staff Code"
)
duties_id = mapped_column(ForeignKey("duties.id"), nullable=False) duties_id: Mapped[Identity] = mapped_column(ForeignKey("duties.id"), nullable=False)
duties_uu_id = mapped_column(String, nullable=False, comment="Duty UUID") duties_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Duty UUID"
)
# people: Mapped["People"] = relationship( # people: Mapped["People"] = relationship(
# "People", back_populates="employees", foreign_keys=[people_id], uselist=True # "People", back_populates="employees", foreign_keys=[people_id], uselist=True
@ -33,7 +40,7 @@ class Staff(CrudCollection):
@classmethod @classmethod
def create_action(cls, data: InsertCompanyEmployees): def create_action(cls, data: InsertCompanyEmployees):
from database_sql_models import Duties from databases import Duties
data_dict = data.model_dump() data_dict = data.model_dump()
if duty := Duties.find_one(uu_id=data.duty_uu_id): if duty := Duties.find_one(uu_id=data.duty_uu_id):
@ -56,10 +63,14 @@ class Employees(CrudCollection):
__tablename__ = "employees" __tablename__ = "employees"
__exclude__fields__ = [] __exclude__fields__ = []
staff_id = mapped_column(ForeignKey("staff.id")) staff_id: Mapped[Identity] = mapped_column(ForeignKey("staff.id"))
staff_uu_id = mapped_column(String, nullable=False, comment="Staff UUID") staff_uu_id: Mapped[str] = mapped_column(
people_id = mapped_column(ForeignKey("people.id"), nullable=True) String, nullable=False, comment="Staff UUID"
people_uu_id = mapped_column(String, nullable=True, comment="People UUID") )
people_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"), nullable=True)
people_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="People UUID"
)
__table_args__ = ( __table_args__ = (
Index("employees_ndx_00", people_id, staff_id, unique=True), Index("employees_ndx_00", people_id, staff_id, unique=True),
@ -72,12 +83,18 @@ class EmployeeHistory(CrudCollection):
__tablename__ = "employee_history" __tablename__ = "employee_history"
__exclude__fields__ = [] __exclude__fields__ = []
staff_id = mapped_column(ForeignKey("staff.id"), nullable=False, comment="Staff ID") staff_id: Mapped[Identity] = mapped_column(
staff_uu_id = mapped_column(String, nullable=False, comment="Staff UUID") ForeignKey("staff.id"), nullable=False, comment="Staff ID"
people_id = mapped_column( )
staff_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="Staff UUID"
)
people_id: Mapped[Identity] = mapped_column(
ForeignKey("people.id"), nullable=False, comment="People ID" ForeignKey("people.id"), nullable=False, comment="People ID"
) )
people_uu_id = mapped_column(String, nullable=False, comment="People UUID") people_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="People UUID"
)
__table_args__ = ( __table_args__ = (
Index("_employee_history_ndx_00", people_id, staff_id), Index("_employee_history_ndx_00", people_id, staff_id),
@ -90,11 +107,17 @@ class EmployeesSalaries(CrudCollection):
__tablename__ = "employee_salaries" __tablename__ = "employee_salaries"
__exclude__fields__ = [] __exclude__fields__ = []
gross_salary = mapped_column(Numeric(20, 6), nullable=False, comment="Gross Salary") gross_salary: Mapped[float] = mapped_column(
net_salary = mapped_column(Numeric(20, 6), nullable=False, comment="Net Salary") Numeric(20, 6), nullable=False, comment="Gross Salary"
)
net_salary: Mapped[float] = mapped_column(
Numeric(20, 6), nullable=False, comment="Net Salary"
)
people_id = mapped_column(ForeignKey("people.id"), nullable=False) people_id: Mapped[Identity] = mapped_column(ForeignKey("people.id"), nullable=False)
people_uu_id = mapped_column(String, nullable=False, comment="People UUID") people_uu_id: Mapped[str] = mapped_column(
String, nullable=False, comment="People UUID"
)
# people: Mapped["People"] = relationship( # people: Mapped["People"] = relationship(
# "People", back_populates="employee_salaries", foreign_keys=[people_id] # "People", back_populates="employee_salaries", foreign_keys=[people_id]

View File

@ -67,8 +67,12 @@ class CrudMixin(Base, SmartQueryMixin, SessionMixin, FilterAttributes):
creds: Credentials = None # The credentials to use in the model. creds: Credentials = None # The credentials to use in the model.
client_arrow: DateTimeLocal = None # The arrow to use in the model. client_arrow: DateTimeLocal = None # The arrow to use in the model.
expiry_starts: Mapped[TIMESTAMP] = mapped_column(TIMESTAMP, server_default=func.now(), nullable=False) expiry_starts: Mapped[TIMESTAMP] = mapped_column(
expiry_ends: Mapped[TIMESTAMP] = mapped_column(TIMESTAMP, default="2099-12-31", server_default="2099-12-31") TIMESTAMP, server_default=func.now(), nullable=False
)
expiry_ends: Mapped[TIMESTAMP] = mapped_column(
TIMESTAMP, default="2099-12-31", server_default="2099-12-31"
)
@classmethod @classmethod
def extract_system_fields(cls, filter_kwargs: dict, create: bool = True): def extract_system_fields(cls, filter_kwargs: dict, create: bool = True):
@ -76,7 +80,9 @@ class CrudMixin(Base, SmartQueryMixin, SessionMixin, FilterAttributes):
Extracts the system fields from the given attributes. Extracts the system fields from the given attributes.
""" """
system_fields = filter_kwargs.copy() system_fields = filter_kwargs.copy()
extract_fields = cls.__system__fields__create__ if create else cls.__system__fields__update__ extract_fields = (
cls.__system__fields__create__ if create else cls.__system__fields__update__
)
for field in extract_fields: for field in extract_fields:
system_fields.pop(field, None) system_fields.pop(field, None)
return system_fields return system_fields
@ -84,6 +90,7 @@ class CrudMixin(Base, SmartQueryMixin, SessionMixin, FilterAttributes):
@classmethod @classmethod
def find_or_create(cls, **kwargs): def find_or_create(cls, **kwargs):
from api_library.date_time_actions.date_functions import system_arrow from api_library.date_time_actions.date_functions import system_arrow
""" """
Finds a record with the given attributes or creates it if it doesn't exist. Finds a record with the given attributes or creates it if it doesn't exist.
If found, sets is_found to True, otherwise False. If found, sets is_found to True, otherwise False.
@ -163,7 +170,9 @@ class CrudMixin(Base, SmartQueryMixin, SessionMixin, FilterAttributes):
self.flush() self.flush()
return self return self
def get_dict(self, exclude: list = None, include: list = None, include_joins: list = None): def get_dict(
self, exclude: list = None, include: list = None, include_joins: list = None
):
return_dict = {} return_dict = {}
if exclude: if exclude:
exclude.extend(list(set(self.__exclude__fields__).difference(exclude))) exclude.extend(list(set(self.__exclude__fields__).difference(exclude)))
@ -263,4 +272,4 @@ class CrudCollection(CrudMixin, BaseMixin, SmartQueryMixin):
deleted: Mapped[bool] = mapped_column(Boolean, server_default="0") deleted: Mapped[bool] = mapped_column(Boolean, server_default="0")
active: Mapped[bool] = mapped_column(Boolean, server_default="1") active: Mapped[bool] = mapped_column(Boolean, server_default="1")
is_notification_send: Mapped[bool] = mapped_column(Boolean, server_default="0") is_notification_send: Mapped[bool] = mapped_column(Boolean, server_default="0")
is_email_send: Mapped[bool] = mapped_column(Boolean, server_default="0") is_email_send: Mapped[bool] = mapped_column(Boolean, server_default="0")

View File

@ -8,8 +8,9 @@ from sqlalchemy import (
Boolean, Boolean,
Integer, Integer,
Index, Index,
Identity,
) )
from sqlalchemy.orm import mapped_column from sqlalchemy.orm import mapped_column, Mapped
class Events(CrudCollection): class Events(CrudCollection):
@ -21,20 +22,30 @@ class Events(CrudCollection):
__tablename__ = "events" __tablename__ = "events"
__exclude__fields__ = [] __exclude__fields__ = []
event_type = mapped_column(String, nullable=False, comment="default") event_type: Mapped[str] = mapped_column(String, nullable=False, comment="default")
function_code = mapped_column(String, nullable=False, comment="function code") function_code: Mapped[str] = mapped_column(
function_class = mapped_column(String, nullable=False, comment="class name") String, nullable=False, comment="function code"
)
function_class: Mapped[str] = mapped_column(
String, nullable=False, comment="class name"
)
# name = mapped_column(String, nullable=True) # form or page title # name: Mapped[str] = mapped_column(String, nullable=True) # form or page title
description = mapped_column(String, server_default="") # form or page description description: Mapped[str] = mapped_column(
property_description = mapped_column(String, server_default="") String, server_default=""
) # form or page description
property_description: Mapped[str] = mapped_column(String, server_default="")
marketing_layer = mapped_column(SmallInteger, server_default="3") marketing_layer = mapped_column(SmallInteger, server_default="3")
cost = mapped_column(Numeric(20, 2), server_default="0.00") cost: Mapped[float] = mapped_column(Numeric(20, 2), server_default="0.00")
unit_price = mapped_column(Numeric(20, 2), server_default="0.00") unit_price: Mapped[float] = mapped_column(Numeric(20, 2), server_default="0.00")
endpoint_id = mapped_column(ForeignKey("endpoint_restriction.id"), nullable=True) endpoint_id: Mapped[Identity] = mapped_column(
endpoint_uu_id = mapped_column(String, nullable=True, comment="Endpoint UUID") ForeignKey("endpoint_restriction.id"), nullable=True
)
endpoint_uu_id: Mapped[str] = mapped_column(
String, nullable=True, comment="Endpoint UUID"
)
__table_args__ = ({"comment": "Events Information"},) __table_args__ = ({"comment": "Events Information"},)
@ -47,9 +58,13 @@ class Modules(CrudCollection):
__tablename__ = "modules" __tablename__ = "modules"
__exclude__fields__ = [] __exclude__fields__ = []
module_name = mapped_column(String, nullable=False, comment="Module Name") module_name: Mapped[str] = mapped_column(
module_description = mapped_column(String, server_default="") String, nullable=False, comment="Module Name"
module_code = mapped_column(String, nullable=False, comment="Module Code") )
module_description: Mapped[str] = mapped_column(String, server_default="")
module_code: Mapped[str] = mapped_column(
String, nullable=False, comment="Module Code"
)
module_layer = mapped_column(Integer, nullable=False, comment="Module Layer") module_layer = mapped_column(Integer, nullable=False, comment="Module Layer")
is_default_module = mapped_column(Boolean, server_default="0") is_default_module = mapped_column(Boolean, server_default="0")
@ -77,12 +92,20 @@ class Services(CrudCollection):
__tablename__ = "services" __tablename__ = "services"
__exclude__fields__ = [] __exclude__fields__ = []
module_id = mapped_column(ForeignKey("modules.id"), nullable=False) module_id: Mapped[Identity] = mapped_column(
module_uu_id = mapped_column(String, nullable=False, comment="Module UUID") ForeignKey("modules.id"), nullable=False
service_name = mapped_column(String, nullable=False, comment="Service Name") )
service_description = mapped_column(String, server_default="") module_uu_id: Mapped[str] = mapped_column(
service_code = mapped_column(String, nullable=True, comment="Service Code") String, nullable=False, comment="Module UUID"
related_responsibility = mapped_column(String, server_default="") )
service_name: Mapped[str] = mapped_column(
String, nullable=False, comment="Service Name"
)
service_description: Mapped[str] = mapped_column(String, server_default="")
service_code: Mapped[str] = mapped_column(
String, nullable=True, comment="Service Code"
)
related_responsibility: Mapped[str] = mapped_column(String, server_default="")
__table_args__ = ({"comment": "Services Information"},) __table_args__ = ({"comment": "Services Information"},)
@ -95,9 +118,11 @@ class Service2Events(CrudCollection):
__tablename__ = "services2events" __tablename__ = "services2events"
__exclude__fields__ = [] __exclude__fields__ = []
service_id = mapped_column(ForeignKey("services.id"), nullable=False) service_id: Mapped[Identity] = mapped_column(
ForeignKey("services.id"), nullable=False
)
service_uu_id = mapped_column(String, nullable=False, comment="Service UUID") service_uu_id = mapped_column(String, nullable=False, comment="Service UUID")
event_id = mapped_column(ForeignKey("events.id"), nullable=False) event_id: Mapped[Identity] = mapped_column(ForeignKey("events.id"), nullable=False)
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID") event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
__table_args__ = ({"comment": "Service2Events Information"},) __table_args__ = ({"comment": "Service2Events Information"},)
@ -144,7 +169,7 @@ class Event2Occupant(CrudCollection):
build_living_space_uu_id = mapped_column( build_living_space_uu_id = mapped_column(
String, nullable=False, comment="Build Living Space UUID" String, nullable=False, comment="Build Living Space UUID"
) )
event_id = mapped_column(ForeignKey("events.id"), nullable=False) event_id: Mapped[Identity] = mapped_column(ForeignKey("events.id"), nullable=False)
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID") event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
__table_args__ = ( __table_args__ = (
@ -180,13 +205,19 @@ class ModulePrice(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
campaign_code = mapped_column(String, nullable=False, comment="Campaign Code") campaign_code = mapped_column(String, nullable=False, comment="Campaign Code")
module_id = mapped_column(ForeignKey("modules.id"), nullable=False) module_id: Mapped[Identity] = mapped_column(
ForeignKey("modules.id"), nullable=False
)
module_uu_id = mapped_column(String, nullable=False, comment="Module UUID") module_uu_id = mapped_column(String, nullable=False, comment="Module UUID")
service_id = mapped_column(ForeignKey("services.id"), nullable=False) service_id: Mapped[Identity] = mapped_column(
ForeignKey("services.id"), nullable=False
)
service_uu_id = mapped_column(String, nullable=False, comment="Service UUID") service_uu_id = mapped_column(String, nullable=False, comment="Service UUID")
event_id = mapped_column(ForeignKey("events.id"), nullable=False) event_id: Mapped[Identity] = mapped_column(ForeignKey("events.id"), nullable=False)
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID") event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
is_counted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22 is_counted_percentage: Mapped[float] = mapped_column(
Numeric(6, 2), server_default="0.00"
) # %22
discounted_price = mapped_column( discounted_price = mapped_column(
Numeric(20, 2), server_default="0.00" Numeric(20, 2), server_default="0.00"
) # Normal: 78.00 TL ) # Normal: 78.00 TL
@ -207,7 +238,7 @@ class ModulePrice(CrudCollection):
# __tablename__ = "modules2_occupant" # __tablename__ = "modules2_occupant"
# #
# #
# discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22 # discounted_percentage: Mapped[float] = mapped_column(Numeric(6, 2), server_default="0.00") # %22
# discounted_price = mapped_column( # discounted_price = mapped_column(
# Numeric(20, 2), server_default="0.00" # Numeric(20, 2), server_default="0.00"
# ) # Normal: 78.00 TL # ) # Normal: 78.00 TL
@ -230,7 +261,7 @@ class ModulePrice(CrudCollection):
# #
# __tablename__ = "modules2_employee" # __tablename__ = "modules2_employee"
# #
# discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22 # discounted_percentage: Mapped[float] = mapped_column(Numeric(6, 2), server_default="0.00") # %22
# discounted_price = mapped_column( # discounted_price = mapped_column(
# Numeric(20, 2), server_default="0.00" # Numeric(20, 2), server_default="0.00"
# ) # Normal: 78.00 TL # ) # Normal: 78.00 TL

View File

@ -5,7 +5,8 @@ from datetime import timedelta
from fastapi import HTTPException from fastapi import HTTPException
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from application.shared_classes import SelectAction, SelectActionWithEmployee from databases.extensions import SelectAction, SelectActionWithEmployee
from databases import Employees, Duties
from sqlalchemy import ( from sqlalchemy import (
String, String,
@ -19,11 +20,12 @@ from sqlalchemy import (
Integer, Integer,
Text, Text,
or_, or_,
Identity,
) )
from sqlalchemy.orm import mapped_column, relationship from sqlalchemy.orm import mapped_column, relationship, Mapped
from validations import InsertUsers, InsertPerson from api_validations.validations_request import InsertUsers, InsertPerson
from extensions.auth.login import UserLoginModule from databases.extensions.auth import UserLoginModule
class UsersTokens(CrudCollection): class UsersTokens(CrudCollection):
@ -31,11 +33,11 @@ class UsersTokens(CrudCollection):
__tablename__ = "users_tokens" __tablename__ = "users_tokens"
__exclude__fields__ = [] __exclude__fields__ = []
user_id = mapped_column(ForeignKey("users.id"), nullable=False) user_id: Mapped[Identity] = mapped_column(ForeignKey("users.id"), nullable=False)
token_type = mapped_column(String(16), server_default="RememberMe") token_type: Mapped[str] = mapped_column(String(16), server_default="RememberMe")
token = mapped_column(String, server_default="") token: Mapped[str] = mapped_column(String, server_default="")
domain = mapped_column(String, server_default="") domain: Mapped[str] = mapped_column(String, server_default="")
expires_at = mapped_column(TIMESTAMP, default=str(DateTimeLocal.shift(days=3))) expires_at = mapped_column(TIMESTAMP, default=str(DateTimeLocal.shift(days=3)))
# users = relationship("Users", back_populates="tokens", foreign_keys=[user_id]) # users = relationship("Users", back_populates="tokens", foreign_keys=[user_id])
@ -69,14 +71,16 @@ class Users(CrudCollection, UserLoginModule, SelectAction):
comment="Email 1/ Phone 2/ User Tag 3 All 111 Only 100", comment="Email 1/ Phone 2/ User Tag 3 All 111 Only 100",
) )
avatar = mapped_column(String, server_default="", comment="Avatar URL for the user") avatar: Mapped[str] = mapped_column(
hash_password = mapped_column( String, server_default="", comment="Avatar URL for the user"
)
hash_password: Mapped[str] = mapped_column(
String(256), server_default="", comment="Hashed password for security" String(256), server_default="", comment="Hashed password for security"
) )
password_token = mapped_column( password_token: Mapped[str] = mapped_column(
String(256), server_default="", comment="Token for password reset" String(256), server_default="", comment="Token for password reset"
) )
remember_me = mapped_column( remember_me: Mapped[bool] = mapped_column(
Boolean, server_default="0", comment="Flag to remember user login" Boolean, server_default="0", comment="Flag to remember user login"
) )
@ -92,7 +96,7 @@ class Users(CrudCollection, UserLoginModule, SelectAction):
server_default=func.now(), server_default=func.now(),
comment="Timestamp when password expiry begins", comment="Timestamp when password expiry begins",
) )
related_company = mapped_column(String, comment="Related Company UUID") related_company: Mapped[str] = mapped_column(String, comment="Related Company UUID")
person_id = mapped_column( person_id = mapped_column(
ForeignKey("people.id"), nullable=False, comment="Foreign key to person table" ForeignKey("people.id"), nullable=False, comment="Foreign key to person table"
@ -214,8 +218,6 @@ class Users(CrudCollection, UserLoginModule, SelectAction):
# } # }
def get_employee_and_duty_details(self): def get_employee_and_duty_details(self):
from database_sql_models.company.employee import Employees
from database_sql_models.company.department import Duties
found_person = People.find_one(id=self.person_id) found_person = People.find_one(id=self.person_id)
found_employees = Employees.filter_by_active( found_employees = Employees.filter_by_active(
@ -265,16 +267,20 @@ class RelationshipDutyPeople(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__access_by__ = RelationAccess.SuperAccessList __access_by__ = RelationAccess.SuperAccessList
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1, 2, 3 company_id: Mapped[Identity] = mapped_column(
ForeignKey("companies.id"), nullable=False
) # 1, 2, 3
duties_id = mapped_column( duties_id = mapped_column(
ForeignKey("duties.id"), nullable=False ForeignKey("duties.id"), nullable=False
) # duty -> (n)person Evyos LTD ) # duty -> (n)person Evyos LTD
member_id = mapped_column(ForeignKey("people.id"), nullable=False) # 2, 3, 4 member_id: Mapped[Identity] = mapped_column(
ForeignKey("people.id"), nullable=False
) # 2, 3, 4
relationship_type = mapped_column( relationship_type = mapped_column(
String, nullable=True, server_default="Employee" String, nullable=True, server_default="Employee"
) # Commercial ) # Commercial
show_only = mapped_column(Boolean, server_default="0") show_only: Mapped[bool] = mapped_column(Boolean, server_default="0")
# related_company: Mapped[List["Company"]] = relationship( # related_company: Mapped[List["Company"]] = relationship(
# "Company", # "Company",
@ -313,43 +319,45 @@ class People(CrudCollection, SelectAction):
"tax_no", "tax_no",
] ]
firstname = mapped_column( firstname: Mapped[str] = mapped_column(
String, nullable=False, comment="First name of the person" String, nullable=False, comment="First name of the person"
) )
surname = mapped_column(String(24), nullable=False, comment="Surname of the person") surname: Mapped[str] = mapped_column(
middle_name = mapped_column( String(24), nullable=False, comment="Surname of the person"
)
middle_name: Mapped[str] = mapped_column(
String, server_default="", comment="Middle name of the person" String, server_default="", comment="Middle name of the person"
) )
sex_code = mapped_column( sex_code: Mapped[str] = mapped_column(
String(1), nullable=False, comment="Sex code of the person (e.g., M/F)" String(1), nullable=False, comment="Sex code of the person (e.g., M/F)"
) )
person_ref = mapped_column( person_ref: Mapped[str] = mapped_column(
String, server_default="", comment="Reference ID for the person" String, server_default="", comment="Reference ID for the person"
) )
person_tag = mapped_column( person_tag: Mapped[str] = mapped_column(
String, server_default="", comment="Unique tag for the person" String, server_default="", comment="Unique tag for the person"
) )
# ENCRYPT DATA # ENCRYPT DATA
father_name = mapped_column( father_name: Mapped[str] = mapped_column(
String, server_default="", comment="Father's name of the person" String, server_default="", comment="Father's name of the person"
) )
mother_name = mapped_column( mother_name: Mapped[str] = mapped_column(
String, server_default="", comment="Mother's name of the person" String, server_default="", comment="Mother's name of the person"
) )
country_code = mapped_column( country_code: Mapped[str] = mapped_column(
String(4), server_default="TR", comment="Country code of the person" String(4), server_default="TR", comment="Country code of the person"
) )
national_identity_id = mapped_column( national_identity_id: Mapped[str] = mapped_column(
String, server_default="", comment="National identity ID of the person" String, server_default="", comment="National identity ID of the person"
) )
birth_place = mapped_column( birth_place: Mapped[str] = mapped_column(
String, server_default="", comment="Birth place of the person" String, server_default="", comment="Birth place of the person"
) )
birth_date = mapped_column( birth_date = mapped_column(
TIMESTAMP, server_default="1900-01-01", comment="Birth date of the person" TIMESTAMP, server_default="1900-01-01", comment="Birth date of the person"
) )
tax_no = mapped_column( tax_no: Mapped[str] = mapped_column(
String, server_default="", comment="Tax number of the person" String, server_default="", comment="Tax number of the person"
) )
# ENCRYPT DATA # ENCRYPT DATA
@ -366,15 +374,12 @@ class People(CrudCollection, SelectAction):
{"comment": "Person Information"}, {"comment": "Person Information"},
) )
@property @property
def full_name(self): def full_name(self):
return f"{self.firstname} {self.middle_name} {self.surname}" return f"{self.firstname} {self.middle_name} {self.surname}"
@classmethod @classmethod
def create_action(cls, data: InsertPerson, token): def create_action(cls, data: InsertPerson, token):
from database_sql_models import Duties
token_duties_id, token_company_id = ( token_duties_id, token_company_id = (
token.selected_company.duty_id, token.selected_company.duty_id,
token.selected_company.company_id, token.selected_company.company_id,
@ -417,14 +422,20 @@ class RelationshipEmployee2PostCode(CrudCollection):
__exclude__fields__ = [] __exclude__fields__ = []
__include__fields__ = [] __include__fields__ = []
company_id = mapped_column(ForeignKey("companies.id"), nullable=True) # 1, 2, 3 company_id: Mapped[Identity] = mapped_column(
employee_id = mapped_column(ForeignKey("employees.id"), nullable=False) ForeignKey("companies.id"), nullable=True
member_id = mapped_column(ForeignKey("address_postcode.id"), nullable=False) ) # 1, 2, 3
employee_id: Mapped[Identity] = mapped_column(
ForeignKey("employees.id"), nullable=False
)
member_id: Mapped[Identity] = mapped_column(
ForeignKey("address_postcode.id"), nullable=False
)
relationship_type = mapped_column( relationship_type = mapped_column(
String, nullable=True, server_default="Employee" String, nullable=True, server_default="Employee"
) # Commercial ) # Commercial
show_only = mapped_column(Boolean, server_default="0") show_only: Mapped[bool] = mapped_column(Boolean, server_default="0")
__table_args__ = ({"comment": "Build2Employee Relationship Information"},) __table_args__ = ({"comment": "Build2Employee Relationship Information"},)
@ -439,7 +450,7 @@ class AddressPostcode(CrudCollection, SelectActionWithEmployee):
__access_by__ = [] __access_by__ = []
__many__table__ = RelationshipEmployee2PostCode __many__table__ = RelationshipEmployee2PostCode
street_id = mapped_column(ForeignKey("address_street.id")) street_id: Mapped[Identity] = mapped_column(ForeignKey("address_street.id"))
street_uu_id = mapped_column(String, server_default="", comment="Street UUID") street_uu_id = mapped_column(String, server_default="", comment="Street UUID")
postcode = mapped_column(String(32), nullable=False, comment="Postcode") postcode = mapped_column(String(32), nullable=False, comment="Postcode")
@ -462,10 +473,12 @@ class Addresses(CrudCollection):
letter_address = mapped_column(String, nullable=False, comment="Address") letter_address = mapped_column(String, nullable=False, comment="Address")
short_letter_address = mapped_column(String, nullable=False, comment="Address") short_letter_address = mapped_column(String, nullable=False, comment="Address")
latitude = mapped_column(Numeric(20, 12), server_default="0") latitude: Mapped[float] = mapped_column(Numeric(20, 12), server_default="0")
longitude = mapped_column(Numeric(20, 12), server_default="0") longitude: Mapped[float] = mapped_column(Numeric(20, 12), server_default="0")
street_id = mapped_column(ForeignKey("address_street.id"), nullable=False) street_id: Mapped[Identity] = mapped_column(
ForeignKey("address_street.id"), nullable=False
)
street_uu_id = mapped_column(String, server_default="", comment="Street UUID") street_uu_id = mapped_column(String, server_default="", comment="Street UUID")
@classmethod @classmethod
@ -612,7 +625,7 @@ class AddressState(CrudCollection):
BigInteger, nullable=True, comment="Address Geographic Id" BigInteger, nullable=True, comment="Address Geographic Id"
) )
country_id = mapped_column(ForeignKey("address_country.id")) country_id: Mapped[Identity] = mapped_column(ForeignKey("address_country.id"))
country_uu_id = mapped_column(String, server_default="", comment="Country UUID") country_uu_id = mapped_column(String, server_default="", comment="Country UUID")
__table_args__ = ( __table_args__ = (
@ -643,7 +656,7 @@ class AddressCity(CrudCollection):
BigInteger, nullable=True, comment="Address Geographic Id" BigInteger, nullable=True, comment="Address Geographic Id"
) )
state_id = mapped_column(ForeignKey("address_state.id")) state_id: Mapped[Identity] = mapped_column(ForeignKey("address_state.id"))
state_uu_id = mapped_column(String, server_default="", comment="State UUID") state_uu_id = mapped_column(String, server_default="", comment="State UUID")
__table_args__ = ( __table_args__ = (
@ -702,7 +715,7 @@ class AddressLocality(CrudCollection):
type_code = mapped_column(String, nullable=True, comment="Type Name") type_code = mapped_column(String, nullable=True, comment="Type Name")
type_description = mapped_column(String, nullable=True, comment="Type Name") type_description = mapped_column(String, nullable=True, comment="Type Name")
gov_code = mapped_column(String(128), nullable=True, comment="Government Code") gov_code = mapped_column(String(128), nullable=True, comment="Government Code")
address_show = mapped_column(Boolean, server_default="1") address_show: Mapped[bool] = mapped_column(Boolean, server_default="1")
address_geographic_id = mapped_column( address_geographic_id = mapped_column(
BigInteger, nullable=True, comment="Address Geographic Id" BigInteger, nullable=True, comment="Address Geographic Id"
) )
@ -740,7 +753,7 @@ class AddressNeighborhood(CrudCollection):
type_code = mapped_column(String, nullable=True, comment="Type Name") type_code = mapped_column(String, nullable=True, comment="Type Name")
type_description = mapped_column(String, nullable=True, comment="Type Name") type_description = mapped_column(String, nullable=True, comment="Type Name")
gov_code = mapped_column(String(128), nullable=True, comment="Government Code") gov_code = mapped_column(String(128), nullable=True, comment="Government Code")
address_show = mapped_column(Boolean, server_default="1") address_show: Mapped[bool] = mapped_column(Boolean, server_default="1")
address_geographic_id = mapped_column( address_geographic_id = mapped_column(
BigInteger, nullable=True, comment="Address Geographic Id" BigInteger, nullable=True, comment="Address Geographic Id"
) )
@ -871,7 +884,7 @@ class OccupantTypes(CrudCollection):
occupant_code = mapped_column(String, server_default="") occupant_code = mapped_column(String, server_default="")
occupant_category = mapped_column(String, server_default="") occupant_category = mapped_column(String, server_default="")
occupant_category_type = mapped_column(String, server_default="") occupant_category_type = mapped_column(String, server_default="")
occupant_is_unique = mapped_column(Boolean, server_default="0") occupant_is_unique: Mapped[bool] = mapped_column(Boolean, server_default="0")
__table_args__ = ({"comment": "Occupant Types Information"},) __table_args__ = ({"comment": "Occupant Types Information"},)
@ -891,40 +904,52 @@ class Contracts(CrudCollection):
""" """
Contract class based on declarative_base and BaseMixin via session Contract class based on declarative_base and BaseMixin via session
""" """
__tablename__ = 'contracts'
__tablename__ = "contracts"
__exclude__fields__ = [] __exclude__fields__ = []
contract_type = mapped_column(String(5), nullable=False, comment="The code for personnel is P and the code for companies is C.") contract_type = mapped_column(
String(5),
nullable=False,
comment="The code for personnel is P and the code for companies is C.",
)
contract_title = mapped_column(String(255)) contract_title = mapped_column(String(255))
contract_details = mapped_column(Text) contract_details = mapped_column(Text)
contract_terms = mapped_column(Text) contract_terms = mapped_column(Text)
contract_code = mapped_column( contract_code = mapped_column(
String(100), nullable=False, comment="contract_code is the unique code given by the system." String(100),
nullable=False,
comment="contract_code is the unique code given by the system.",
) )
contract_date = mapped_column( contract_date = mapped_column(
TIMESTAMP, server_default="2099-12-31 23:59:59", TIMESTAMP,
server_default="2099-12-31 23:59:59",
comment="contract date is the date the contract is made. " comment="contract date is the date the contract is made. "
"expire start is the start date of the contract, expire en is the end date of the contract." "expire start is the start date of the contract, expire en is the end date of the contract.",
) )
company_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True) company_id = mapped_column(Integer, ForeignKey("companies.id"), nullable=True)
company_uu_id = mapped_column(String, server_default="", comment="Company UUID") company_uu_id = mapped_column(String, server_default="", comment="Company UUID")
person_id = mapped_column(Integer, ForeignKey('people.id'), nullable=True) person_id = mapped_column(Integer, ForeignKey("people.id"), nullable=True)
person_uu_id = mapped_column(String, server_default="", comment="Person UUID") person_uu_id = mapped_column(String, server_default="", comment="Person UUID")
@classmethod @classmethod
def retrieve_contact_no(cls): def retrieve_contact_no(cls):
import arrow import arrow
# todo When create record contract_code == below string # todo When create record contract_code == below string
related_date, counter = arrow.now(), 1 related_date, counter = arrow.now(), 1
return f"{related_date.date().year}{str(cls.contract_type)}{str(counter).zfill(6)}" return (
f"{related_date.date().year}{str(cls.contract_type)}{str(counter).zfill(6)}"
)
__table_args__ = ( __table_args__ = (
Index("_contract_ndx_01", contract_code, unique=True), Index("_contract_ndx_01", contract_code, unique=True),
{"comment": "Contract Information"} {"comment": "Contract Information"},
) )
# def selected_employee_and_duty_details(self, selected_duty_uu_id): # def selected_employee_and_duty_details(self, selected_duty_uu_id):
# from database_sql_models import ( # from database_sql_models import (

View File

@ -4,6 +4,7 @@ from sqlalchemy import (
UUID, UUID,
String, String,
text, text,
Identity,
) )
from sqlalchemy.orm import ( from sqlalchemy.orm import (
Mapped, Mapped,
@ -16,14 +17,16 @@ class ApiEnumDropdown(BaseCollection):
__tablename__ = "api_enum_dropdown" __tablename__ = "api_enum_dropdown"
__exclude__fields__ = ["enum_class"] __exclude__fields__ = ["enum_class"]
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[Identity] = mapped_column(primary_key=True)
uu_id: Mapped[str] = mapped_column( uu_id: Mapped[UUID] = mapped_column(
UUID, server_default=text("gen_random_uuid()"), index=True, unique=True UUID, server_default=text("gen_random_uuid()"), index=True, unique=True
) )
enum_class = mapped_column(String, nullable=False, comment="Enum Constant Name") enum_class: Mapped[str] = mapped_column(
key = mapped_column(String, nullable=False, comment="Enum Key") String, nullable=False, comment="Enum Constant Name"
value = mapped_column(String, nullable=False, comment="Enum Value") )
description = mapped_column(String, nullable=True) key: Mapped[str] = mapped_column(String, nullable=False, comment="Enum Key")
value: Mapped[str] = mapped_column(String, nullable=False, comment="Enum Value")
description: Mapped[str] = mapped_column(String, nullable=True)
__table_args__ = ({"comment": "Enum objets that are linked to tables"},) __table_args__ = ({"comment": "Enum objets that are linked to tables"},)

View File

@ -1,6 +1,3 @@
class AlchemyResponse: class AlchemyResponse:
""" """
alchemy_object = [AlchemyObject].filter_non_deleted() -> AlchemyResponse alchemy_object = [AlchemyObject].filter_non_deleted() -> AlchemyResponse

View File

@ -1,5 +1,6 @@
from sqlalchemy import Column, String from sqlalchemy import String
from databases.sql_models.core_mixin import CrudCollection from databases.sql_models.core_mixin import CrudCollection
from sqlalchemy.orm import mapped_column, Mapped
class EndpointRestriction(CrudCollection): class EndpointRestriction(CrudCollection):
@ -10,18 +11,18 @@ class EndpointRestriction(CrudCollection):
__tablename__ = "endpoint_restriction" __tablename__ = "endpoint_restriction"
__exclude__fields__ = [] __exclude__fields__ = []
endpoint_function = Column( endpoint_function: Mapped[str] = mapped_column(
String, server_default="", comment="Function name of the API endpoint" String, server_default="", comment="Function name of the API endpoint"
) )
endpoint_name = Column( endpoint_name: Mapped[str] = mapped_column(
String, server_default="", comment="Name of the API endpoint" String, server_default="", comment="Name of the API endpoint"
) )
endpoint_method = Column( endpoint_method: Mapped[str] = mapped_column(
String, server_default="", comment="HTTP method used by the endpoint" String, server_default="", comment="HTTP method used by the endpoint"
) )
endpoint_desc = Column( endpoint_desc: Mapped[str] = mapped_column(
String, server_default="", comment="Description of the endpoint" String, server_default="", comment="Description of the endpoint"
) )
endpoint_code = Column( endpoint_code: Mapped[str] = mapped_column(
String, server_default="", unique=True, comment="Unique code for the endpoint" String, server_default="", unique=True, comment="Unique code for the endpoint"
) )

View File

@ -32,7 +32,7 @@ class FilterAttributes:
status_code="HTTP_304_NOT_MODIFIED", status_code="HTTP_304_NOT_MODIFIED",
error_case=e.__class__.__name__, error_case=e.__class__.__name__,
data={}, data={},
message=str(e.__context__).split('\n')[0], message=str(e.__context__).split("\n")[0],
) )
def destroy(self): def destroy(self):
@ -50,7 +50,7 @@ class FilterAttributes:
status_code="HTTP_304_NOT_MODIFIED", status_code="HTTP_304_NOT_MODIFIED",
error_case=e.__class__.__name__, error_case=e.__class__.__name__,
data={}, data={},
message=str(e.__context__).split('\n')[0], message=str(e.__context__).split("\n")[0],
) )
@classmethod @classmethod
@ -93,6 +93,7 @@ class FilterAttributes:
def get_not_expired_query_arg(cls, *arg, expired=True): def get_not_expired_query_arg(cls, *arg, expired=True):
"""Add expiry_starts and expiry_ends to the query.""" """Add expiry_starts and expiry_ends to the query."""
from api_library.date_time_actions.date_functions import system_arrow from api_library.date_time_actions.date_functions import system_arrow
if expired: if expired:
arg_add = ( arg_add = (
*arg[0], *arg[0],
@ -103,7 +104,7 @@ class FilterAttributes:
return arg[0] return arg[0]
@classmethod @classmethod
def filter_by_all(cls, **kwargs): def filter_by_all(cls, **kwargs):
""" """
Filters all the records regardless of is_deleted, is_confirmed. Filters all the records regardless of is_deleted, is_confirmed.
""" """
@ -151,10 +152,12 @@ class FilterAttributes:
cls.__session__.rollback() cls.__session__.rollback()
raise HTTPException( raise HTTPException(
status_code=getattr(status, status_code, 'HTTP_404_NOT_FOUND'), status_code=getattr(status, status_code, "HTTP_404_NOT_FOUND"),
detail=dumps({ detail=dumps(
"data": data, {
"error": error_case, "data": data,
"message": message, "error": error_case,
}) "message": message,
}
),
) )

View File

@ -60,7 +60,6 @@ services:
networks: networks:
- network_store_services - network_store_services
depends_on: depends_on:
- wag_management_init_service
- grafana - grafana
wag_management_service_second: wag_management_service_second:
@ -74,7 +73,6 @@ services:
networks: networks:
- network_store_services - network_store_services
depends_on: depends_on:
- wag_management_init_service
- grafana - grafana
wag_management_init_service: wag_management_init_service:
@ -85,8 +83,7 @@ services:
networks: networks:
- network_store_services - network_store_services
depends_on: depends_on:
- postgres_commercial - wag_management_service
- commercial_memory_service
# - commercial_mongo_service # - commercial_mongo_service
wag_management_test_service: wag_management_test_service:

View File

@ -12,6 +12,7 @@ from handlers_exception import (
from prometheus_fastapi_instrumentator import Instrumentator from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Counter, Histogram from prometheus_client import Counter, Histogram
from service_app.app_runner_init import create_endpoints_from_api_functions
app = create_app() app = create_app()
Instrumentator().instrument(app=app).expose(app=app) Instrumentator().instrument(app=app).expose(app=app)
@ -23,12 +24,13 @@ app.add_middleware(
"allow_credentials": True, "allow_credentials": True,
"allow_methods": ["*"], "allow_methods": ["*"],
"allow_headers": ["*"], "allow_headers": ["*"],
} },
) )
app.add_middleware(AuthHeaderMiddleware) app.add_middleware(AuthHeaderMiddleware)
app.add_exception_handler(HTTPException, exception_handler_http) app.add_exception_handler(HTTPException, exception_handler_http)
app.add_exception_handler(Exception, exception_handler_exception) app.add_exception_handler(Exception, exception_handler_exception)
create_endpoints_from_api_functions(api_app=app)
# # Define a counter metric # # Define a counter metric
# REQUESTS_COUNT = Counter( # REQUESTS_COUNT = Counter(

View File

@ -0,0 +1,34 @@
from databases import EndpointRestriction
def create_endpoints_from_api_functions(api_app):
for route in api_app.routes:
route_path, route_summary = (
str(getattr(route, "path")),
str(getattr(route, "name")) or "",
)
# if route_path in Config.INSECURE_PATHS:
# continue
# print('route_path ', route_path, 'route_summary', route_summary)
create_dict = dict(
is_confirmed=True,
active=True,
deleted=False,
is_notification_send=True,
)
methods = [method.lower() for method in getattr(route, "methods")]
for route_method in methods:
restriction = EndpointRestriction.find_or_create(
**dict(
endpoint_method=route_method,
endpoint_name=route_path,
endpoint_desc=route_summary.replace("_", " "),
endpoint_function=route_summary,
**create_dict,
)
)
if not restriction.is_found:
restriction.endpoint_code = f"AR{str(restriction.id).zfill(3)}"
restriction.save()
return

View File

@ -1,5 +1,3 @@
def create_app(): def create_app():
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.responses import JSONResponse from fastapi.responses import JSONResponse
@ -9,7 +7,6 @@ def create_app():
from api_configs import Config from api_configs import Config
import routers import routers
api_app = FastAPI(title=str(Config.TITLE), default_response_class=JSONResponse) api_app = FastAPI(title=str(Config.TITLE), default_response_class=JSONResponse)
@api_app.get("/", include_in_schema=False, summary=str(Config.DESCRIPTION)) @api_app.get("/", include_in_schema=False, summary=str(Config.DESCRIPTION))

View File

@ -6,4 +6,4 @@ from .api_exception_handlers.http_exception_handler import (
__all__ = [ __all__ = [
"exception_handler_http", "exception_handler_http",
"exception_handler_exception", "exception_handler_exception",
] ]

View File

@ -7,21 +7,23 @@ from fastapi.responses import JSONResponse
def exception_handler_http(request: Request, exc: HTTPException): def exception_handler_http(request: Request, exc: HTTPException):
print('headers', request.headers) print("headers", request.headers)
detail = loads(exc.detail) detail = loads(exc.detail)
return JSONResponse( return JSONResponse(
status_code=exc.status_code, status_code=exc.status_code,
content={ content={
"Data": detail.get('data', {}), "Data": detail.get("data", {}),
"Error": detail.get('error_case', 'UNKNOWN'), "Error": detail.get("error_case", "UNKNOWN"),
"Message": detail.get('message', 'An error occurred while processing the request') "Message": detail.get(
} "message", "An error occurred while processing the request"
),
},
) )
def exception_handler_exception(request: Request, exc: Exception): def exception_handler_exception(request: Request, exc: Exception):
print('headers', request.headers) print("headers", request.headers)
return JSONResponse( return JSONResponse(
status_code=status.HTTP_417_EXPECTATION_FAILED, content={"message": exc.__str__()} status_code=status.HTTP_417_EXPECTATION_FAILED,
content={"message": exc.__str__()},
) )

View File

@ -6,6 +6,7 @@ from starlette import status
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.base import BaseHTTPMiddleware
class MiddlewareLogs: class MiddlewareLogs:
@staticmethod @staticmethod
@ -65,7 +66,9 @@ def prepare_response_needs(response, start_time):
def check_if_path_secure(request, insecure_paths) -> bool: def check_if_path_secure(request, insecure_paths) -> bool:
return str(getattr(getattr(request, "url", None), "path", None)) not in insecure_paths return (
str(getattr(getattr(request, "url", None), "path", None)) not in insecure_paths
)
def check_if_token_is_not_valid(request, endpoint_name): def check_if_token_is_not_valid(request, endpoint_name):

View File

@ -1,3 +1 @@
__all__ = [] __all__ = []

View File

@ -15,7 +15,6 @@ from api_validations.core_response import return_json_response_from_alchemy
from databases import ( from databases import (
BuildArea, BuildArea,
Build, Build,
) )

View File

@ -2,11 +2,11 @@ from fastapi.routing import APIRouter
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import ( from api_validations.validations_request import (
InsertEmployees, InsertEmployees,
UnBindEmployees2People, UnBindEmployees2People,
BindEmployees2People, BindEmployees2People,
PatchRecord, PatchRecord,
ListOptions, ListOptions,
) )
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -2,7 +2,9 @@ from fastapi.routing import APIRouter
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import ( from api_validations.validations_request import (
DepartmentsPydantic, PatchRecord, ListOptions DepartmentsPydantic,
PatchRecord,
ListOptions,
) )
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -2,7 +2,10 @@ from fastapi.routing import APIRouter
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import ( from api_validations.validations_request import (
InsertPerson, UpdateUsers, PatchRecord, ListOptions InsertPerson,
UpdateUsers,
PatchRecord,
ListOptions,
) )
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -4,7 +4,10 @@ from fastapi.responses import JSONResponse
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import ( from api_validations.validations_request import (
InsertDecisionBook, UpdateDecisionBook, PatchRecord, ListOptions InsertDecisionBook,
UpdateDecisionBook,
PatchRecord,
ListOptions,
) )
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -1,7 +1,10 @@
from fastapi.routing import APIRouter from fastapi.routing import APIRouter
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import UpdateEndpointAccessList, InsertEndpointAccess from api_validations.validations_request import (
UpdateEndpointAccessList,
InsertEndpointAccess,
)
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -2,7 +2,10 @@ from fastapi.routing import APIRouter
from fastapi.requests import Request from fastapi.requests import Request
from api_validations.validations_request import ( from api_validations.validations_request import (
InsertUsers, UpdateUsers, PatchRecord, ListOptions InsertUsers,
UpdateUsers,
PatchRecord,
ListOptions,
) )
from api_services.redis.auth_actions.token import parse_token_object_to_dict from api_services.redis.auth_actions.token import parse_token_object_to_dict

View File

@ -1,6 +1,17 @@
from databases import (
Events,
Services,
Service2Events,
Employees,
Staff,
)
from api_events.events.events.events_bind_services import (
ServiceBindEmployeeEventMethods,
)
def create_all_events_from_actions(): def create_all_events_from_actions():
import api_events import api_events.events as events
from databases.sql_models import Events
active_confirmed = dict( active_confirmed = dict(
created_by="System", created_by="System",
@ -56,8 +67,7 @@ def create_all_events_from_actions():
def add_events_all_services_and_occupant_types(): def add_events_all_services_and_occupant_types():
from database_sql_models import Services, Service2Events import api_events.tasks2events as tasks2events
import tasks2events
active_confirmed = dict( active_confirmed = dict(
created_by="System", created_by="System",
@ -90,8 +100,6 @@ def add_events_all_services_and_occupant_types():
def add_events_to_system_super_user(): def add_events_to_system_super_user():
from events.events_bind_services import ServiceBindEmployeeEventMethods
from database_sql_models import Services, Employees, Staff
add_service = Services.find_one(service_code="SRE-SUE") add_service = Services.find_one(service_code="SRE-SUE")
if not add_service: if not add_service:
@ -109,31 +117,3 @@ def add_events_to_system_super_user():
service_id=add_service.id, service_id=add_service.id,
employee_id=add_employee.id, employee_id=add_employee.id,
) )
# super_user_service = Services.find_or_create(service_code="SRE-SU")
# if not super_user_service:
# raise Exception("Super user is service not found")
#
# user_default_service = Services.find_or_create(service_code="AUTH")
# if not user_default_service:
# raise Exception("AUTH service is not found")
#
# for item in SuperUserEventBlock():
# event_id, event_uu_id = item
# Service2Events.find_or_create(
# service_id=super_user_service.id,
# service_uu_id=str(super_user_service.uu_id),
# event_id=event_id,
# event_uu_id=event_uu_id,
# **active_confirmed,
# )
#
# for event_block in AuthDefaultEventBlock():
# event_id, event_uu_id = event_block
# Service2Events.find_or_create(
# service_id=user_default_service.id,
# service_uu_id=str(user_default_service.uu_id),
# event_id=event_id,
# event_uu_id=event_uu_id,
# **active_confirmed,
# )

View File

@ -3,11 +3,10 @@ from databases import MongoQueryIdentity, Event2Employee, OccupantTypes
def create_occupant_types_defaults(): def create_occupant_types_defaults():
""" """
occupant_category = mapped_column(String, server_default="") occupant_category = mapped_column(String, server_default="")
occupant_category_type = mapped_column(String, server_default="") occupant_category_type = mapped_column(String, server_default="")
occupant_is_unique = mapped_column(Boolean, server_default="0") occupant_is_unique = mapped_column(Boolean, server_default="0")
""" """
list_occupant_types = [ list_occupant_types = [
{ {
@ -146,7 +145,7 @@ def create_occupant_types_defaults():
def create_application_defaults(): def create_application_defaults():
from database_sql_models import ( from databases import (
Companies, Companies,
Departments, Departments,
Duty, Duty,

View File

@ -1,6 +1,13 @@
from json import loads from json import loads
from os import path from os import path
from databases import (
AddressCountry,
AddressCity,
AddressDistrict,
AddressLocality,
AddressNeighborhood,
AddressState,
)
path_to_folder = "initialize_app/default_inits" path_to_folder = "initialize_app/default_inits"
list_of_snippets = [ list_of_snippets = [
@ -13,9 +20,6 @@ list_of_snippets = [
def create_country_defaults(path_to_joined_folder, confirmed_by_system): def create_country_defaults(path_to_joined_folder, confirmed_by_system):
from database_sql_models import (
AddressCountry,
)
with open(path_to_joined_folder("countries.json"), "r") as file: with open(path_to_joined_folder("countries.json"), "r") as file:
countries = loads(file.read()) countries = loads(file.read())
@ -34,9 +38,6 @@ def create_country_defaults(path_to_joined_folder, confirmed_by_system):
def create_cities_defaults(path_to_joined_folder, confirmed_by_system, state_id): def create_cities_defaults(path_to_joined_folder, confirmed_by_system, state_id):
from database_sql_models import (
AddressCity,
)
with open(path_to_joined_folder("cities.json"), "r") as file: with open(path_to_joined_folder("cities.json"), "r") as file:
cities = loads(file.read()) cities = loads(file.read())
@ -57,10 +58,6 @@ def create_cities_defaults(path_to_joined_folder, confirmed_by_system, state_id)
def create_district_defaults(path_to_joined_folder, confirmed_by_system): def create_district_defaults(path_to_joined_folder, confirmed_by_system):
from database_sql_models import (
AddressCity,
AddressDistrict,
)
with open(path_to_joined_folder("district.json"), "r") as file: with open(path_to_joined_folder("district.json"), "r") as file:
districts = loads(file.read()) districts = loads(file.read())
@ -84,10 +81,6 @@ def create_district_defaults(path_to_joined_folder, confirmed_by_system):
def create_locality_defaults(path_to_joined_folder, confirmed_by_system): def create_locality_defaults(path_to_joined_folder, confirmed_by_system):
from database_sql_models import (
AddressDistrict,
AddressLocality,
)
with open(path_to_joined_folder("locality.json"), "r") as file: with open(path_to_joined_folder("locality.json"), "r") as file:
localities = loads(file.read()) localities = loads(file.read())
@ -113,11 +106,6 @@ def create_locality_defaults(path_to_joined_folder, confirmed_by_system):
def create_neighborhood_defaults(path_to_joined_folder, confirmed_by_system): def create_neighborhood_defaults(path_to_joined_folder, confirmed_by_system):
from database_sql_models import (
AddressLocality,
AddressNeighborhood,
AddressDistrict,
)
with open(path_to_joined_folder("neighborhood.json"), "r") as file: with open(path_to_joined_folder("neighborhood.json"), "r") as file:
neighborhoods = loads(file.read()) neighborhoods = loads(file.read())
@ -150,10 +138,6 @@ def create_neighborhood_defaults(path_to_joined_folder, confirmed_by_system):
def create_identity_address_defaults(): def create_identity_address_defaults():
from database_sql_models import (
AddressCountry,
AddressState,
)
print("Creating address defaults ------------------") print("Creating address defaults ------------------")

View File

@ -1,7 +1,11 @@
from databases import (
BuildTypes,
ApiEnumDropdown,
)
def init_api_enums_build_types(): def init_api_enums_build_types():
from database_sql_models import BuildTypes from api_validations.validations_request import InsertBuildTypes
from database_sql_models.others.enums import ApiEnumDropdown
from validations import InsertBuildTypes
insert_types = [ insert_types = [
{ {

View File

@ -1,49 +1,14 @@
import typing import typing
from database_sql_models import ( from databases import (
Modules, Modules,
Duty, Duty,
Services, Services,
Service2Events, Service2Events,
OccupantTypes, OccupantTypes,
EndpointRestriction,
) )
def create_endpoints_from_api_functions():
from app import app as api_app
for route in api_app.routes:
route_path, route_summary = (
str(getattr(route, "path")),
str(getattr(route, "name")) or "",
)
# if route_path in Config.INSECURE_PATHS:
# continue
# print('route_path ', route_path, 'route_summary', route_summary)
create_dict = dict(
is_confirmed=True,
active=True,
deleted=False,
is_notification_send=True,
)
methods = [method.lower() for method in getattr(route, "methods")]
for route_method in methods:
restriction = EndpointRestriction.find_or_create(
**dict(
endpoint_method=route_method,
endpoint_name=route_path,
endpoint_desc=route_summary.replace("_", " "),
endpoint_function=route_summary,
**create_dict,
)
)
if not restriction.is_found:
restriction.endpoint_code = f"AR{str(restriction.id).zfill(3)}"
restriction.save()
return
def create_services_building(module_dict: dict): def create_services_building(module_dict: dict):
""" """
4. Service [Bina] Yönetim - OPTIONAL 4. Service [Bina] Yönetim - OPTIONAL

View File

@ -1,5 +1,3 @@
def do_alembic(): def do_alembic():
from sqlalchemy import text from sqlalchemy import text
from alembic_generate import generate_alembic_with_session from alembic_generate import generate_alembic_with_session
@ -57,7 +55,7 @@ def create_application_defaults_func(create_address=False):
phone_code="90", phone_code="90",
country_id=country.id, country_id=country.id,
country_uu_id=str(country.uu_id), country_uu_id=str(country.uu_id),
**confirmed_dict **confirmed_dict,
) )
city = AddressCity.find_or_create( city = AddressCity.find_or_create(
city_name="ANKARA", city_name="ANKARA",
@ -65,14 +63,14 @@ def create_application_defaults_func(create_address=False):
licence_plate="06", licence_plate="06",
state_id=state.id, state_id=state.id,
state_uu_id=str(state.uu_id), state_uu_id=str(state.uu_id),
**confirmed_dict **confirmed_dict,
) )
district = AddressDistrict.find_or_create( district = AddressDistrict.find_or_create(
district_name="ÇANKAYA", district_name="ÇANKAYA",
district_code="1231", district_code="1231",
city_id=city.id, city_id=city.id,
city_uu_id=str(city.uu_id), city_uu_id=str(city.uu_id),
**confirmed_dict **confirmed_dict,
) )
locality = AddressLocality.find_or_create( locality = AddressLocality.find_or_create(
locality_name="MERKEZ", locality_name="MERKEZ",
@ -81,7 +79,7 @@ def create_application_defaults_func(create_address=False):
type_description=None, type_description=None,
district_id=district.id, district_id=district.id,
district_uu_id=str(district.uu_id), district_uu_id=str(district.uu_id),
**confirmed_dict **confirmed_dict,
) )
neighborhood = AddressNeighborhood.find_or_create( neighborhood = AddressNeighborhood.find_or_create(
neighborhood_name="AYRANCI MAHALLESİ", neighborhood_name="AYRANCI MAHALLESİ",
@ -90,7 +88,7 @@ def create_application_defaults_func(create_address=False):
type_description="MAHALLESİ", type_description="MAHALLESİ",
locality_id=locality.id, locality_id=locality.id,
locality_uu_id=str(locality.uu_id), locality_uu_id=str(locality.uu_id),
**confirmed_dict **confirmed_dict,
) )
street = AddressStreet.find_or_create( street = AddressStreet.find_or_create(
street_name="REŞAT NURİ CADDESİ", street_name="REŞAT NURİ CADDESİ",
@ -99,7 +97,7 @@ def create_application_defaults_func(create_address=False):
street_code="52270", street_code="52270",
neighborhood_id=neighborhood.id, neighborhood_id=neighborhood.id,
neighborhood_uu_id=str(neighborhood.uu_id), neighborhood_uu_id=str(neighborhood.uu_id),
**confirmed_dict **confirmed_dict,
) )
return return
@ -110,4 +108,3 @@ if __name__ == "__main__":
if init_alembic_address: if init_alembic_address:
do_alembic() do_alembic()
create_application_defaults_func(create_address=False) create_application_defaults_func(create_address=False)

View File

@ -1,4 +1,2 @@
if __name__ == "__main__": if __name__ == "__main__":
print("service_app_test is running") print("service_app_test is running")

View File

@ -3,16 +3,18 @@ from test_application.evyos.datas.get_occupants_codes import get_occupants_types
from test_application.evyos.datas.get_type_codes import get_type_codes_key_and_class from test_application.evyos.datas.get_type_codes import get_type_codes_key_and_class
decision_book_items_dict = lambda token, item_comment, info_type_uu_id, unit_price, is_fixed, st, ed: { decision_book_items_dict = (
"token": token, lambda token, item_comment, info_type_uu_id, unit_price, is_fixed, st, ed: {
"item_comment": f"Test {item_comment}", "token": token,
"info_type_uu_id": info_type_uu_id, "item_comment": f"Test {item_comment}",
"unit_price": unit_price, "info_type_uu_id": info_type_uu_id,
"unit_price_is_fixed": is_fixed, "unit_price": unit_price,
"debit_start_date": st, "unit_price_is_fixed": is_fixed,
"debit_end_date": ed, "debit_start_date": st,
**active_and_confirmed, "debit_end_date": ed,
} **active_and_confirmed,
}
)
def create_decision_book_items(decision_book_items): def create_decision_book_items(decision_book_items):
@ -70,8 +72,12 @@ def collect_invitation_to_building_residents(
def create_decision_book_items_with_occupant_user( def create_decision_book_items_with_occupant_user(
writers_token: str, unit_price: float, is_fixed: bool, info_type_uu_id: str, writers_token: str,
start_date: str = None, end_date: str = None unit_price: float,
is_fixed: bool,
info_type_uu_id: str,
start_date: str = None,
end_date: str = None,
): ):
print("create_decision_book_items_with_occupant_user : ", writers_token) print("create_decision_book_items_with_occupant_user : ", writers_token)
list_of_items = [ list_of_items = [
@ -82,7 +88,7 @@ def create_decision_book_items_with_occupant_user(
unit_price=unit_price, unit_price=unit_price,
is_fixed=is_fixed, is_fixed=is_fixed,
st=start_date, st=start_date,
ed=end_date ed=end_date,
), ),
] ]
for item in list_of_items: for item in list_of_items:
@ -92,14 +98,21 @@ def create_decision_book_items_with_occupant_user(
def run_decision_book_items( def run_decision_book_items(
writers_token, unit_price, info_type_uu_id, is_fixed, start_date=None, end_date=None writers_token, unit_price, info_type_uu_id, is_fixed, start_date=None, end_date=None
): ):
if start_date and end_date: if start_date and end_date:
create_decision_book_items_with_occupant_user( create_decision_book_items_with_occupant_user(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed, info_type_uu_id=info_type_uu_id, writers_token=writers_token,
start_date=start_date, end_date=end_date unit_price=unit_price,
is_fixed=is_fixed,
info_type_uu_id=info_type_uu_id,
start_date=start_date,
end_date=end_date,
) )
else: else:
create_decision_book_items_with_occupant_user( create_decision_book_items_with_occupant_user(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed, info_type_uu_id=info_type_uu_id, writers_token=writers_token,
unit_price=unit_price,
is_fixed=is_fixed,
info_type_uu_id=info_type_uu_id,
) )

View File

@ -20,7 +20,7 @@ login_creds_employee = {
"access_key": "karatay.berkay.sup@evyos.com.tr", "access_key": "karatay.berkay.sup@evyos.com.tr",
"password": "string", "password": "string",
"remember_me": False, "remember_me": False,
"password_token": "" "password_token": "",
} }
access_key_president = "bmanco@example.net" access_key_president = "bmanco@example.net"
login_creds_occupant = { login_creds_occupant = {
@ -28,7 +28,7 @@ login_creds_occupant = {
"access_key": access_key_president, "access_key": access_key_president,
"password": "string", "password": "string",
"remember_me": False, "remember_me": False,
"password_token": "o_2Y_yXS-cl6MxLbzLrXQetXTlDLD3UBDTQNa_mBMyzSOVIgx3LGbnufLRJjd4g6BWFbwVgJIUxbK-Pi0R5dwxfVJKyoEeDdej40uRHSsElKR16nvnqgFB_BJ4nmyN0KSunZHra5NqHJor17EGExOSmlttZV5dC7vFsrc-GUkg" "password_token": "o_2Y_yXS-cl6MxLbzLrXQetXTlDLD3UBDTQNa_mBMyzSOVIgx3LGbnufLRJjd4g6BWFbwVgJIUxbK-Pi0R5dwxfVJKyoEeDdej40uRHSsElKR16nvnqgFB_BJ4nmyN0KSunZHra5NqHJor17EGExOSmlttZV5dC7vFsrc-GUkg",
} }
wrt_creds_occupant = { wrt_creds_occupant = {
"domain": "evyos.com.tr", "domain": "evyos.com.tr",
@ -43,7 +43,10 @@ add_with_occupant = True
assign_people_to_create_item = 3 assign_people_to_create_item = 3
# selection_list = None # selection_list = None
selection_list = ["7e370616-7bcf-469f-b9a2-c0da55463939", "c2d385d8-b772-4ecd-be89-8c468738654a"] selection_list = [
"7e370616-7bcf-469f-b9a2-c0da55463939",
"c2d385d8-b772-4ecd-be89-8c468738654a",
]
# selection_list = None # selection_list = None
manager_token = "" manager_token = ""
writers_token = manager_token writers_token = manager_token
@ -109,8 +112,10 @@ if add_with_occupant:
)["data"]["uu_id"] )["data"]["uu_id"]
unit_price = 15.90 unit_price = 15.90
run_decision_book_items( run_decision_book_items(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed_price, writers_token=writers_token,
info_type_uu_id=info_type_d_uu_id unit_price=unit_price,
is_fixed=is_fixed_price,
info_type_uu_id=info_type_d_uu_id,
) )
is_fixed_price = True is_fixed_price = True
@ -120,8 +125,12 @@ if add_with_occupant:
start_date, end_date = "2024-11-01", "2025-02-01" start_date, end_date = "2024-11-01", "2025-02-01"
unit_price = 850 unit_price = 850
run_decision_book_items( run_decision_book_items(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed_price, writers_token=writers_token,
info_type_uu_id=info_type_a_uu_id, start_date=start_date, end_date=end_date unit_price=unit_price,
is_fixed=is_fixed_price,
info_type_uu_id=info_type_a_uu_id,
start_date=start_date,
end_date=end_date,
) )
info_type_a_uu_id = get_type_codes_key_and_class( info_type_a_uu_id = get_type_codes_key_and_class(
@ -129,8 +138,12 @@ if add_with_occupant:
)["data"]["uu_id"] )["data"]["uu_id"]
unit_price = 5000 unit_price = 5000
run_decision_book_items( run_decision_book_items(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed_price, writers_token=writers_token,
info_type_uu_id=info_type_a_uu_id, start_date=start_date, end_date=end_date unit_price=unit_price,
is_fixed=is_fixed_price,
info_type_uu_id=info_type_a_uu_id,
start_date=start_date,
end_date=end_date,
) )
info_type_a_uu_id = get_type_codes_key_and_class( info_type_a_uu_id = get_type_codes_key_and_class(
@ -138,8 +151,12 @@ if add_with_occupant:
)["data"]["uu_id"] )["data"]["uu_id"]
unit_price = 2000 unit_price = 2000
run_decision_book_items( run_decision_book_items(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed_price, writers_token=writers_token,
info_type_uu_id=info_type_a_uu_id, start_date=start_date, end_date=end_date unit_price=unit_price,
is_fixed=is_fixed_price,
info_type_uu_id=info_type_a_uu_id,
start_date=start_date,
end_date=end_date,
) )
info_type_a_uu_id = get_type_codes_key_and_class( info_type_a_uu_id = get_type_codes_key_and_class(
@ -147,7 +164,10 @@ if add_with_occupant:
)["data"]["uu_id"] )["data"]["uu_id"]
unit_price = 750 unit_price = 750
run_decision_book_items( run_decision_book_items(
writers_token=writers_token, unit_price=unit_price, is_fixed=is_fixed_price, writers_token=writers_token,
info_type_uu_id=info_type_a_uu_id, start_date=start_date, end_date=end_date unit_price=unit_price,
is_fixed=is_fixed_price,
info_type_uu_id=info_type_a_uu_id,
start_date=start_date,
end_date=end_date,
) )