first commit
This commit is contained in:
165
databases/__init__.py
Normal file
165
databases/__init__.py
Normal file
@@ -0,0 +1,165 @@
|
||||
# SQL Models
|
||||
from databases.sql_models.account.account import (
|
||||
AccountBooks,
|
||||
AccountCodeParser,
|
||||
AccountRecords,
|
||||
AccountCodes,
|
||||
AccountDetail,
|
||||
AccountMaster,
|
||||
)
|
||||
from databases.sql_models.account.iban import (
|
||||
BuildIbans,
|
||||
BuildIbanDescription,
|
||||
)
|
||||
from databases.sql_models.api.encrypter import (
|
||||
CrypterEngine
|
||||
)
|
||||
from databases.sql_models.building.build import (
|
||||
Build,
|
||||
BuildTypes,
|
||||
BuildParts,
|
||||
BuildArea,
|
||||
BuildSites,
|
||||
BuildLivingSpace,
|
||||
BuildPersonProviding,
|
||||
BuildCompaniesProviding,
|
||||
RelationshipEmployee2Build,
|
||||
)
|
||||
from databases.sql_models.building.decision_book import (
|
||||
BuildDecisionBook,
|
||||
BuildDecisionBookItems,
|
||||
BuildDecisionBookPerson,
|
||||
BuildDecisionBookLegal,
|
||||
BuildDecisionBookItemsUnapproved,
|
||||
BuildDecisionBookInvitations,
|
||||
BuildDecisionBookPayments,
|
||||
BuildDecisionBookProjects,
|
||||
BuildDecisionBookProjectPerson,
|
||||
BuildDecisionBookPersonOccupants,
|
||||
)
|
||||
from databases.sql_models.company.company import (
|
||||
Companies,
|
||||
RelationshipDutyCompany,
|
||||
)
|
||||
from databases.sql_models.company.employee import (
|
||||
Employees,
|
||||
EmployeesSalaries,
|
||||
EmployeeHistory,
|
||||
Staff,
|
||||
)
|
||||
from databases.sql_models.company.department import (
|
||||
Duty,
|
||||
Duties,
|
||||
Departments,
|
||||
)
|
||||
from databases.sql_models.event.event import (
|
||||
Modules,
|
||||
Services,
|
||||
Service2Events,
|
||||
Events,
|
||||
Event2Occupant,
|
||||
Event2Employee,
|
||||
)
|
||||
from databases.sql_models.identity.identity import (
|
||||
Addresses,
|
||||
AddressCity,
|
||||
AddressStreet,
|
||||
AddressLocality,
|
||||
AddressDistrict,
|
||||
AddressNeighborhood,
|
||||
AddressState,
|
||||
AddressCountry,
|
||||
AddressPostcode,
|
||||
AddressGeographicLocations,
|
||||
UsersTokens,
|
||||
OccupantTypes,
|
||||
People,
|
||||
Users,
|
||||
RelationshipDutyPeople,
|
||||
RelationshipEmployee2PostCode,
|
||||
Contracts,
|
||||
)
|
||||
from databases.sql_models.others.enums import (
|
||||
ApiEnumDropdown,
|
||||
)
|
||||
from databases.sql_models.rules.rules import (
|
||||
EndpointRestriction,
|
||||
)
|
||||
|
||||
#NO-SQL Models
|
||||
from databases.no_sql_models.mongo_database import (
|
||||
MongoQuery,
|
||||
)
|
||||
from databases.no_sql_models.identity import (
|
||||
MongoQueryIdentity,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AccountBooks",
|
||||
"AccountCodeParser",
|
||||
"AccountRecords",
|
||||
"AccountCodes",
|
||||
"AccountDetail",
|
||||
"AccountMaster",
|
||||
"BuildIbans",
|
||||
"BuildIbanDescription",
|
||||
"CrypterEngine",
|
||||
"Build",
|
||||
"BuildTypes",
|
||||
"BuildParts",
|
||||
"BuildArea",
|
||||
"BuildSites",
|
||||
"BuildLivingSpace",
|
||||
"BuildPersonProviding",
|
||||
"BuildCompaniesProviding",
|
||||
"BuildDecisionBook",
|
||||
"BuildDecisionBookItems",
|
||||
"BuildDecisionBookPerson",
|
||||
"BuildDecisionBookLegal",
|
||||
"BuildDecisionBookItemsUnapproved",
|
||||
"BuildDecisionBookInvitations",
|
||||
"BuildDecisionBookPayments",
|
||||
"BuildDecisionBookProjects",
|
||||
"BuildDecisionBookProjectPerson",
|
||||
"BuildDecisionBookPersonOccupants",
|
||||
"Companies",
|
||||
"RelationshipDutyCompany",
|
||||
"Employees",
|
||||
"EmployeesSalaries",
|
||||
"EmployeeHistory",
|
||||
"Staff",
|
||||
"Duty",
|
||||
"Duties",
|
||||
"Departments",
|
||||
"Modules",
|
||||
"Services",
|
||||
"Service2Events",
|
||||
"Events",
|
||||
"Event2Occupant",
|
||||
"Event2Employee",
|
||||
"Addresses",
|
||||
"AddressCity",
|
||||
"AddressStreet",
|
||||
"AddressLocality",
|
||||
"AddressDistrict",
|
||||
"AddressNeighborhood",
|
||||
"AddressState",
|
||||
"AddressCountry",
|
||||
"AddressPostcode",
|
||||
"AddressGeographicLocations",
|
||||
"UsersTokens",
|
||||
"OccupantTypes",
|
||||
"People",
|
||||
"Users",
|
||||
"RelationshipDutyPeople",
|
||||
"RelationshipEmployee2PostCode",
|
||||
"Contracts",
|
||||
"ApiEnumDropdown",
|
||||
"EndpointRestriction",
|
||||
"RelationshipEmployee2Build",
|
||||
# ------------------------------------------------
|
||||
"MongoQuery",
|
||||
"MongoQueryIdentity",
|
||||
]
|
||||
|
||||
|
||||
0
databases/no_sql_models/__init__.py
Normal file
0
databases/no_sql_models/__init__.py
Normal file
137
databases/no_sql_models/identity.py
Normal file
137
databases/no_sql_models/identity.py
Normal file
@@ -0,0 +1,137 @@
|
||||
import datetime
|
||||
|
||||
from fastapi import HTTPException
|
||||
from .validations import PasswordHistoryViaUser, DomainViaUser, AccessHistoryViaUser
|
||||
from .mongo_database import MongoQuery
|
||||
|
||||
|
||||
class MongoQueryIdentity:
|
||||
"""
|
||||
4ex. mongo_collection_name = str(Company.uu_id()) + "*" + str('UserPasswordHistory')
|
||||
"""
|
||||
|
||||
def __init__(self, company_uuid, storage_reasoning: str = None):
|
||||
self.company_uuid = company_uuid
|
||||
self.mongo_collection_base = str(company_uuid)
|
||||
if storage_reasoning:
|
||||
self.mongo_collection_name = (
|
||||
str(company_uuid) + "*" + str(storage_reasoning)
|
||||
)
|
||||
else:
|
||||
self.mongo_collection_name = str(company_uuid) + "*" + str("Domain")
|
||||
self.mongo_engine = MongoQuery(
|
||||
table_name=self.mongo_collection_name, database_name="mongo_database"
|
||||
)
|
||||
|
||||
def use_collection(self, storage_reasoning):
|
||||
self.mongo_collection_name = (
|
||||
str(self.company_uuid) + "*" + str(storage_reasoning)
|
||||
)
|
||||
self.mongo_engine = MongoQuery(
|
||||
table_name=self.mongo_collection_name, database_name="mongo_database"
|
||||
)
|
||||
|
||||
def create_domain_via_user(self, payload: DomainViaUser):
|
||||
self.use_collection("Domain")
|
||||
return self.mongo_engine.insert(
|
||||
payload={
|
||||
"user_uu_id": payload.user_uu_id,
|
||||
"other_domains_list": [payload.main_domain],
|
||||
"main_domain": payload.main_domain,
|
||||
"modified_at": datetime.datetime.now().timestamp(),
|
||||
}
|
||||
)
|
||||
|
||||
def update_domain_via_user(self, payload: DomainViaUser):
|
||||
self.use_collection("Domain")
|
||||
return self.mongo_engine.update(
|
||||
match=payload.user_uu_id,
|
||||
payload={
|
||||
"other_domains_list": payload.other_domains_list,
|
||||
"modified_at": datetime.datetime.now().timestamp(),
|
||||
},
|
||||
field="user_uu_id",
|
||||
)
|
||||
|
||||
def get_domain_via_user(self, user_uu_id):
|
||||
self.use_collection("Domain")
|
||||
return self.mongo_engine.get_one(match=str(user_uu_id), field="user_uu_id")
|
||||
|
||||
def refresh_password_history_via_user(self, payload: PasswordHistoryViaUser):
|
||||
self.use_collection("PasswordHistory")
|
||||
password_history_item = self.mongo_engine.get_one(
|
||||
match=payload.user_uu_id, field="user_uu_id"
|
||||
)
|
||||
if not password_history_item:
|
||||
self.mongo_engine.insert(
|
||||
payload={
|
||||
"user_uu_id": str(payload.user_uu_id),
|
||||
"password_history": [],
|
||||
}
|
||||
)
|
||||
|
||||
password_history_item = self.mongo_engine.get_one(
|
||||
match=payload.user_uu_id, field="user_uu_id"
|
||||
)
|
||||
password_history_list = password_history_item.get("password_history", [])
|
||||
hashed_password = payload.password_add.get("password")
|
||||
|
||||
for password_in_history in password_history_list:
|
||||
if password_in_history.get("password") == str(hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Password already used. Please enter a new password that you have not used last 3 times.",
|
||||
)
|
||||
|
||||
if len(password_history_list) > 3:
|
||||
password_history_list.pop(0)
|
||||
|
||||
password_history_list.append(payload.password_add)
|
||||
|
||||
return self.mongo_engine.update(
|
||||
match=payload.user_uu_id,
|
||||
payload={
|
||||
"password_history": password_history_list,
|
||||
"access_history_detail": payload.access_history_detail,
|
||||
"modified_at": datetime.datetime.now().timestamp(),
|
||||
},
|
||||
field="user_uu_id",
|
||||
)
|
||||
|
||||
def get_password_history_via_user(self, user_uu_id):
|
||||
self.use_collection("PasswordHistory")
|
||||
return self.mongo_engine.get_one(match=user_uu_id, field="user_uu_id")
|
||||
|
||||
def update_access_history_via_user(self, payload: AccessHistoryViaUser):
|
||||
self.use_collection("AccessHistory")
|
||||
if already_dict := self.get_access_history_via_user(
|
||||
user_uu_id=payload.user_uu_id
|
||||
):
|
||||
access_history = already_dict[0].get("access_history") or []
|
||||
access_history.append(payload.access_history)
|
||||
if len(access_history) > 60:
|
||||
access_history.pop(0)
|
||||
return self.mongo_engine.update(
|
||||
match=payload.user_uu_id,
|
||||
payload={
|
||||
"user_uu_id": payload.user_uu_id,
|
||||
"access_history": access_history,
|
||||
"modified_at": datetime.datetime.now().timestamp(),
|
||||
},
|
||||
field="user_uu_id",
|
||||
)
|
||||
return self.mongo_engine.insert(
|
||||
payload={
|
||||
"user_uu_id": payload.user_uu_id,
|
||||
"access_history": [payload.access_history],
|
||||
"modified_at": datetime.datetime.now().timestamp(),
|
||||
}
|
||||
)
|
||||
|
||||
def get_access_history_via_user(self, user_uu_id):
|
||||
self.use_collection("AccessHistory")
|
||||
return self.mongo_engine.filter_by(
|
||||
payload={"user_uu_id": user_uu_id},
|
||||
sort_by="modified_at",
|
||||
sort_direction="desc",
|
||||
)
|
||||
89
databases/no_sql_models/login_handlers.py
Normal file
89
databases/no_sql_models/login_handlers.py
Normal file
@@ -0,0 +1,89 @@
|
||||
# from loggers.loggers import LoginLogger
|
||||
|
||||
|
||||
def get_menu_from_mongo(user_id, company_name):
|
||||
from databases.no_sql_models.mongo_database import MongoQuery
|
||||
|
||||
mongo = MongoQuery(
|
||||
table_name=company_name.replace(" ", ""), database_name="mongo_database"
|
||||
)
|
||||
mongo_dict = mongo.parse_json(mongo.get_one(match=user_id, field="user_id")) or {}
|
||||
return mongo_dict.get("menu", [])
|
||||
|
||||
|
||||
def load_user_with_erp_details(found_user, access_dict: dict = None):
|
||||
duties = []
|
||||
employee = found_user.person.employee
|
||||
duty_dict = {}
|
||||
try:
|
||||
duty_dict = employee.duty.get_dict(
|
||||
include=["duty_name", "duty_code", "duty_description"]
|
||||
)
|
||||
duty_dict["buildings"] = []
|
||||
duty_dict["response_buildings"] = []
|
||||
duty_dict["department"] = employee.duty.department.get_dict(
|
||||
include=["department_name", "department_code"]
|
||||
)
|
||||
duty_dict["company"] = employee.duty.department.company.get_dict(
|
||||
include=["formal_name", "public_name", "tax_no", "default_lang_type"]
|
||||
)
|
||||
except Exception as e:
|
||||
# LoginLogger.log_exception(
|
||||
# {
|
||||
# "exc": e,
|
||||
# "user": found_user.uu_id,
|
||||
# "function": "load_user_with_erp_details",
|
||||
# }
|
||||
# )
|
||||
err = e
|
||||
print('MongoQuery load_user_with_erp_details', err)
|
||||
|
||||
|
||||
for building in list(set(employee.duty.department.company.response_buildings)):
|
||||
build_parts = []
|
||||
for part in building.parts:
|
||||
build_parts.append(
|
||||
part.get_dict(
|
||||
include=["uu_id", "part_name", "part_code", "part_description"]
|
||||
)
|
||||
)
|
||||
duty_dict["response_buildings"].append(
|
||||
{
|
||||
"build": building.get_dict(include=["build_name", "uu_id"]),
|
||||
"parts": build_parts,
|
||||
}
|
||||
)
|
||||
for building in list(set(employee.duty.department.company.buildings)):
|
||||
build_parts = []
|
||||
for part in building.parts:
|
||||
build_parts.append(
|
||||
part.get_dict(
|
||||
include=[
|
||||
"uu_id",
|
||||
"part_name",
|
||||
"part_code",
|
||||
"part_description",
|
||||
]
|
||||
)
|
||||
)
|
||||
duty_dict["buildings"].append(
|
||||
{
|
||||
"build": building.get_dict(include=["build_name", "uu_id"]),
|
||||
"parts": build_parts,
|
||||
}
|
||||
)
|
||||
duties.append(duty_dict)
|
||||
return_dict = access_dict if access_dict else {}
|
||||
return_dict.update(
|
||||
{
|
||||
"data": {
|
||||
"profile": found_user.get_dict(),
|
||||
"employee_info": duties,
|
||||
"menu": get_menu_from_mongo(
|
||||
found_user.id,
|
||||
company_name=duty_dict.get("company", {}).get("public_name", ""),
|
||||
),
|
||||
},
|
||||
}
|
||||
)
|
||||
return return_dict
|
||||
99
databases/no_sql_models/mongo_database.py
Normal file
99
databases/no_sql_models/mongo_database.py
Normal file
@@ -0,0 +1,99 @@
|
||||
import pymongo
|
||||
|
||||
from json import loads
|
||||
from bson import ObjectId, json_util
|
||||
from pydantic import BaseModel
|
||||
from api_configs import MongoConfig
|
||||
|
||||
from pymongo import MongoClient
|
||||
from pymongo.collection import Collection
|
||||
from pymongo.results import InsertManyResult
|
||||
# from configs import TestMongo as MongoConfig
|
||||
|
||||
|
||||
def parse_json(data):
|
||||
return loads(json_util.dumps(data))
|
||||
|
||||
|
||||
def create_database_client(url, database_name):
|
||||
return MongoClient(url)[database_name]
|
||||
|
||||
|
||||
class Paginate(BaseModel):
|
||||
pageSize: int = 10
|
||||
pageNumber: int = 1
|
||||
sortField: str = "_id"
|
||||
sortOrder: str = "desc"
|
||||
|
||||
def grab_paginates(self):
|
||||
size_ = self.pageSize
|
||||
return (
|
||||
size_,
|
||||
size_ * (self.pageNumber - 1),
|
||||
self.sortField,
|
||||
-1 if self.sortOrder == "desc" else 1,
|
||||
)
|
||||
|
||||
|
||||
class MongoQuery:
|
||||
|
||||
def __init__(self, table_name: str, database_name: str):
|
||||
database = MongoClient(MongoConfig.url)[database_name]
|
||||
if table_name not in database.collection_names():
|
||||
database.create_collection(name=table_name)
|
||||
self.table: Collection = database[table_name]
|
||||
|
||||
@staticmethod
|
||||
def grab_paginates(paginate):
|
||||
return (
|
||||
paginate.size,
|
||||
paginate.size * (paginate.page - 1),
|
||||
paginate.order_field,
|
||||
-1 if paginate.order_type == "desc" else 1,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def parse_json(data):
|
||||
return loads(json_util.dumps(data))
|
||||
|
||||
def insert(self, payload) -> InsertManyResult:
|
||||
return self.table.insert_many(documents=[payload])
|
||||
|
||||
def update(self, match, payload, field: str = "id"):
|
||||
if field == "id":
|
||||
filter_ = {"_id": ObjectId(match)}
|
||||
self.table.update_one(filter=filter_, update={"$set": payload})
|
||||
self.table.update_one(filter={field: match}, update={"$set": payload})
|
||||
|
||||
def get_one(self, match, field: str = "id"):
|
||||
if field == "id":
|
||||
return self.parse_json(
|
||||
data=self.table.find_one(filter={"_id": ObjectId(match)})
|
||||
)
|
||||
return self.parse_json(data=self.table.find_one(filter={field: match}))
|
||||
|
||||
def filter_by(self, payload, sort_by: str = "_id", sort_direction: str = "asc"):
|
||||
sort_direction = (
|
||||
pymongo.ASCENDING
|
||||
if str(sort_direction).lower() == "asc"
|
||||
else pymongo.DESCENDING
|
||||
)
|
||||
return_ = self.table.find(payload).sort(sort_by, sort_direction)
|
||||
return self.parse_json(data=return_)
|
||||
|
||||
def delete_one(self, match, field: str = "id"):
|
||||
if field == "id":
|
||||
self.table.delete_one(filter={"_id": ObjectId(match)})
|
||||
self.table.delete_one(filter={field: match})
|
||||
|
||||
def list_all(self, paginate: Paginate):
|
||||
size, skip, field, order = paginate.grab_paginates()
|
||||
return_ = self.table.find().sort([(field, order)]).skip(skip).limit(size)
|
||||
return self.table.count_documents({}), self.parse_json(data=return_)
|
||||
|
||||
def get_all(self):
|
||||
return_ = self.table.find()
|
||||
return self.table.count_documents({}), self.parse_json(data=return_)
|
||||
|
||||
|
||||
# Mongo = MongoQuery(table_name="XcompanyConfig", database_name="mongo_database")
|
||||
19
databases/no_sql_models/validations.py
Normal file
19
databases/no_sql_models/validations.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class DomainViaUser(BaseModel):
|
||||
user_uu_id: str
|
||||
main_domain: str
|
||||
other_domains_list: Optional[list] = None
|
||||
|
||||
|
||||
class PasswordHistoryViaUser(BaseModel):
|
||||
user_uu_id: str
|
||||
password_add: dict
|
||||
access_history_detail: Optional[dict]
|
||||
|
||||
|
||||
class AccessHistoryViaUser(BaseModel):
|
||||
user_uu_id: str
|
||||
access_history: dict
|
||||
0
databases/sql_models/__init__.py
Normal file
0
databases/sql_models/__init__.py
Normal file
588
databases/sql_models/account/account.py
Normal file
588
databases/sql_models/account/account.py
Normal file
@@ -0,0 +1,588 @@
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
from sqlalchemy.orm import mapped_column
|
||||
from sqlalchemy import (
|
||||
String,
|
||||
Integer,
|
||||
ForeignKey,
|
||||
Index,
|
||||
SmallInteger,
|
||||
Boolean,
|
||||
TIMESTAMP,
|
||||
Numeric,
|
||||
)
|
||||
|
||||
|
||||
class AccountBooks(CrudCollection):
|
||||
|
||||
__tablename__ = "account_books"
|
||||
__exclude__fields__ = []
|
||||
|
||||
country = mapped_column(String, nullable=False)
|
||||
branch_type = 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_uu_id = mapped_column(String, nullable=False)
|
||||
branch_id = mapped_column(ForeignKey("companies.id"))
|
||||
branch_uu_id = mapped_column(String, comment="Branch UU ID")
|
||||
|
||||
# company: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="company_account_books", foreign_keys=[company_id]
|
||||
# )
|
||||
# branch: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="branch_account_books", foreign_keys=[branch_id]
|
||||
# )
|
||||
# account_master: Mapped[List["AccountMaster"]] = relationship(
|
||||
# "AccountMaster",
|
||||
# back_populates="account_header",
|
||||
# foreign_keys="AccountMaster.account_header_id",
|
||||
# )
|
||||
# account_detail: Mapped[List["AccountDetail"]] = relationship(
|
||||
# "AccountDetail",
|
||||
# back_populates="account_header",
|
||||
# foreign_keys="AccountDetail.account_header_id",
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"account_companies_book_ndx_00", company_id, CrudCollection.expiry_starts
|
||||
),
|
||||
{"comment": "Account Book Information"},
|
||||
)
|
||||
|
||||
|
||||
class AccountCodes(CrudCollection):
|
||||
|
||||
__tablename__ = "account_codes"
|
||||
__exclude__fields__ = []
|
||||
|
||||
account_code = mapped_column(String(48), nullable=False, comment="Account Code")
|
||||
comment_line = mapped_column(String(128), nullable=False, comment="Comment Line")
|
||||
|
||||
is_receive_or_debit = mapped_column(Boolean)
|
||||
product_id = mapped_column(Integer, server_default="0")
|
||||
nvi_id = mapped_column(String(48), server_default="")
|
||||
status_id = mapped_column(SmallInteger, server_default="0")
|
||||
account_code_seperator = mapped_column(String(1), server_default=".")
|
||||
|
||||
system_id = mapped_column(SmallInteger, server_default="0")
|
||||
locked = mapped_column(SmallInteger, server_default="0")
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"))
|
||||
company_uu_id = mapped_column(String, nullable=False, comment="Company UU ID")
|
||||
customer_id = mapped_column(ForeignKey("companies.id"))
|
||||
customer_uu_id = mapped_column(String, nullable=False, comment="Customer UU ID")
|
||||
person_id = mapped_column(ForeignKey("people.id"))
|
||||
person_uu_id = mapped_column(String, nullable=False, comment="Person UU ID")
|
||||
|
||||
# company: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="account_codes", foreign_keys=[company_id]
|
||||
# )
|
||||
# customer: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="account_codes", foreign_keys=[customer_id]
|
||||
# )
|
||||
# person: Mapped["People"] = relationship(
|
||||
# "People", back_populates="account_codes", foreign_keys=[person_id]
|
||||
# )
|
||||
# account_detail: Mapped[List["AccountDetail"]] = relationship(
|
||||
# "AccountDetail",
|
||||
# back_populates="account_code",
|
||||
# foreign_keys="AccountDetail.account_code_id",
|
||||
# )
|
||||
#
|
||||
# account_code_parser: Mapped["AccountCodeParser"] = relationship(
|
||||
# "AccountCodeParser",
|
||||
# back_populates="account_codes",
|
||||
# foreign_keys="AccountCodeParser.account_code_id",
|
||||
# )
|
||||
|
||||
|
||||
class AccountCodeParser(CrudCollection):
|
||||
|
||||
__tablename__ = "account_code_parser"
|
||||
__exclude__fields__ = []
|
||||
|
||||
account_code_1 = mapped_column(String, nullable=False, comment="Order")
|
||||
account_code_2 = mapped_column(String, nullable=False, comment="Order")
|
||||
account_code_3 = mapped_column(String, nullable=False, comment="Order")
|
||||
account_code_4 = mapped_column(String, server_default="")
|
||||
account_code_5 = mapped_column(String, server_default="")
|
||||
account_code_6 = mapped_column(String, server_default="")
|
||||
|
||||
account_code_id = mapped_column(ForeignKey("account_codes.id"), nullable=False)
|
||||
account_code_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Account Code UU ID"
|
||||
)
|
||||
|
||||
# account_codes: Mapped["AccountCodes"] = relationship(
|
||||
# "AccountCodes",
|
||||
# back_populates="account_code_parser",
|
||||
# foreign_keys=[account_code_id],
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_account_code_parser_ndx_00", account_code_id),
|
||||
{"comment": "Account Code Parser Information"},
|
||||
)
|
||||
|
||||
@property
|
||||
def get_account_code(self):
|
||||
return f"{self.account_codes.account_code_seperator}".join(
|
||||
[
|
||||
getattr(self, f"account_code_{i}")
|
||||
for i in range(1, 7)
|
||||
if getattr(self, f"account_code_{i}")
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class AccountMaster(CrudCollection):
|
||||
"""
|
||||
AccountCodes class based on declarative_base and CrudCollection via session
|
||||
"""
|
||||
|
||||
__tablename__ = "account_master"
|
||||
__exclude__fields__ = []
|
||||
|
||||
doc_date = mapped_column(TIMESTAMP, nullable=False, comment="Document Date")
|
||||
plug_type = mapped_column(String, nullable=False, comment="Plug Type")
|
||||
plug_number = mapped_column(Integer, nullable=False, comment="Plug Number")
|
||||
|
||||
special_code = mapped_column(String(12), server_default="")
|
||||
authorization_code = mapped_column(String(12), server_default="")
|
||||
|
||||
doc_code = mapped_column(String(12), server_default="")
|
||||
doc_type = mapped_column(SmallInteger, server_default="0")
|
||||
|
||||
comment_line1 = mapped_column(String, server_default="")
|
||||
comment_line2 = mapped_column(String, server_default="")
|
||||
comment_line3 = mapped_column(String, server_default="")
|
||||
comment_line4 = mapped_column(String, server_default="")
|
||||
comment_line5 = mapped_column(String, server_default="")
|
||||
comment_line6 = mapped_column(String, server_default="")
|
||||
project_code = mapped_column(String(12), server_default="")
|
||||
module_no = mapped_column(String, server_default="")
|
||||
journal_no = mapped_column(Integer, server_default="0")
|
||||
|
||||
status_id = mapped_column(SmallInteger, server_default="0")
|
||||
canceled = mapped_column(Boolean, server_default="0")
|
||||
print_count = mapped_column(SmallInteger, server_default="0")
|
||||
total_active = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_passive = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_active_1 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_passive_1 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_active_2 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_passive_2 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_active_3 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_passive_3 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_active_4 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
total_passive_4 = mapped_column(Numeric(20, 6), server_default="0")
|
||||
cross_ref = mapped_column(Integer, server_default="0")
|
||||
data_center_id = mapped_column(String, server_default="")
|
||||
data_center_rec_num = mapped_column(Integer, server_default="0")
|
||||
|
||||
account_header_id = mapped_column(ForeignKey("account_books.id"), nullable=False)
|
||||
account_header_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Account Header UU ID"
|
||||
)
|
||||
project_item_id = mapped_column(ForeignKey("build_decision_book_projects.id"))
|
||||
project_item_uu_id = mapped_column(String, comment="Project Item UU ID")
|
||||
department_id = mapped_column(ForeignKey("departments.id"))
|
||||
department_uu_id = mapped_column(String, comment="Department UU ID")
|
||||
|
||||
# account_header: Mapped["AccountBooks"] = relationship(
|
||||
# "AccountBooks",
|
||||
# back_populates="account_master",
|
||||
# foreign_keys=[account_header_id],
|
||||
# )
|
||||
# project_item: Mapped["BuildDecisionBookProjects"] = relationship(
|
||||
# "BuildDecisionBookProjects",
|
||||
# back_populates="account_master",
|
||||
# foreign_keys=[project_item_id],
|
||||
# )
|
||||
# account_detail: Mapped[List["AccountDetail"]] = relationship(
|
||||
# "AccountDetail",
|
||||
# back_populates="account_master",
|
||||
# foreign_keys="AccountDetail.account_master_id",
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_account_master_ndx_00", doc_date, account_header_id),
|
||||
{"comment": "Account Master Information"},
|
||||
)
|
||||
|
||||
|
||||
class AccountDetail(CrudCollection):
|
||||
"""
|
||||
AccountCodes class based on declarative_base and CrudCollection via session
|
||||
"""
|
||||
|
||||
__tablename__ = "account_detail"
|
||||
__exclude__fields__ = []
|
||||
__enum_list__ = [("plug_type", "AccountingReceiptTypes", "M")]
|
||||
|
||||
doc_date = mapped_column(TIMESTAMP, nullable=False, comment="Document Date")
|
||||
line_no = mapped_column(SmallInteger, nullable=False, comment="Line Number")
|
||||
receive_debit = mapped_column(String(1), nullable=False, comment="Receive Debit")
|
||||
debit = mapped_column(Numeric(20, 6), nullable=False, comment="Debit")
|
||||
|
||||
department = mapped_column(String(24), server_default="")
|
||||
special_code = mapped_column(String(12), server_default="")
|
||||
account_ref = mapped_column(Integer, server_default="0")
|
||||
account_fiche_ref = mapped_column(Integer, server_default="0")
|
||||
center_ref = mapped_column(Integer, server_default="0")
|
||||
general_code = mapped_column(String(32), server_default="")
|
||||
credit = mapped_column(Numeric(20, 6), server_default="0")
|
||||
currency_type = mapped_column(String(4), server_default="TL")
|
||||
exchange_rate = mapped_column(Numeric(20, 6), server_default="0")
|
||||
debit_cur = mapped_column(Numeric(20, 6), server_default="0")
|
||||
credit_cur = mapped_column(Numeric(20, 6), server_default="0")
|
||||
discount_cur = mapped_column(Numeric(20, 6), server_default="0")
|
||||
amount = mapped_column(Numeric(20, 6), server_default="0")
|
||||
cross_account_code = mapped_column(String(32), server_default="")
|
||||
inf_index = mapped_column(Numeric(20, 6), server_default="0")
|
||||
not_inflated = mapped_column(SmallInteger, server_default="0")
|
||||
not_calculated = mapped_column(SmallInteger, server_default="0")
|
||||
comment_line1 = mapped_column(String(64), server_default="")
|
||||
comment_line2 = mapped_column(String(64), server_default="")
|
||||
comment_line3 = mapped_column(String(64), server_default="")
|
||||
comment_line4 = mapped_column(String(64), server_default="")
|
||||
comment_line5 = mapped_column(String(64), server_default="")
|
||||
comment_line6 = mapped_column(String(64), server_default="")
|
||||
owner_acc_ref = mapped_column(Integer, server_default="0")
|
||||
from_where = mapped_column(Integer, server_default="0")
|
||||
orj_eid = mapped_column(Integer, server_default="0")
|
||||
canceled = mapped_column(SmallInteger, server_default="0")
|
||||
cross_ref = mapped_column(Integer, server_default="0")
|
||||
data_center_id = mapped_column(String, server_default="")
|
||||
data_center_rec_num = mapped_column(Integer, server_default="0")
|
||||
status_id = mapped_column(SmallInteger, server_default="0")
|
||||
|
||||
plug_type_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
|
||||
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_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Account Header UU ID"
|
||||
)
|
||||
account_code_id = mapped_column(ForeignKey("account_codes.id"), nullable=False)
|
||||
account_code_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Account Code UU ID"
|
||||
)
|
||||
account_master_id = mapped_column(ForeignKey("account_master.id"), nullable=False)
|
||||
account_master_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Account Master UU ID"
|
||||
)
|
||||
project_id = mapped_column(ForeignKey("build_decision_book_projects.id"))
|
||||
project_uu_id = mapped_column(String, comment="Project UU ID")
|
||||
|
||||
# account_header: Mapped["AccountBooks"] = relationship(
|
||||
# "AccountBooks",
|
||||
# back_populates="account_detail",
|
||||
# foreign_keys=[account_header_id],
|
||||
# )
|
||||
# account_code: Mapped["AccountCodes"] = relationship(
|
||||
# "AccountCodes",
|
||||
# back_populates="account_detail",
|
||||
# foreign_keys=[account_code_id],
|
||||
# )
|
||||
# account_master: Mapped["AccountMaster"] = relationship(
|
||||
# "AccountMaster",
|
||||
# back_populates="account_detail",
|
||||
# foreign_keys=[account_master_id],
|
||||
# )
|
||||
# project: Mapped["BuildDecisionBookProjects"] = relationship(
|
||||
# "BuildDecisionBookProjects",
|
||||
# back_populates="account_detail",
|
||||
# foreign_keys=[project_id],
|
||||
# )
|
||||
# decision_book_payment_detail: Mapped["BuildDecisionBookPaymentsDetail"] = (
|
||||
# relationship(
|
||||
# "BuildDecisionBookPaymentsDetail",
|
||||
# back_populates="accounting",
|
||||
# foreign_keys="BuildDecisionBookPaymentsDetail.accounting_id",
|
||||
# )
|
||||
# )
|
||||
# decision_book_project_payment_detail: Mapped[
|
||||
# "BuildDecisionBookProjectPaymentsDetail"
|
||||
# ] = relationship(
|
||||
# "BuildDecisionBookProjectPaymentsDetail",
|
||||
# back_populates="accounting",
|
||||
# foreign_keys="BuildDecisionBookProjectPaymentsDetail.accounting_id",
|
||||
# )
|
||||
# decision_book_budget: Mapped["BuildDecisionBookBudget"] = relationship(
|
||||
# "BuildDecisionBookBudget",
|
||||
# back_populates="accounting",
|
||||
# foreign_keys="BuildDecisionBookBudget.accounting_id",
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_account_detail_ndx_00",
|
||||
account_master_id,
|
||||
doc_date,
|
||||
line_no,
|
||||
account_header_id,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Account Detail Information"},
|
||||
)
|
||||
|
||||
|
||||
class AccountRecords(CrudCollection):
|
||||
|
||||
__tablename__ = "account_records"
|
||||
__exclude__fields__ = []
|
||||
__enum_list__ = [
|
||||
("receive_debit", "DebitTypes", "D"),
|
||||
("budget_type", "BudgetType", "B"),
|
||||
]
|
||||
"""
|
||||
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
|
||||
customer_id = sorumlu kullanıcı bilgisi, company_id = sorumlu firma
|
||||
|
||||
"""
|
||||
|
||||
iban = mapped_column(String(64), nullable=False, comment="IBAN Number of Bank")
|
||||
bank_date = mapped_column(
|
||||
TIMESTAMP, nullable=False, comment="Bank Transaction Date"
|
||||
)
|
||||
|
||||
currency_value = mapped_column(
|
||||
Numeric(20, 6), nullable=False, comment="Currency Value"
|
||||
)
|
||||
bank_balance = mapped_column(Numeric(20, 6), nullable=False, comment="Bank Balance")
|
||||
currency = mapped_column(String(5), nullable=False, comment="Unit of Currency")
|
||||
additional_balance = mapped_column(
|
||||
Numeric(20, 6), nullable=False, comment="Additional Balance"
|
||||
)
|
||||
channel_branch = mapped_column(String(120), nullable=False, comment="Branch Bank")
|
||||
process_name = mapped_column(
|
||||
String, nullable=False, comment="Bank Process Type Name"
|
||||
)
|
||||
process_type = mapped_column(
|
||||
String, nullable=False, comment="Bank Process Type"
|
||||
)
|
||||
process_comment = mapped_column(
|
||||
String, nullable=False, comment="Transaction Record Comment"
|
||||
)
|
||||
bank_reference_code = mapped_column(
|
||||
String, nullable=False, comment="Bank Reference Code"
|
||||
)
|
||||
|
||||
add_comment_note = mapped_column(String, server_default="")
|
||||
is_receipt_mail_send = mapped_column(Boolean, server_default="0")
|
||||
found_from = mapped_column(String, server_default="")
|
||||
similarity = mapped_column(Numeric(20, 6), server_default="0")
|
||||
remainder_balance = mapped_column(Numeric(20, 6), server_default="0")
|
||||
|
||||
bank_date_y = mapped_column(Integer)
|
||||
bank_date_m = mapped_column(SmallInteger)
|
||||
bank_date_w = mapped_column(SmallInteger)
|
||||
bank_date_d = mapped_column(SmallInteger)
|
||||
|
||||
approving_accounting_record = mapped_column(Boolean, server_default="0")
|
||||
accounting_receipt_date = mapped_column(
|
||||
TIMESTAMP, server_default="1900-01-01 00:00:00"
|
||||
)
|
||||
accounting_receipt_number = mapped_column(Integer, server_default="0")
|
||||
status_id = mapped_column(SmallInteger, server_default="0")
|
||||
|
||||
approved_record = mapped_column(Boolean, server_default="0")
|
||||
import_file_name = mapped_column(String, nullable=True, comment="XLS Key")
|
||||
|
||||
receive_debit = mapped_column(ForeignKey("api_enum_dropdown.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_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Budget Type UU ID"
|
||||
)
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"))
|
||||
company_uu_id = mapped_column(String, nullable=True, comment="Company UU ID")
|
||||
send_company_id = mapped_column(ForeignKey("companies.id"))
|
||||
send_company_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Send Company UU ID"
|
||||
)
|
||||
|
||||
customer_id = mapped_column(ForeignKey("people.id"))
|
||||
customer_uu_id = mapped_column(String, nullable=True, comment="Customer UU ID")
|
||||
send_person_id = mapped_column(ForeignKey("people.id"))
|
||||
send_person_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Send Person UU ID"
|
||||
)
|
||||
approving_accounting_person = mapped_column(ForeignKey("people.id"))
|
||||
approving_accounting_person_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Approving Accounting Person UU ID"
|
||||
)
|
||||
# build_id = mapped_column(ForeignKey("build.id"), nullable=True)
|
||||
build_parts_id = mapped_column(ForeignKey("build_parts.id"))
|
||||
build_parts_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Build Parts UU ID"
|
||||
)
|
||||
build_decision_book_id = mapped_column(ForeignKey("build_decision_book.id"))
|
||||
build_decision_book_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Build Decision Book UU ID"
|
||||
)
|
||||
|
||||
# companies: Mapped[List["Company"]] = relationship(
|
||||
# "Company", back_populates="budget_records", foreign_keys=[company_id]
|
||||
# )
|
||||
# send_companies: Mapped[List["Company"]] = relationship(
|
||||
# "Company", back_populates="send_budget_records", foreign_keys=[send_company_id]
|
||||
# )
|
||||
#
|
||||
# parts: Mapped[List["BuildParts"]] = relationship(
|
||||
# "BuildParts", back_populates="budget_records", foreign_keys=[build_parts_id]
|
||||
# )
|
||||
# people: Mapped["People"] = relationship(
|
||||
# "People", back_populates="budget_records", foreign_keys=[customer_id]
|
||||
# )
|
||||
# send_person: Mapped["People"] = relationship(
|
||||
# "People", back_populates="budget_records", foreign_keys=[send_person_id]
|
||||
# )
|
||||
# decision_books: Mapped[List["BuildDecisionBook"]] = relationship(
|
||||
# "BuildDecisionBook",
|
||||
# back_populates="budget_records",
|
||||
# foreign_keys=[build_decision_book_id],
|
||||
# )
|
||||
#
|
||||
# decision_book_payment_detail: Mapped["BuildDecisionBookPaymentsDetail"] = (
|
||||
# relationship(
|
||||
# "BuildDecisionBookPaymentsDetail",
|
||||
# back_populates="budget_records",
|
||||
# foreign_keys="BuildDecisionBookPaymentsDetail.budget_records_id",
|
||||
# )
|
||||
# )
|
||||
#
|
||||
# decision_book_project_payments_detail: Mapped[
|
||||
# List["BuildDecisionBookProjectPaymentsDetail"]
|
||||
# ] = relationship(
|
||||
# "BuildDecisionBookProjectPaymentsDetail",
|
||||
# back_populates="budget_records",
|
||||
# foreign_keys="BuildDecisionBookProjectPaymentsDetail.budget_records_id",
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_budget_records_ndx_00", is_receipt_mail_send, bank_date),
|
||||
Index(
|
||||
"_budget_records_ndx_01",
|
||||
iban,
|
||||
bank_date,
|
||||
bank_reference_code,
|
||||
bank_balance,
|
||||
unique=True,
|
||||
),
|
||||
Index("_budget_records_ndx_02", status_id, bank_date),
|
||||
{
|
||||
"comment": "Bank Records that are related to building and financial transactions"
|
||||
},
|
||||
)
|
||||
#
|
||||
# def payment_budget_record_close(self):
|
||||
# from database_sql_models import (
|
||||
# DecisionBookProjectPaymentsMaster,
|
||||
# ApiEnumDropdown,
|
||||
# BuildDecisionBook,
|
||||
# BuildDecisionBookPaymentsMaster,
|
||||
# )
|
||||
#
|
||||
# budget_record = self
|
||||
# if self.receive_debit == ApiEnumDropdown.uuid_of_enum(
|
||||
# enum_class="DebitTypes", key="R"
|
||||
# ):
|
||||
# print(
|
||||
# "This record is not debit. Debit:",
|
||||
# self.receive_debit,
|
||||
# "DebitTypes.R.name",
|
||||
# # str(DebitTypes.R.name),
|
||||
# )
|
||||
# return
|
||||
# if abs(budget_record.currency_value + budget_record.remainder_balance) > 0:
|
||||
# payment_dict = {
|
||||
# "budget_records_id": self.id,
|
||||
# "build_decision_book_id": budget_record.build_decision_book_id,
|
||||
# "build_parts_id": budget_record.build_parts_id,
|
||||
# "start_date": budget_record.bank_date,
|
||||
# "paid_value": budget_record.currency_value
|
||||
# - budget_record.remainder_balance,
|
||||
# "is_all": False,
|
||||
# }
|
||||
# (paid_value, start_paid_value, balance) = (
|
||||
# float(budget_record.currency_value - budget_record.remainder_balance),
|
||||
# float(budget_record.currency_value - budget_record.remainder_balance),
|
||||
# float(budget_record.remainder_balance),
|
||||
# )
|
||||
# print(
|
||||
# "self.id",
|
||||
# self.id,
|
||||
# "paid_value",
|
||||
# paid_value,
|
||||
# "start_paid_value",
|
||||
# start_paid_value,
|
||||
# "balance",
|
||||
# balance,
|
||||
# self.receive_debit,
|
||||
# )
|
||||
#
|
||||
# if not BuildDecisionBook.find_one(
|
||||
# id=payment_dict["build_decision_book_id"]
|
||||
# ):
|
||||
# return paid_value
|
||||
#
|
||||
# if budget_record.replication_id == 55:
|
||||
# if paid_value > 0:
|
||||
# payment_dict["dues_type"] = ApiEnumDropdown.uuid_of_enum(
|
||||
# enum_class="BuildDuesTypes", key="L"
|
||||
# )
|
||||
# paid_value = (
|
||||
# DecisionBookProjectPaymentsMaster.pay_law_and_ren_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# )
|
||||
# print("dues_type", payment_dict["dues_type"], paid_value)
|
||||
# if paid_value > 0:
|
||||
# payment_dict.pop("dues_type", None)
|
||||
# paid_value = BuildDecisionBookPaymentsMaster.pay_dues_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# print("dues_type", None, paid_value)
|
||||
# if paid_value > 0:
|
||||
# payment_dict["dues_type"] = ApiEnumDropdown.uuid_of_enum(
|
||||
# enum_class="BuildDuesTypes", key="R"
|
||||
# )
|
||||
# paid_value = (
|
||||
# DecisionBookProjectPaymentsMaster.pay_law_and_ren_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# )
|
||||
# print("dues_type", payment_dict["dues_type"], paid_value)
|
||||
# payment_dict["is_all"] = True
|
||||
# if paid_value > 0:
|
||||
# payment_dict["dues_type"] = ApiEnumDropdown.uuid_of_enum(
|
||||
# enum_class="BuildDuesTypes", key="L"
|
||||
# )
|
||||
# paid_value = (
|
||||
# DecisionBookProjectPaymentsMaster.pay_law_and_ren_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# )
|
||||
# print("is all dues_type", payment_dict["dues_type"], paid_value)
|
||||
# if paid_value > 0:
|
||||
# payment_dict.pop("dues_type", None)
|
||||
# paid_value = BuildDecisionBookPaymentsMaster.pay_dues_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# print("is all dues_type", None, paid_value)
|
||||
# if paid_value > 0:
|
||||
# payment_dict["dues_type"] = ApiEnumDropdown.uuid_of_enum(
|
||||
# enum_class="BuildDuesTypes", key="R"
|
||||
# )
|
||||
# paid_value = (
|
||||
# DecisionBookProjectPaymentsMaster.pay_law_and_ren_of_build_part(
|
||||
# **payment_dict
|
||||
# )
|
||||
# )
|
||||
# print("is all dues_type", payment_dict["dues_type"], paid_value)
|
||||
101
databases/sql_models/account/iban.py
Normal file
101
databases/sql_models/account/iban.py
Normal file
@@ -0,0 +1,101 @@
|
||||
from sqlalchemy.orm import mapped_column
|
||||
from sqlalchemy import String, ForeignKey, Index, TIMESTAMP, SmallInteger
|
||||
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
|
||||
class BuildIbans(CrudCollection):
|
||||
"""
|
||||
BuildParts class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "build_ibans"
|
||||
__exclude__fields__ = []
|
||||
|
||||
iban = mapped_column(
|
||||
String(40), server_default="", nullable=False, comment="IBAN number"
|
||||
)
|
||||
start_date = mapped_column(
|
||||
TIMESTAMP, nullable=False, comment="Bank Transaction Start Date"
|
||||
)
|
||||
|
||||
stop_date = mapped_column(TIMESTAMP, server_default="2900-01-01 00:00:00")
|
||||
bank_code = mapped_column(String(24), server_default="TR0000000000000")
|
||||
xcomment = mapped_column(String(64), server_default="????")
|
||||
|
||||
build_id = mapped_column(
|
||||
ForeignKey("build.id"), nullable=False, comment="Building ID"
|
||||
)
|
||||
build_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Building UUID", index=True
|
||||
)
|
||||
# building: Mapped["Build"] = relationship(
|
||||
# "Build", back_populates="build_ibans", foreign_keys=[build_id]
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_build_ibans_ndx_01", iban, start_date, unique=True),
|
||||
{"comment": "IBANs related to money transactions due to building objects"},
|
||||
)
|
||||
|
||||
# @property
|
||||
# def enums(self):
|
||||
# return_dict = {}
|
||||
# for key, enum in self.__enums_list__.items():
|
||||
# for enum_item in EnumDropdown.filter_by(enum_class=enum):
|
||||
# return_dict[key] = {
|
||||
# enum_item.get_dict(include=["key", "value", "description"])
|
||||
# }
|
||||
# return return_dict
|
||||
|
||||
|
||||
class BuildIbanDescription(CrudCollection):
|
||||
"""
|
||||
SearchComments class based on declarative_base and CrudCollection via session
|
||||
"""
|
||||
|
||||
__tablename__ = "build_iban_description"
|
||||
__exclude__fields__ = []
|
||||
|
||||
iban = mapped_column(String, nullable=False, comment="IBAN Number")
|
||||
group_id = mapped_column(SmallInteger, nullable=False, comment="Group ID")
|
||||
search_word = mapped_column(
|
||||
String, nullable=False, comment="Search Word", index=True
|
||||
)
|
||||
|
||||
decision_book_project_id = mapped_column(ForeignKey("build_decision_book_projects.id"))
|
||||
decision_book_project_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Decision Book Project UUID"
|
||||
)
|
||||
customer_id = mapped_column(ForeignKey("people.id"))
|
||||
customer_uu_id = mapped_column(String, nullable=False, comment="Customer UUID")
|
||||
company_id = mapped_column(ForeignKey("companies.id"))
|
||||
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID")
|
||||
build_parts_id = mapped_column(ForeignKey("build_parts.id"))
|
||||
build_parts_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Build Parts UUID"
|
||||
)
|
||||
|
||||
# decision_book_project: Mapped["BuildDecisionBookProjects"] = relationship(
|
||||
# "BuildDecisionBookProjects",
|
||||
# back_populates="search_iban_description",
|
||||
# foreign_keys=[decision_book_project_id],
|
||||
# )
|
||||
# customer: Mapped["People"] = relationship(
|
||||
# "People", back_populates="search_iban_description", foreign_keys=[customer_id]
|
||||
# )
|
||||
# company: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="search_iban_description", foreign_keys=[company_id]
|
||||
# )
|
||||
# parts: Mapped["BuildParts"] = relationship(
|
||||
# "BuildParts",
|
||||
# back_populates="search_iban_description",
|
||||
# foreign_keys=[build_parts_id],
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_search_iban_description_ndx_00", iban, search_word, group_id, unique=True
|
||||
),
|
||||
{"comment": "Search Iban Description Information"},
|
||||
)
|
||||
124
databases/sql_models/api/encrypter.py
Normal file
124
databases/sql_models/api/encrypter.py
Normal file
@@ -0,0 +1,124 @@
|
||||
import random
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import mapped_column, Mapped
|
||||
|
||||
from cryptography.fernet import Fernet, MultiFernet
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
|
||||
class CrypterEngine(CrudCollection):
|
||||
|
||||
__tablename__ = "crypter_engine"
|
||||
__table_args__ = ()
|
||||
encrypt_list = []
|
||||
decrypt_list = []
|
||||
keys_error = "Unable to retrieve encrypt keys"
|
||||
alchemy_error = "Alchemy object is empty"
|
||||
|
||||
key_first: Mapped[str] = mapped_column(String, nullable=False)
|
||||
key_second: Mapped[str] = mapped_column(String, nullable=False)
|
||||
|
||||
@classmethod
|
||||
def get_valid_keys(cls, row=None):
|
||||
cls.encrypt_list, cls.decrypt_list = [], []
|
||||
if not cls.filter_active(
|
||||
cls.created_at > datetime.now() - timedelta(days=29)
|
||||
).get(1):
|
||||
cls.create_encrypt_keys(count=100)
|
||||
if decrypt_identifier := getattr(row, "cryp_uu_id", None):
|
||||
if decrypt_row := cls.find_one(uu_id=str(decrypt_identifier)):
|
||||
return (
|
||||
decrypt_row.key_first.decode(),
|
||||
decrypt_row.key_second.decode(),
|
||||
decrypt_row.uu_id,
|
||||
)
|
||||
if encrypt_rows := cls.filter_active(
|
||||
cls.created_at > datetime.now() - timedelta(days=29)
|
||||
).data:
|
||||
encrypt_row = random.choice(encrypt_rows)
|
||||
return (
|
||||
encrypt_row.key_first.encode(),
|
||||
encrypt_row.key_second.encode(),
|
||||
encrypt_rows.uu_id,
|
||||
)
|
||||
return None, None, None
|
||||
|
||||
@classmethod
|
||||
def create_encrypt_keys(cls, count: int):
|
||||
for _ in range(count):
|
||||
key_first = Fernet.generate_key()
|
||||
key_second = Fernet.generate_key()
|
||||
cls.find_or_create(
|
||||
key_first=key_first.decode(), key_second=key_second.decode()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def raise_exception(cls, message=None):
|
||||
raise Exception(message if message else cls.keys_error)
|
||||
|
||||
@classmethod
|
||||
def encrypt_given_alchemy_list(cls, alchemy_object_list: list):
|
||||
for alchemy_object in alchemy_object_list:
|
||||
key_first, key_second, cryp_uu_id = cls.get_valid_keys()
|
||||
fernet_keys = MultiFernet([Fernet(key_first), Fernet(key_second)])
|
||||
if not key_first or not key_second:
|
||||
cls.raise_exception()
|
||||
alchemy_dict = alchemy_object.get_dict() if alchemy_object else None
|
||||
if not alchemy_dict:
|
||||
cls.raise_exception(cls.alchemy_error)
|
||||
for key, plain_row in alchemy_dict.items():
|
||||
if key in alchemy_object.__encrypt_list__:
|
||||
alchemy_dict[key] = fernet_keys.encrypt(plain_row).decode()
|
||||
alchemy_dict["cryp_uu_id"] = cryp_uu_id
|
||||
cls.encrypt_list.append(alchemy_object.update(**alchemy_dict))
|
||||
return cls.encrypt_list
|
||||
|
||||
@classmethod
|
||||
def encrypt_given_alchemy_object(cls, alchemy_object_object):
|
||||
key_first, key_second, cryp_uu_id = cls.get_valid_keys()
|
||||
fernet_keys = MultiFernet([Fernet(key_first), Fernet(key_second)])
|
||||
if not key_first or not key_second:
|
||||
cls.raise_exception()
|
||||
alchemy_dict = (
|
||||
alchemy_object_object.get_dict() if alchemy_object_object else None
|
||||
)
|
||||
if not alchemy_dict:
|
||||
cls.raise_exception(cls.alchemy_error)
|
||||
for key, plain_row in alchemy_dict.items():
|
||||
if key in alchemy_object_object.__encrypt_list__:
|
||||
alchemy_dict[key] = fernet_keys.encrypt(plain_row).decode()
|
||||
alchemy_dict["cryp_uu_id"] = cryp_uu_id
|
||||
return alchemy_object_object.update(**alchemy_dict)
|
||||
|
||||
@classmethod
|
||||
def decrypt_given_alchemy(cls, alchemy_object_list: list):
|
||||
for alchemy_object in alchemy_object_list:
|
||||
key_first, key_second, cryp_uu_id = cls.get_valid_keys(row=alchemy_object)
|
||||
fernet_keys = MultiFernet([Fernet(key_first), Fernet(key_second)])
|
||||
if not key_first or not key_second:
|
||||
cls.raise_exception()
|
||||
alchemy_dict = alchemy_object.get_dict() if alchemy_object else None
|
||||
if not alchemy_dict:
|
||||
cls.raise_exception(cls.alchemy_error)
|
||||
for key, plain_row in alchemy_dict.items():
|
||||
if key in alchemy_object.__encrypt_list__:
|
||||
alchemy_dict[key] = fernet_keys.decrypt(plain_row).decode()
|
||||
cls.decrypt_list.append(alchemy_dict)
|
||||
return cls.decrypt_list
|
||||
|
||||
@classmethod
|
||||
def decrypt_given_alchemy_object(cls, alchemy_object):
|
||||
key_first, key_second, cryp_uu_id = cls.get_valid_keys(row=alchemy_object)
|
||||
fernet_keys = MultiFernet([Fernet(key_first), Fernet(key_second)])
|
||||
if not key_first or not key_second:
|
||||
cls.raise_exception()
|
||||
alchemy_dict = alchemy_object.get_dict() if alchemy_object else None
|
||||
if not alchemy_dict:
|
||||
cls.raise_exception(cls.alchemy_error)
|
||||
for key, plain_row in alchemy_dict.items():
|
||||
if key in alchemy_object.__encrypt_list__:
|
||||
alchemy_dict[key] = fernet_keys.decrypt(plain_row).decode()
|
||||
return alchemy_dict
|
||||
806
databases/sql_models/building/build.py
Normal file
806
databases/sql_models/building/build.py
Normal file
@@ -0,0 +1,806 @@
|
||||
import typing
|
||||
from operator import or_
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
from sqlalchemy.orm import mapped_column, relationship, Mapped
|
||||
from sqlalchemy import (
|
||||
String,
|
||||
Integer,
|
||||
ForeignKey,
|
||||
Index,
|
||||
SmallInteger,
|
||||
Boolean,
|
||||
TIMESTAMP,
|
||||
Text,
|
||||
Numeric,
|
||||
)
|
||||
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
from databases import ApiEnumDropdown
|
||||
|
||||
from application.shared_classes import SelectActionWithEmployee, Explanation
|
||||
from validations import (
|
||||
InsertBuildParts,
|
||||
InsertBuild,
|
||||
UpdateBuild,
|
||||
)
|
||||
from valids.auth.token_validations import EmployeeTokenObject, OccupantTokenObject
|
||||
|
||||
|
||||
class AbstractBuild:
|
||||
"""
|
||||
Abstract and explanation of Build class for end-user guide
|
||||
"""
|
||||
|
||||
gov_address_code = Explanation(
|
||||
explanation="Devletin resmi adres kodudur.",
|
||||
usage="Devletin resmi adres kodu istendiğinde kullanılır.",
|
||||
alias="Devlet Adres Kodu",
|
||||
example=["1234567890"],
|
||||
)
|
||||
build_name = Explanation(
|
||||
explanation="Bina adıdır.",
|
||||
usage="Bina adı istendiğinde kullanılır.",
|
||||
alias="Bina Adı",
|
||||
example=["X Binası", "Y Binası"],
|
||||
)
|
||||
build_no = Explanation(
|
||||
explanation="Bina numarasıdır.",
|
||||
usage="Bina numarası istendiğinde kullanılır.",
|
||||
alias="Bina No",
|
||||
example=["1234567890"],
|
||||
)
|
||||
build_types = Explanation(
|
||||
explanation="Bina türüdür.",
|
||||
usage="Bina türü istendiğinde kullanılır.",
|
||||
alias="Bina Türü",
|
||||
example=["Ofis", "Konut", "Depo"],
|
||||
)
|
||||
max_floor = Explanation(
|
||||
explanation="Bina kat sayısıdır.",
|
||||
usage="Bina kat sayısı istendiğinde kullanılır.",
|
||||
alias="Kat Sayısı",
|
||||
example=["1", "2", "3"],
|
||||
)
|
||||
underground_floor = Explanation(
|
||||
explanation="Bina bodrum kat sayısıdır.",
|
||||
usage="Bina bodrum kat sayısı istendiğinde kullanılır.",
|
||||
alias="Bodrum Kat Sayısı",
|
||||
example=["1", "2", "3"],
|
||||
)
|
||||
build_date = Explanation(
|
||||
explanation="Bina yapım tarihidir.",
|
||||
usage="Bina yapım tarihi istendiğinde kullanılır.",
|
||||
alias="Yapım Tarihi",
|
||||
example=["2021-01-01"],
|
||||
)
|
||||
tax_no = Explanation(
|
||||
explanation="Bina vergi numarasıdır.",
|
||||
usage="Bina vergi numarası istendiğinde kullanılır.",
|
||||
alias="Vergi No",
|
||||
example=["1234567890"],
|
||||
)
|
||||
lift_count = Explanation(
|
||||
explanation="Bina asansör sayısıdır.",
|
||||
usage="Bina asansör sayısı istendiğinde kullanılır.",
|
||||
alias="Asansör Sayısı",
|
||||
example=["1", "2", "3"],
|
||||
)
|
||||
heating_system = Explanation(
|
||||
explanation="Bina ısıtma sistemi var mı?",
|
||||
usage="Bina ısıtma sistemi var mı istendiğinde kullanılır.",
|
||||
alias="Isıtma Sistemi",
|
||||
example=[True, False],
|
||||
)
|
||||
cooling_system = Explanation(
|
||||
explanation="Bina soğutma sistemi var mı?",
|
||||
usage="Bina soğutma sistemi var mı istendiğinde kullanılır.",
|
||||
alias="Soğutma Sistemi",
|
||||
example=[True, False],
|
||||
)
|
||||
hot_water_system = Explanation(
|
||||
explanation="Bina sıcak su sistemi var mı?",
|
||||
usage="Bina sıcak su sistemi var mı istendiğinde kullanılır.",
|
||||
alias="Sıcak Su Sistemi",
|
||||
example=[True, False],
|
||||
)
|
||||
|
||||
|
||||
class BuildTypes(CrudCollection):
|
||||
"""
|
||||
BuildTypes class based on declarative_base and BaseMixin via session
|
||||
|
||||
"""
|
||||
|
||||
__tablename__ = "build_types"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
function_code = mapped_column(
|
||||
String(12), server_default="", nullable=False, comment="Function Code"
|
||||
)
|
||||
type_code = mapped_column(
|
||||
String(12), server_default="", nullable=False, comment="Structure Type Code"
|
||||
)
|
||||
lang = mapped_column(
|
||||
String(4), server_default="TR", nullable=False, comment="Language"
|
||||
)
|
||||
type_name = mapped_column(
|
||||
String(48), server_default="", nullable=False, comment="Type Name"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_build_types_ndx_00", type_code, function_code, lang, unique=True),
|
||||
{"comment": "Function group of building types with their language information"},
|
||||
)
|
||||
|
||||
|
||||
class Part2Employee(CrudCollection):
|
||||
"""
|
||||
Employee2Parts class based on declarative_base and BaseMixin via session
|
||||
In between start and end date, a part can be assigned to only one employee
|
||||
"""
|
||||
|
||||
__tablename__ = "part2employee"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
build_id = mapped_column(Integer, comment="Building ID")
|
||||
part_id = mapped_column(
|
||||
ForeignKey("build_parts.id"), nullable=False, comment="Part ID"
|
||||
)
|
||||
employee_id = mapped_column(
|
||||
ForeignKey("employees.id"), nullable=False, comment="Employee ID"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_part2employee_ndx_00", employee_id, part_id, unique=True),
|
||||
{"comment": "Employee2Parts Information"},
|
||||
)
|
||||
|
||||
|
||||
class RelationshipEmployee2Build(CrudCollection):
|
||||
"""
|
||||
CompanyRelationship class based on declarative_base and CrudCollection via session
|
||||
Company -> Sub Company -> Sub-Sub Company
|
||||
|
||||
"""
|
||||
|
||||
__tablename__ = "relationship_employee2build"
|
||||
__exclude__fields__ = []
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1, 2, 3
|
||||
employee_id = mapped_column(
|
||||
ForeignKey("employees.id"), nullable=False
|
||||
) # employee -> (n)person Evyos LTD
|
||||
member_id = mapped_column(ForeignKey("build.id"), nullable=False) # 2, 3, 4
|
||||
|
||||
relationship_type = mapped_column(
|
||||
String, nullable=True, server_default="Employee"
|
||||
) # Commercial
|
||||
show_only = mapped_column(Boolean, server_default="False")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"relationship_build_employee_ndx_00",
|
||||
company_id,
|
||||
employee_id,
|
||||
member_id,
|
||||
relationship_type,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Build & Employee Relationship Information"},
|
||||
)
|
||||
|
||||
|
||||
class Build(CrudCollection, SelectActionWithEmployee):
|
||||
"""
|
||||
Builds class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "build"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
__access_by__ = []
|
||||
__many__table__ = RelationshipEmployee2Build
|
||||
__explain__ = AbstractBuild()
|
||||
|
||||
gov_address_code = mapped_column(String, server_default="", unique=True)
|
||||
build_name = mapped_column(String, nullable=False, comment="Building Name")
|
||||
build_no = mapped_column(String(8), nullable=False, comment="Building Number")
|
||||
|
||||
max_floor = mapped_column(
|
||||
SmallInteger, server_default="1", nullable=False, comment="Max Floor"
|
||||
)
|
||||
underground_floor = mapped_column(
|
||||
SmallInteger, server_default="0", nullable=False, comment="Underground Floor"
|
||||
)
|
||||
build_date = mapped_column(TIMESTAMP, server_default="1900-01-01")
|
||||
decision_period_date = mapped_column(
|
||||
TIMESTAMP,
|
||||
server_default="1900-01-01",
|
||||
comment="Building annual ordinary meeting period",
|
||||
)
|
||||
tax_no = mapped_column(String(24), server_default="")
|
||||
lift_count = mapped_column(SmallInteger, server_default="0")
|
||||
heating_system = mapped_column(Boolean, server_default="True")
|
||||
cooling_system = mapped_column(Boolean, server_default="False")
|
||||
hot_water_system = mapped_column(Boolean, server_default="False")
|
||||
block_service_man_count = mapped_column(SmallInteger, server_default="0")
|
||||
security_service_man_count = mapped_column(SmallInteger, server_default="0")
|
||||
garage_count = mapped_column(
|
||||
SmallInteger, server_default="0", comment="Garage Count"
|
||||
)
|
||||
management_room_id = mapped_column(
|
||||
Integer, nullable=True, comment="Management Room ID"
|
||||
)
|
||||
|
||||
site_id = mapped_column(ForeignKey("build_sites.id"))
|
||||
site_uu_id = mapped_column(String, comment="Site UUID")
|
||||
address_id = mapped_column(ForeignKey("addresses.id"))
|
||||
address_uu_id = mapped_column(String, comment="Address UUID")
|
||||
build_types_id = mapped_column(
|
||||
ForeignKey("build_types.id"), nullable=False, comment="Building Type"
|
||||
)
|
||||
build_types_uu_id = mapped_column(String, comment="Building Type UUID")
|
||||
|
||||
parts: Mapped[List["BuildParts"]] = relationship(
|
||||
"BuildParts", back_populates="buildings", foreign_keys="BuildParts.build_id"
|
||||
)
|
||||
decision_books: Mapped[List["BuildDecisionBook"]] = relationship(
|
||||
"BuildDecisionBook",
|
||||
back_populates="buildings",
|
||||
foreign_keys="BuildDecisionBook.build_id",
|
||||
)
|
||||
|
||||
#
|
||||
# build_ibans: Mapped["BuildIbans"] = relationship(
|
||||
# "BuildIbans", back_populates="building", foreign_keys="BuildIbans.build_id"
|
||||
# )
|
||||
# areas: Mapped["BuildArea"] = relationship(
|
||||
# "BuildArea", back_populates="buildings", foreign_keys="BuildArea.build_id"
|
||||
# )
|
||||
# response_companies: Mapped["Companies"] = relationship(
|
||||
# "Companies",
|
||||
# back_populates="response_buildings",
|
||||
# foreign_keys=[response_company_id],
|
||||
# )
|
||||
# addresses: Mapped[List["Address"]] = relationship(
|
||||
# "Address", back_populates="buildings", foreign_keys=[address_id]
|
||||
# )
|
||||
# peoples: Mapped["People"] = relationship(
|
||||
# "People", back_populates="buildings", foreign_keys=[people_id]
|
||||
# )
|
||||
# sites: Mapped["BuildSites"] = relationship(
|
||||
# "BuildSites", back_populates="buildings", foreign_keys=[site_id]
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_builds_ndx_00", gov_address_code),
|
||||
Index("_builds_ndx_01", build_name, build_no),
|
||||
{
|
||||
"comment": "Build objects are building that are created for living and store purposes"
|
||||
},
|
||||
)
|
||||
|
||||
@property
|
||||
def management_room(self):
|
||||
if management_room := BuildParts.find_one(
|
||||
id=self.management_room_id, build_id=self.id, active=True, is_confirmed=True
|
||||
):
|
||||
return management_room
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, data: InsertBuild, token):
|
||||
from database_sql_models import Addresses
|
||||
|
||||
data_dict = data.excluded_dump()
|
||||
data_dict["address_id"] = None
|
||||
if data.address_uu_id:
|
||||
official_address = Addresses.find_one(uu_id=data.address_uu_id)
|
||||
data_dict["address_id"] = official_address.id
|
||||
data_dict["build_no"] = str(official_address.build_number)
|
||||
del data_dict["address_uu_id"]
|
||||
if not data_dict["address_id"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Address is not found in database. Re-enter address record then try again.",
|
||||
)
|
||||
build_type = BuildTypes.find_one(uu_id=str(data.build_types_uu_id))
|
||||
data_dict["build_types_id"] = build_type.id
|
||||
del data_dict["build_types_uu_id"]
|
||||
build_created = cls.find_or_create(**data_dict)
|
||||
if not build_created.is_found:
|
||||
cls.__many__table__.find_or_create(
|
||||
company_id=token.selected_company.company_id,
|
||||
employee_id=token.selected_company.employee_id,
|
||||
member_id=build_created.id,
|
||||
is_confirmed=True,
|
||||
)
|
||||
return build_created
|
||||
|
||||
@classmethod
|
||||
def update_action(cls, data: UpdateBuild, build_uu_id: str, token):
|
||||
from database_sql_models import Addresses
|
||||
|
||||
data_dict = data.excluded_dump()
|
||||
if data.official_address_uu_id:
|
||||
official_address = Addresses.find_one(uu_id=data.address_uu_id)
|
||||
data_dict["address_id"] = official_address.id
|
||||
del data_dict["address_uu_id"]
|
||||
if build_to_update := cls.find_one(uu_id=build_uu_id, person_id=token.id):
|
||||
return build_to_update.update(**data_dict)
|
||||
|
||||
@property
|
||||
def top_flat(self):
|
||||
max_flat_no = 0
|
||||
for part in self.parts:
|
||||
if part.part_no > self.max_flat_no:
|
||||
max_flat_no = part.part_no
|
||||
return max_flat_no
|
||||
|
||||
@property
|
||||
def bottom_flat(self):
|
||||
min_flat_no = 0
|
||||
for part in self.parts:
|
||||
if part.part_no < self.max_flat_no:
|
||||
min_flat_no = part.part_no
|
||||
return min_flat_no
|
||||
|
||||
@property
|
||||
def human_livable_parts(self) -> tuple:
|
||||
parts = list(part for part in self.parts if part.human_livable)
|
||||
return parts, len(parts)
|
||||
|
||||
@property
|
||||
def livable_part_count(self):
|
||||
livable_parts = BuildParts.filter_active(
|
||||
BuildParts.build_id == self.id, BuildParts.human_livable == True
|
||||
)
|
||||
if not livable_parts.data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="There is no livable part in this building.",
|
||||
)
|
||||
return livable_parts.count
|
||||
|
||||
@property
|
||||
def part_type_count(self):
|
||||
building_types = None
|
||||
for part in self.parts:
|
||||
building_types = {}
|
||||
build_type = BuildTypes.find_one(id=part.build_part_type_id)
|
||||
if build_type.type_code in building_types:
|
||||
building_types[build_type.type_code]["list"].append(part.part_no)
|
||||
else:
|
||||
building_types[build_type.type_code] = {"list": [part.part_no]}
|
||||
|
||||
# for key, val in building_types.items():
|
||||
# list_parts = val["list"]
|
||||
# building_types[key] = {
|
||||
# "list": list_parts,
|
||||
# "min": min(list_parts),
|
||||
# "max": max(list_parts),
|
||||
# "count": len(list_parts),
|
||||
# }
|
||||
return building_types
|
||||
|
||||
|
||||
class BuildParts(CrudCollection):
|
||||
"""
|
||||
BuildParts class based on declarative_base and BaseMixin via session
|
||||
Attentions: Part_no is unique for each building and Every building must have a management section.!!! default no 0
|
||||
"""
|
||||
|
||||
__tablename__ = "build_parts"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
__enum_list__ = [("part_direction", "Directions", "NN")]
|
||||
|
||||
# https://adres.nvi.gov.tr/VatandasIslemleri/AdresSorgu
|
||||
address_gov_code = mapped_column(
|
||||
String, nullable=False, comment="Goverment Door Code"
|
||||
)
|
||||
# part_name = mapped_column(String(24), server_default="", nullable=False, comment="Part Name")
|
||||
part_no = mapped_column(
|
||||
SmallInteger, server_default="0", nullable=False, comment="Part Number"
|
||||
)
|
||||
part_level = mapped_column(
|
||||
SmallInteger, server_default="0", comment="Building Part Level"
|
||||
)
|
||||
part_code = mapped_column(
|
||||
String, server_default="", nullable=False, comment="Part Code"
|
||||
)
|
||||
part_gross_size = mapped_column(
|
||||
Integer, server_default="0", comment="Part Gross Size"
|
||||
)
|
||||
part_net_size = mapped_column(Integer, server_default="0", comment="Part Net Size")
|
||||
default_accessory = mapped_column(
|
||||
Text, server_default="0", comment="Default Accessory"
|
||||
)
|
||||
human_livable = mapped_column(Boolean, server_default="1", comment="Human Livable")
|
||||
due_part_key = mapped_column(
|
||||
String, server_default="", nullable=False, comment="Constant Payment Group"
|
||||
)
|
||||
|
||||
build_id = mapped_column(
|
||||
ForeignKey("build.id"), nullable=False, comment="Building ID"
|
||||
)
|
||||
build_uu_id = mapped_column(String, nullable=False, comment="Building UUID")
|
||||
part_direction_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
|
||||
part_direction_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Part Direction UUID"
|
||||
)
|
||||
part_type_id = mapped_column(
|
||||
ForeignKey("build_types.id"), nullable=False, comment="Building Part Type"
|
||||
)
|
||||
part_type_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Building Part Type UUID"
|
||||
)
|
||||
|
||||
buildings: Mapped["Build"] = relationship(
|
||||
"Build", back_populates="parts", foreign_keys=[build_id]
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("build_parts_ndx_01", build_id, part_no, unique=True),
|
||||
{"comment": "Part objects that are belong to building objects"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, data: InsertBuildParts, token):
|
||||
data_dict = data.dump()
|
||||
build_from_duty = Build.select_action(
|
||||
employee_id=token.selected_company.employee_id,
|
||||
filter_expr=[Build.uu_id == data.build_uu_id],
|
||||
)
|
||||
building = build_from_duty.first()
|
||||
if not building:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="This Employee can not reach this building or building uu-id not found in database. "
|
||||
"Check with your supervisor.",
|
||||
)
|
||||
|
||||
if build_types := BuildTypes.find_one(uu_id=data.build_part_type_uu_id):
|
||||
part_direction = ApiEnumDropdown.get_by_uuid(
|
||||
uuid=str(data.part_direction_uu_id)
|
||||
)
|
||||
|
||||
data_dict["part_gross_size"] = data.part_gross_size
|
||||
data_dict["part_net_size"] = data.part_net_size
|
||||
data_dict["part_type_id"] = build_types.id
|
||||
data_dict["part_level"] = data.part_level
|
||||
data_dict["build_id"] = building.id
|
||||
data_dict["part_no"] = data.part_no
|
||||
data_dict["part_code"] = (
|
||||
f"{build_types.type_code}:{str(data_dict['part_no']).zfill(2)}"
|
||||
)
|
||||
data_dict["address_gov_code"] = data.address_gov_code
|
||||
data_dict["default_accessory"] = data.default_accessory
|
||||
data_dict["human_livable"] = bool(data.human_livable)
|
||||
|
||||
data_dict["build_uu_id"] = str(data.build_uu_id)
|
||||
data_dict["part_type_id"] = build_types.id
|
||||
data_dict["part_type_uu_id"] = str(build_types.uu_id)
|
||||
data_dict["part_direction_id"] = part_direction.id
|
||||
data_dict["part_direction_uu_id"] = str(part_direction.uu_id)
|
||||
# data_dict["part_direction"] = str(data.part_direction_uu_id)
|
||||
|
||||
if not data_dict["part_gross_size"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Part Gross Size can not be empty.",
|
||||
)
|
||||
|
||||
if not data_dict["part_net_size"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Part Net Size can not be empty.",
|
||||
)
|
||||
pt = int(data_dict["part_net_size"])
|
||||
data_dict["due_part_key"] = str(pt + (5 - (pt % 5))) + "M2"
|
||||
del data_dict["build_part_type_uu_id"]
|
||||
return cls.find_or_create(**data_dict)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Build Part can not be created.",
|
||||
)
|
||||
|
||||
@property
|
||||
def part_name(self):
|
||||
if build_type := BuildTypes.find_one(id=self.build_part_type_id):
|
||||
return f"{str(build_type.type_name).upper()} : {str(self.part_no).upper()}"
|
||||
return f"Undefined:{str(build_type.type_name).upper()}"
|
||||
|
||||
|
||||
class BuildLivingSpace(CrudCollection):
|
||||
"""
|
||||
LivingSpace class based on declarative_base and BaseMixin via session
|
||||
Owner or live person = Occupant of the build part
|
||||
+ Query OR(owner_person_id == person_id, life_person_id == person_id) AND (now(date))
|
||||
"""
|
||||
|
||||
__tablename__ = "build_living_space"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
fix_value = mapped_column(
|
||||
Numeric(20, 6),
|
||||
server_default="0",
|
||||
comment="Fixed value is deducted from debit.",
|
||||
)
|
||||
fix_percent = mapped_column(
|
||||
Numeric(6, 2),
|
||||
server_default="0",
|
||||
comment="Fixed percent is deducted from debit.",
|
||||
)
|
||||
|
||||
agreement_no = mapped_column(String, server_default="", comment="Agreement No")
|
||||
marketing_process = mapped_column(Boolean, server_default="False")
|
||||
marketing_layer = mapped_column(SmallInteger, server_default="0")
|
||||
|
||||
discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22
|
||||
discounted_price = mapped_column(
|
||||
Numeric(20, 2), server_default="0.00"
|
||||
) # Normal: 78.00 TL
|
||||
calculated_price = mapped_column(
|
||||
Numeric(20, 2), server_default="0.00"
|
||||
) # sana düz 75.00 TL yapar
|
||||
|
||||
build_parts_id = mapped_column(
|
||||
ForeignKey("build_parts.id"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Build Part ID",
|
||||
)
|
||||
build_parts_uu_id = mapped_column(String, nullable=False, comment="Build Part UUID")
|
||||
person_id = mapped_column(
|
||||
ForeignKey("people.id"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
comment="Responsible People ID",
|
||||
)
|
||||
person_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Responsible People UUID"
|
||||
)
|
||||
occupant_type = mapped_column(
|
||||
ForeignKey("occupant_types.id"),
|
||||
nullable=False,
|
||||
comment="Occupant Type",
|
||||
)
|
||||
occupant_type_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Occupant Type UUID"
|
||||
)
|
||||
__table_args__ = (
|
||||
{"comment": "Living Space inside building parts that are related to people"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_action(
|
||||
cls,
|
||||
data: dict,
|
||||
token_dict: typing.Union[EmployeeTokenObject, OccupantTokenObject],
|
||||
):
|
||||
from database_sql_models import Services, OccupantTypes
|
||||
from events.events_bind_services import ServiceBindOccupantEventMethods
|
||||
|
||||
created_living_space = BuildLivingSpace.find_or_create(**data)
|
||||
if not created_living_space.is_found:
|
||||
occupant_type = OccupantTypes.find_one(
|
||||
uu_id=created_living_space.occupant_type_uu_id
|
||||
)
|
||||
related_service = Services.find_one(
|
||||
active=True,
|
||||
related_responsibility=occupant_type.occupant_code,
|
||||
)
|
||||
if not related_service:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_418_IM_A_TEAPOT,
|
||||
detail="Service is not found in database. Re-enter service record then try again.",
|
||||
)
|
||||
ServiceBindOccupantEventMethods.bind_services_occupant_system(
|
||||
service_id=related_service.id,
|
||||
build_living_space_id=created_living_space.id,
|
||||
)
|
||||
return created_living_space
|
||||
|
||||
@classmethod
|
||||
def find_living_from_customer_id(
|
||||
cls, customer_id, process_date, add_days: int = 32
|
||||
):
|
||||
formatted_date = datetime.strptime(str(process_date), "%Y-%m-%d %H:%M:%S")
|
||||
living_spaces = cls.filter_active(
|
||||
or_(
|
||||
cls.owner_person_id == customer_id,
|
||||
cls.life_person_id == customer_id,
|
||||
),
|
||||
cls.start_date < formatted_date - timedelta(days=add_days),
|
||||
cls.stop_date > formatted_date + timedelta(days=add_days),
|
||||
)
|
||||
return living_spaces.data, living_spaces.count
|
||||
|
||||
|
||||
class BuildArea(CrudCollection):
|
||||
"""
|
||||
Builds class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "build_area"
|
||||
|
||||
area_name = mapped_column(String, server_default="")
|
||||
area_code = mapped_column(String, server_default="")
|
||||
area_type = mapped_column(String, server_default="GREEN")
|
||||
area_direction = mapped_column(String(2), server_default="NN")
|
||||
area_gross_size = mapped_column(Numeric(20, 6), server_default="0")
|
||||
area_net_size = mapped_column(Numeric(20, 6), server_default="0")
|
||||
width = mapped_column(Integer, server_default="0")
|
||||
size = mapped_column(Integer, server_default="0")
|
||||
|
||||
build_id = mapped_column(ForeignKey("build.id"))
|
||||
build_uu_id = mapped_column(String, comment="Building UUID")
|
||||
part_type_id = mapped_column(
|
||||
ForeignKey("build_types.id"), nullable=True, comment="Building Part Type"
|
||||
)
|
||||
part_type_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Building Part Type UUID"
|
||||
)
|
||||
|
||||
# buildings: Mapped["Build"] = relationship(
|
||||
# "Build", back_populates="areas", foreign_keys=[build_id]
|
||||
# )
|
||||
|
||||
_table_args_ = (
|
||||
Index("_edm_build_parts_area_ndx_00", build_id, area_code, unique=True),
|
||||
)
|
||||
|
||||
|
||||
class BuildSites(CrudCollection):
|
||||
"""
|
||||
Builds class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "build_sites"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
site_name = mapped_column(String(24), nullable=False)
|
||||
site_no = mapped_column(String(8), nullable=False)
|
||||
|
||||
address_id = mapped_column(ForeignKey("addresses.id"))
|
||||
address_uu_id = mapped_column(String, comment="Address UUID")
|
||||
|
||||
# addresses: Mapped["Address"] = relationship(
|
||||
# "Address", back_populates="site", foreign_keys=[address_id]
|
||||
# )
|
||||
# buildings: Mapped["Build"] = relationship(
|
||||
# "Build", back_populates="sites", foreign_keys="Build.site_id"
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_sites_ndx_01", site_no, site_name),
|
||||
{"comment": "Sites that groups building objets"},
|
||||
)
|
||||
|
||||
|
||||
class BuildCompaniesProviding(CrudCollection):
|
||||
"""
|
||||
|
||||
"""
|
||||
|
||||
__tablename__ = "build_companies_providing"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
build_id = mapped_column(ForeignKey("build.id"), nullable=False, comment="Building ID")
|
||||
build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
|
||||
company_id = mapped_column(ForeignKey("companies.id"))
|
||||
company_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
|
||||
provide_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
|
||||
provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
|
||||
contract_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_build_companies_providing_ndx_00", build_id, company_id, provide_id , unique=True),
|
||||
{"comment": "Companies providing services for building"},
|
||||
)
|
||||
|
||||
|
||||
class BuildPersonProviding(CrudCollection):
|
||||
"""
|
||||
|
||||
"""
|
||||
|
||||
__tablename__ = "build_person_providing"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
build_id = mapped_column(ForeignKey("build.id"), nullable=False, comment="Building ID")
|
||||
build_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
|
||||
people_id = mapped_column(ForeignKey("people.id"))
|
||||
people_uu_id = mapped_column(String, nullable=True, comment="People UUID")
|
||||
provide_id = mapped_column(ForeignKey("api_enum_dropdown.id"), nullable=True)
|
||||
provide_uu_id = mapped_column(String, nullable=True, comment="Providing UUID")
|
||||
contract_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_build_person_providing_ndx_00", build_id, people_id, provide_id , unique=True),
|
||||
{"comment": "People providing services for building"},
|
||||
)
|
||||
|
||||
|
||||
# owner_people: Mapped["People"] = relationship(
|
||||
# "People",
|
||||
# back_populates="owner_buildings",
|
||||
# foreign_keys=[current_owner_person_id],
|
||||
# )
|
||||
# tenant_people: Mapped["People"] = relationship(
|
||||
# "People",
|
||||
# back_populates="tenant_buildings",
|
||||
# foreign_keys=[current_tenant_person_id],
|
||||
# )
|
||||
# decision_book_management: Mapped[List["BuildDecisionBookManagement"]] = (
|
||||
# relationship(
|
||||
# "BuildDecisionBookManagement",
|
||||
# back_populates="buildings",
|
||||
# foreign_keys="BuildDecisionBookManagement.build_parts_id",
|
||||
# )
|
||||
# )
|
||||
# budget_records: Mapped[List["CompanyBudgetRecords"]] = relationship(
|
||||
# "CompanyBudgetRecords",
|
||||
# back_populates="parts",
|
||||
# foreign_keys="CompanyBudgetRecords.build_parts_id",
|
||||
# )
|
||||
# living_spaces: Mapped[List["BuildLivingSpace"]] = relationship(
|
||||
# "BuildLivingSpace",
|
||||
# back_populates="parts",
|
||||
# foreign_keys="BuildLivingSpace.build_parts_id",
|
||||
# )
|
||||
# decision_book_payment_master: Mapped[List["BuildDecisionBookPaymentsMaster"]] = (
|
||||
# relationship(
|
||||
# "BuildDecisionBookPaymentsMaster",
|
||||
# back_populates="parts",
|
||||
# foreign_keys="BuildDecisionBookPaymentsMaster.build_parts_id",
|
||||
# )
|
||||
# )
|
||||
# decision_book_project_payments_master: Mapped[
|
||||
# "BuildDecisionBookProjectPaymentsMaster"
|
||||
# ] = relationship(
|
||||
# "BuildDecisionBookProjectPaymentsMaster",
|
||||
# back_populates="parts",
|
||||
# foreign_keys="BuildDecisionBookProjectPaymentsMaster.build_parts_id",
|
||||
# )
|
||||
# search_iban_description: Mapped["BuildIbanDescription"] = relationship(
|
||||
# "BuildIbanDescription",
|
||||
# back_populates="parts",
|
||||
# foreign_keys="BuildIbanDescription.build_parts_id",
|
||||
# )
|
||||
|
||||
# parts: Mapped[List["BuildParts"]] = relationship(
|
||||
# "BuildParts", back_populates="living_spaces", foreign_keys=[build_parts_id]
|
||||
# )
|
||||
# owner_people: Mapped["People"] = relationship(
|
||||
# "People", back_populates="owner_living_spaces", foreign_keys=[owner_person_id]
|
||||
# )
|
||||
# life_people: Mapped["People"] = relationship(
|
||||
# "People", back_populates="life_living_spaces", foreign_keys=[life_person_id]
|
||||
# )
|
||||
# company_id = mapped_column(ForeignKey("companies.id"))
|
||||
# response_company_id = mapped_column(ForeignKey("companies.id"))
|
||||
# person_id = mapped_column(ForeignKey("people.id"))
|
||||
|
||||
# companies: Mapped["Companies"] = relationship(
|
||||
# "Companies", back_populates="buildings", foreign_keys=[company_id]
|
||||
# )
|
||||
# @classmethod
|
||||
# def select_action(cls, duty_id, token=None):
|
||||
# from database_sql_models import Companies
|
||||
#
|
||||
# related_companies = Companies.select_action(duty_id=duty_id)
|
||||
# companies_ids = [company.id for company in related_companies.all()]
|
||||
# return cls.filter_all(cls.company_id.in_(companies_ids)).query
|
||||
1581
databases/sql_models/building/decision_book.py
Normal file
1581
databases/sql_models/building/decision_book.py
Normal file
File diff suppressed because it is too large
Load Diff
535
databases/sql_models/company/company.py
Normal file
535
databases/sql_models/company/company.py
Normal file
@@ -0,0 +1,535 @@
|
||||
from fastapi.exceptions import HTTPException
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
from sqlalchemy import String, Integer, Boolean, ForeignKey, Index
|
||||
from sqlalchemy.orm import mapped_column
|
||||
|
||||
from api_configs import RelationAccess
|
||||
from application.shared_classes import SelectAction, Explanation
|
||||
from validations import InsertCompany, UpdateCompany
|
||||
from validations.company import MatchCompany2Company
|
||||
from valids.auth.token_validations import EmployeeTokenObject
|
||||
|
||||
|
||||
class RelationshipDutyCompany(CrudCollection):
|
||||
"""
|
||||
CompanyRelationship class based on declarative_base and CrudCollection via session
|
||||
Company -> Sub Company -> Sub-Sub Company
|
||||
|
||||
if owner_id == parent_id: can manipulate data of any record
|
||||
else: Read-Only
|
||||
duty_id = if relationship_type == base An organization / not operational / no responsible person
|
||||
|
||||
relationship = company_id filter -> Action filter(company_id) relationship_type = Organization
|
||||
relationship = company_id filter -> Action filter(company_id) relationship_type = Commercial
|
||||
"""
|
||||
|
||||
__tablename__ = "relationship_duty_company"
|
||||
__exclude__fields__ = []
|
||||
__access_by__ = RelationAccess.SuperAccessList
|
||||
|
||||
owner_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1
|
||||
duties_id = mapped_column(
|
||||
ForeignKey("duties.id"), nullable=False
|
||||
) # duty -> (n)employee Evyos LTD
|
||||
|
||||
member_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 2, 3, 4
|
||||
parent_id = mapped_column(ForeignKey("companies.id"), nullable=True) # None
|
||||
|
||||
relationship_type = mapped_column(
|
||||
String, nullable=True, server_default="Commercial"
|
||||
) # Commercial, Organization # Bulk
|
||||
child_count = mapped_column(Integer) # 0
|
||||
show_only = mapped_column(Boolean, server_default="0")
|
||||
|
||||
# related_company: Mapped[List["Companies"]] = relationship(
|
||||
# "Companies",
|
||||
# back_populates="related_companies",
|
||||
# foreign_keys=[related_company_id],
|
||||
# )
|
||||
|
||||
@classmethod
|
||||
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(
|
||||
"company_id"
|
||||
)
|
||||
send_duties, list_match_company_id = Duties.find_one(uu_id=data.duty_uu_id), []
|
||||
send_user_duties = Duties.find_one(
|
||||
duties_id=send_duties.id, company_id=token_duties_id
|
||||
)
|
||||
if not send_user_duties:
|
||||
raise Exception(
|
||||
"Send Duty is not found in company. Please check duty uuid and try again."
|
||||
)
|
||||
|
||||
for company_uu_id in list(data.match_company_uu_id):
|
||||
company = Companies.find_one(uu_id=company_uu_id)
|
||||
bulk_company = RelationshipDutyCompany.find_one(
|
||||
owner_id=token_company_id,
|
||||
relationship_type="Bulk",
|
||||
member_id=company.id,
|
||||
)
|
||||
if not bulk_company:
|
||||
raise Exception(
|
||||
f"Bulk Company is not found in company. "
|
||||
f"Please check company uuid {bulk_company.uu_id} and try again."
|
||||
)
|
||||
list_match_company_id.append(bulk_company)
|
||||
|
||||
for match_company_id in list_match_company_id:
|
||||
RelationshipDutyCompany.find_or_create(
|
||||
owner_id=token_company_id,
|
||||
duties_id=send_user_duties.id,
|
||||
member_id=match_company_id.id,
|
||||
parent_id=match_company_id.parent_id,
|
||||
relationship_type="Commercial",
|
||||
show_only=False,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
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(
|
||||
"company_id"
|
||||
)
|
||||
send_duties, list_match_company_id = Duties.find_one(uu_id=data.duty_uu_id), []
|
||||
send_user_duties = Duties.find_one(
|
||||
duties_id=send_duties.id, company_id=token_duties_id
|
||||
)
|
||||
if not send_user_duties:
|
||||
raise Exception(
|
||||
"Send Duty is not found in company. Please check duty uuid and try again."
|
||||
)
|
||||
|
||||
for company_uu_id in list(data.match_company_uu_id):
|
||||
company = Companies.find_one(uu_id=company_uu_id)
|
||||
bulk_company = RelationshipDutyCompany.find_one(
|
||||
owner_id=token_company_id,
|
||||
relationship_type="Bulk",
|
||||
member_id=company.id,
|
||||
)
|
||||
if not bulk_company:
|
||||
raise Exception(
|
||||
f"Bulk Company is not found in company. "
|
||||
f"Please check company uuid {bulk_company.uu_id} and try again."
|
||||
)
|
||||
list_match_company_id.append(bulk_company)
|
||||
|
||||
for match_company_id in list_match_company_id:
|
||||
Duties.init_a_company_default_duties(company_id=match_company_id.id)
|
||||
RelationshipDutyCompany.find_or_create(
|
||||
owner_id=token_company_id,
|
||||
duties_id=send_user_duties.id,
|
||||
member_id=match_company_id.id,
|
||||
parent_id=match_company_id.parent_id,
|
||||
relationship_type="Organization",
|
||||
show_only=False,
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_company_relationship_ndx_01",
|
||||
duties_id,
|
||||
owner_id,
|
||||
member_id,
|
||||
relationship_type,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Company Relationship Information"},
|
||||
)
|
||||
|
||||
|
||||
class AbstractCompany:
|
||||
"""
|
||||
Abstract and explanation of Company class for end-user guide
|
||||
"""
|
||||
|
||||
formal_name = Explanation(
|
||||
explanation="Devletin resmi kayıtlarında bulunan şirket ünvanıdır.",
|
||||
usage="Devletin resmi kayıtlarında bulunan şirket adı istendiğinde kullanılır.",
|
||||
alias="Resmi Ünvan",
|
||||
example=["X Şirketi LTD", "Y Şirketi A.Ş."],
|
||||
)
|
||||
company_type = Explanation(
|
||||
explanation="Şirketin türüdür.",
|
||||
usage="Şirketin türü istendiğinde kullanılır.",
|
||||
alias="Şirket Türü",
|
||||
example=[
|
||||
"Şahıs",
|
||||
"Limited",
|
||||
"Anonim",
|
||||
"Kolektif",
|
||||
"Komandit",
|
||||
"Kooperatif",
|
||||
"Serbest Meslek",
|
||||
"Adi Ortaklık",
|
||||
],
|
||||
)
|
||||
commercial_type = Explanation(
|
||||
explanation="Şirketin ticari türüdür.",
|
||||
usage="Şirketin ticari türü istendiğinde kullanılır.",
|
||||
alias="Ticari Tür",
|
||||
example=["Tüzel", "Birey"],
|
||||
)
|
||||
tax_no = Explanation(
|
||||
explanation="Şirketin vergi numarasıdır.",
|
||||
usage="Şirketin vergi numarası istendiğinde kullanılır.",
|
||||
alias="Vergi No",
|
||||
example=["1234567890"],
|
||||
)
|
||||
public_name = Explanation(
|
||||
explanation="Şirketin kamuoyunda bilinen adıdır.",
|
||||
usage="Şirketin kamuoyunda bilinen adı istendiğinde kullanılır.",
|
||||
alias="Piyasada Bilinen Adı",
|
||||
example=["X Şirketi", "Y Şirketi"],
|
||||
)
|
||||
company_tag = Explanation(
|
||||
explanation="Şirketin takma adı veya etiketidir.",
|
||||
usage="Şirketin yöneticisin karar verdiği takma adı veya etiketi istendiğinde kullanılır.",
|
||||
alias="Şirket Etiketi veya Takma Adı",
|
||||
example=["X", "Y"],
|
||||
)
|
||||
default_lang_type = Explanation(
|
||||
explanation="Şirketin varsayılan dil türüdür.",
|
||||
usage="Şirketin varsayılan dil türü istendiğinde kullanılır.",
|
||||
alias="Şirketin Dil Türü",
|
||||
example=["TR", "EN"],
|
||||
)
|
||||
default_money_type = Explanation(
|
||||
explanation="Şirketin varsayılan para birimi türüdür.",
|
||||
usage="Şirketin varsayılan para birimi türü istendiğinde kullanılır.",
|
||||
alias="Şirketin Para Birimi Türü",
|
||||
example=["TL", "USD", "EUR"],
|
||||
)
|
||||
is_commercial = Explanation(
|
||||
explanation="Şirketin ticari olup olmadığını belirtir.",
|
||||
usage="Şirketin ticari olup olmadığını applikasyonun anlaması için kullanılır.",
|
||||
condition=lambda commercial_type: True if commercial_type == "Şahıs" else False,
|
||||
alias="Şirket Ticari mi?",
|
||||
)
|
||||
is_blacklist = Explanation(
|
||||
explanation="Şirketin kara listeye alınıp alınmadığını belirtir.",
|
||||
usage="Şirketin kara listeye alınıp alınmadığını applikasyonun anlaması için kullanılır.",
|
||||
alias="Kara Listeye alınsın mı?",
|
||||
example=[True, False],
|
||||
)
|
||||
parent_id = Explanation(
|
||||
explanation="Şirketin sorumlu olduğu şirketin ID'sidir.",
|
||||
usage="Şirketin sorumlu olduğu şirketin ID'si istendiğinde kullanılır.",
|
||||
alias="Sorumlu Şirket",
|
||||
example=[
|
||||
"Bir şirketin sorumlu şirketi hangisi olduğunu bulmak için kullanılır.",
|
||||
],
|
||||
)
|
||||
workplace_no = Explanation(
|
||||
explanation="Şirketin iş yeri numarasıdır.",
|
||||
usage="Şirketin iş yeri numarası istendiğinde kullanılır.",
|
||||
alias="İş Yeri No",
|
||||
example=["1234567890"],
|
||||
)
|
||||
official_address_id = Explanation(
|
||||
explanation="Şirketin resmi adresidi.",
|
||||
usage="Şirketin resmi adresinin ne olduğunu bulmak için kullanılır.",
|
||||
alias="Resmi Adres",
|
||||
example=[
|
||||
"Bu şirketin adresi nedir sorusuna cevap vermek için kullanılır.",
|
||||
],
|
||||
)
|
||||
top_responsible_company_id = Explanation(
|
||||
explanation="Şirketin en üst sorumlu şirketin ID'sidir.",
|
||||
usage="Şirketin en üst sorumlu şirketin hangisi olduğunu bulmak için kullanılır.",
|
||||
alias="Ana Yetkili Şirket",
|
||||
example=[
|
||||
"Bölge veya ülke genelinde en üst sorumlu şirketin hangisi olduğunu belirtmek için kullanılır.",
|
||||
],
|
||||
)
|
||||
buildings = Explanation(
|
||||
explanation="Şirketin sahip olduğu binaların listesidir.",
|
||||
usage="Şirketin sahip olduğu binaların listesini bulmak için kullanılır.",
|
||||
alias="Sorumlu olduğu binalar Binalar",
|
||||
example=[
|
||||
"Şirketin sahip olduğu binaların listesini bulmak için kullanılır.",
|
||||
],
|
||||
)
|
||||
|
||||
def wag_create_company(self):
|
||||
"""
|
||||
Er kişiye wag_create_company fonksiyonu = fieldları manipule edebilir?
|
||||
78 ile oluşturulan bir user için wag_create_company fonksiyonu = fieldları manipule edebilir?
|
||||
"""
|
||||
return {
|
||||
"commercial_type": self.commercial_type,
|
||||
"formal_name": self.formal_name,
|
||||
"public_name": self.public_name,
|
||||
"company_type": self.company_type,
|
||||
"tax_no": self.tax_no,
|
||||
"workplace_no": self.workplace_no,
|
||||
"company_tag": self.company_tag,
|
||||
"default_lang_type": self.default_lang_type,
|
||||
"default_money_type": self.default_money_type,
|
||||
"official_address_id": self.official_address_id,
|
||||
}
|
||||
|
||||
def wag_update_company(self):
|
||||
return {
|
||||
"commercial_type": self.commercial_type,
|
||||
"formal_name": self.formal_name,
|
||||
"public_name": self.public_name,
|
||||
"company_type": self.company_type,
|
||||
"tax_no": self.tax_no,
|
||||
"workplace_no": self.workplace_no,
|
||||
"company_tag": self.company_tag,
|
||||
"default_lang_type": self.default_lang_type,
|
||||
"default_money_type": self.default_money_type,
|
||||
"official_address_id": self.official_address_id,
|
||||
}
|
||||
|
||||
|
||||
class Companies(CrudCollection, SelectAction):
|
||||
"""
|
||||
Company class based on declarative_base and CrudCollection via session
|
||||
formal_name = Government register name by offical
|
||||
public_name = Public registered name by User
|
||||
nick_name = Search by nickname, commercial_type = Tüzel veya birey
|
||||
"""
|
||||
|
||||
__tablename__ = "companies"
|
||||
|
||||
__exclude__fields__ = ["is_blacklist", "is_commercial"]
|
||||
__access_by__ = []
|
||||
__many__table__ = RelationshipDutyCompany
|
||||
__explain__ = AbstractCompany()
|
||||
|
||||
formal_name = mapped_column(String, nullable=False, comment="Formal Name")
|
||||
company_type = mapped_column(String, nullable=False, comment="Company Type")
|
||||
commercial_type = mapped_column(String, nullable=False, comment="Commercial Type")
|
||||
tax_no = mapped_column(
|
||||
String, index=True, unique=True, nullable=False, comment="Tax No"
|
||||
)
|
||||
|
||||
public_name = mapped_column(String, comment="Public Name of a company")
|
||||
company_tag = mapped_column(String, comment="Company Tag")
|
||||
default_lang_type = mapped_column(String, server_default="TR")
|
||||
default_money_type = mapped_column(String, server_default="TL")
|
||||
is_commercial = mapped_column(Boolean, server_default="False")
|
||||
is_blacklist = mapped_column(Boolean, server_default="False")
|
||||
parent_id = mapped_column(Integer, nullable=True)
|
||||
workplace_no = mapped_column(String, nullable=True)
|
||||
|
||||
official_address_id = mapped_column(ForeignKey("addresses.id"))
|
||||
official_address_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Official Address UUID"
|
||||
)
|
||||
top_responsible_company_id = mapped_column(
|
||||
ForeignKey("companies.id"), nullable=True
|
||||
)
|
||||
top_responsible_company_uu_id = mapped_column(
|
||||
String, nullable=True, comment="Top Responsible Company UUID"
|
||||
)
|
||||
|
||||
# buildings: Mapped[List["Build"]] = relationship(
|
||||
# "Build",
|
||||
# back_populates="companies",
|
||||
# foreign_keys="Build.company_id",
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_company_ndx_01", tax_no, unique=True),
|
||||
Index("_company_ndx_02", formal_name, public_name),
|
||||
{"comment": "Company Information"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, data: InsertCompany, token: EmployeeTokenObject):
|
||||
from database_sql_models import Addresses, Duties
|
||||
|
||||
data_dict = data.model_dump()
|
||||
if cls.find_one(tax_no=str(data.tax_no).strip()):
|
||||
raise Exception(
|
||||
"Company already exists. Please ask supervisor to make company visible for your duty."
|
||||
)
|
||||
|
||||
official_address = Addresses.find_one(uu_id=data.official_address_uu_id)
|
||||
if not official_address:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Official address is not found. Please check address uuid and try again.",
|
||||
)
|
||||
|
||||
bulk_duties = Duties.get_bulk_duties_of_a_company(
|
||||
company_id=token.selected_company.company_id
|
||||
)
|
||||
|
||||
data_dict["parent_id"] = token.selected_company.company_id
|
||||
data_dict["official_address_id"] = official_address.id
|
||||
data_dict["official_address_uu_id"] = str(official_address.uu_id)
|
||||
data_dict["top_responsible_company_id"] = token.selected_company.company_id
|
||||
data_dict["top_responsible_company_uu_id"] = (
|
||||
token.selected_company.company_uu_id
|
||||
)
|
||||
|
||||
company_created = cls.find_or_create(**data_dict)
|
||||
if not company_created.is_found:
|
||||
RelationshipDutyCompany.find_or_create(
|
||||
owner_id=token.selected_company.company_id,
|
||||
duties_id=bulk_duties.id,
|
||||
member_id=company_created.id,
|
||||
parent_id=company_created.parent_id,
|
||||
relationship_type="Bulk",
|
||||
show_only=False,
|
||||
)
|
||||
if (
|
||||
not str(token.get("priority_code")) == "78"
|
||||
): # Company based configuration will be applied
|
||||
user_duties = Duties.find_one(
|
||||
duties_id=token.selected_company.duty_id,
|
||||
company_id=token.selected_company.company_id,
|
||||
)
|
||||
RelationshipDutyCompany.find_or_create(
|
||||
owner_id=token.selected_company.company_id,
|
||||
duties_id=user_duties.id,
|
||||
member_id=company_created.id,
|
||||
parent_id=company_created.parent_id,
|
||||
relationship_type="Commercial",
|
||||
show_only=False,
|
||||
)
|
||||
return company_created
|
||||
|
||||
@classmethod
|
||||
def update_action(cls, data: UpdateCompany, token):
|
||||
from database_sql_models import Addresses
|
||||
|
||||
data_dict = data.excluded_dump()
|
||||
duty_id = token.get("duty_id")
|
||||
company_id = token.get("company_id")
|
||||
if data.official_address_uu_id:
|
||||
official_address = Addresses.find_one(uu_id=data.official_address_uu_id)
|
||||
data_dict["official_address_id"] = official_address.id
|
||||
del data_dict["official_address_uu_id"], data_dict["company_uu_id"]
|
||||
company_to_update = cls.select_action(
|
||||
duty_id=duty_id,
|
||||
filter_expr=[
|
||||
cls.uu_id == data.company_uu_id,
|
||||
RelationshipDutyCompany.parent_id == company_id,
|
||||
],
|
||||
)
|
||||
return company_to_update.update(**data_dict)
|
||||
|
||||
# parent_id = mapped_column(ForeignKey("companies.id"))
|
||||
# if data.parent_uu_id:
|
||||
# company = Companies.find_one(uu_id=data.parent_uu_id)
|
||||
# data_dict["parent_id"] = company.id
|
||||
# def is_access_valid(self, endpoint_ext: str):
|
||||
# try:
|
||||
# if (
|
||||
# not arrow.get(self.stop_date)
|
||||
# > arrow.utcnow()
|
||||
# > arrow.get(self.start_date)
|
||||
# ):
|
||||
# message = f"Kullanıcı yetkileri süresi dolmuştur. {self.endpoint_name} için supervisor ile görüşünüz."
|
||||
# SystemLogs.create_log(
|
||||
# log_type="ERROR",
|
||||
# log_code="ACCESS_EXPIRED",
|
||||
# log_action=self.__tablename__,
|
||||
# log_message=message,
|
||||
# )
|
||||
# return False
|
||||
# except Exception as e:
|
||||
# SystemLogs.create_log(
|
||||
# log_type="ERROR",
|
||||
# log_code="ACCESS_EXPIRED",
|
||||
# log_action=self.__tablename__,
|
||||
# log_message=e,
|
||||
# )
|
||||
# return False
|
||||
#
|
||||
# access_dict = {
|
||||
# "LIST": self.access_read,
|
||||
# "INSERT": self.access_write,
|
||||
# "UPDATE": self.access_update,
|
||||
# "DELETE": self.access_delete,
|
||||
# "ACTIVE": self.access_update,
|
||||
# "PRINT": self.report_print,
|
||||
# "EXPORT": self.report_export,
|
||||
# }
|
||||
# return access_dict.get(endpoint_ext.upper(), False)
|
||||
|
||||
# official_address: Mapped[List["Address"]] = relationship(
|
||||
# "Address",
|
||||
# back_populates="official_companies",
|
||||
# foreign_keys=[official_address_id],
|
||||
# )
|
||||
#
|
||||
# emails: Mapped[List["UsersEmails"]] = relationship(
|
||||
# "UsersEmails", back_populates="companies", foreign_keys="UsersEmails.company_id"
|
||||
# )
|
||||
# phones: Mapped[List["UsersPhones"]] = relationship(
|
||||
# "UsersPhones", back_populates="company", foreign_keys="UsersPhones.company_id"
|
||||
# )
|
||||
# buildings: Mapped[List["Build"]] = relationship(
|
||||
# "Build",
|
||||
# back_populates="companies",
|
||||
# foreign_keys="Build.company_id",
|
||||
# )
|
||||
# response_buildings: Mapped[List["Build"]] = relationship(
|
||||
# "Build",
|
||||
# back_populates="response_companies",
|
||||
# foreign_keys="Build.response_company_id",
|
||||
# )
|
||||
# departments: Mapped[List["CompanyDepartments"]] = relationship(
|
||||
# "CompanyDepartments",
|
||||
# back_populates="company",
|
||||
# foreign_keys="CompanyDepartments.company_id",
|
||||
# )
|
||||
# budget_records: Mapped[List["CompanyBudgetRecords"]] = relationship(
|
||||
# "CompanyBudgetRecords",
|
||||
# back_populates="companies",
|
||||
# foreign_keys="CompanyBudgetRecords.company_id",
|
||||
# )
|
||||
# send_budget_records: Mapped[List["CompanyBudgetRecords"]] = relationship(
|
||||
# "CompanyBudgetRecords",
|
||||
# back_populates="send_companies",
|
||||
# foreign_keys="CompanyBudgetRecords.send_company_id",
|
||||
# )
|
||||
# decision_books: Mapped[List["BuildDecisionBook"]] = relationship(
|
||||
# "BuildDecisionBook",
|
||||
# back_populates="companies",
|
||||
# foreign_keys="BuildDecisionBook.resp_company_id",
|
||||
# )
|
||||
# decision_book_projects: Mapped[List["BuildDecisionBookProjects"]] = relationship(
|
||||
# "BuildDecisionBookProjects",
|
||||
# back_populates="companies",
|
||||
# foreign_keys="BuildDecisionBookProjects.resp_company_id",
|
||||
# )
|
||||
# decision_book_legal: Mapped["BuildDecisionBookLegal"] = relationship(
|
||||
# "BuildDecisionBookLegal",
|
||||
# back_populates="attorney_companies",
|
||||
# foreign_keys="BuildDecisionBookLegal.resp_attorney_company",
|
||||
# )
|
||||
#
|
||||
# company_account_books: Mapped["AccountBooks"] = relationship(
|
||||
# "AccountBooks",
|
||||
# back_populates="company",
|
||||
# foreign_keys="AccountBooks.company_id",
|
||||
# )
|
||||
# branch_account_books: Mapped["AccountBooks"] = relationship(
|
||||
# "AccountBooks",
|
||||
# back_populates="branch",
|
||||
# foreign_keys="AccountBooks.branch_id",
|
||||
# )
|
||||
# account_codes: Mapped["AccountCodes"] = relationship(
|
||||
# "AccountCodes", back_populates="company", foreign_keys="AccountCodes.company_id"
|
||||
# )
|
||||
# search_iban_description: Mapped["BuildIbanDescription"] = relationship(
|
||||
# "BuildIbanDescription",
|
||||
# back_populates="company",
|
||||
# foreign_keys="BuildIbanDescription.company_id",
|
||||
# )
|
||||
# related_companies: Mapped[List["CompanyRelationship"]] = relationship(
|
||||
# "CompanyRelationship",
|
||||
# back_populates="related_company",
|
||||
# foreign_keys="CompanyRelationship.related_company_id",
|
||||
# )
|
||||
206
databases/sql_models/company/department.py
Normal file
206
databases/sql_models/company/department.py
Normal file
@@ -0,0 +1,206 @@
|
||||
from sqlalchemy import String, Integer, ForeignKey, Index, Boolean
|
||||
from sqlalchemy.orm import mapped_column
|
||||
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
|
||||
class Departments(CrudCollection):
|
||||
|
||||
__tablename__ = "departments"
|
||||
__exclude__fields__ = []
|
||||
|
||||
parent_department_id = mapped_column(Integer, server_default="0")
|
||||
department_code = mapped_column(
|
||||
String(16), nullable=False, index=True, comment="Department Code"
|
||||
)
|
||||
department_name = mapped_column(
|
||||
String(128), nullable=False, comment="Department Name"
|
||||
)
|
||||
department_description = mapped_column(String, server_default="")
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"), nullable=False)
|
||||
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID")
|
||||
|
||||
# @classmethod
|
||||
# def create_action(cls, data: DepartmentsPydantic, token):
|
||||
# data_dict = data.model_dump()
|
||||
# data_dict["company_id"] = token.selected_company.company_id
|
||||
# return cls.find_or_create(**data_dict)
|
||||
|
||||
__table_args__ = {"comment": "Departments Information"}
|
||||
|
||||
|
||||
class Duty(CrudCollection):
|
||||
|
||||
__tablename__ = "duty"
|
||||
__exclude__fields__ = []
|
||||
|
||||
duty_name = mapped_column(String, unique=True, nullable=False, comment="Duty Name")
|
||||
duty_code = mapped_column(String, nullable=False, comment="Duty Code")
|
||||
duty_description = mapped_column(String, comment="Duty Description")
|
||||
|
||||
# @classmethod
|
||||
# def create_action(cls, data: InsertCompanyDuty, token):
|
||||
# # if not cls.__is_super__:
|
||||
# # raise HTTPException(
|
||||
# # status_code=401, detail="You are not authorized to create a duty."
|
||||
# # )
|
||||
# data_dict = data.model_dump()
|
||||
#
|
||||
# return cls.find_or_create(**data_dict)
|
||||
|
||||
__table_args__ = ({"comment": "Duty Information"},)
|
||||
|
||||
|
||||
class Duties(CrudCollection):
|
||||
|
||||
__tablename__ = "duties"
|
||||
__exclude__fields__ = []
|
||||
|
||||
users_default_duty = mapped_column(
|
||||
ForeignKey("duty.id"), nullable=True, comment="Default Duty for Users"
|
||||
)
|
||||
company_id = mapped_column(Integer)
|
||||
company_uu_id = mapped_column(String, nullable=False, comment="Company UUID")
|
||||
duties_id = mapped_column(ForeignKey("duty.id"), nullable=False)
|
||||
duties_uu_id = mapped_column(String, nullable=False, comment="Duty UUID")
|
||||
department_id = mapped_column(
|
||||
ForeignKey("departments.id"), nullable=False, comment="Department ID"
|
||||
)
|
||||
department_uu_id = mapped_column(String, nullable=False, comment="Department UUID")
|
||||
# priority_id = mapped_column(ForeignKey("priority.id"), nullable=True)
|
||||
management_duty = mapped_column(
|
||||
Boolean, server_default="0"
|
||||
) # is this a prime Company Duty ???
|
||||
|
||||
@classmethod
|
||||
def init_a_company_default_duties(cls, company_id, company_uu_id):
|
||||
__default_init__ = ["Execution Office", "IT Department"]
|
||||
|
||||
active_row = dict(
|
||||
is_confirmed=True, active=True, deleted=False, is_notification_send=True
|
||||
)
|
||||
|
||||
execution = Departments.find_or_create(
|
||||
department_name="Execution Office",
|
||||
department_code="EO001",
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
**active_row,
|
||||
)
|
||||
it_dept = Departments.find_or_create(
|
||||
department_name="IT Department",
|
||||
department_code="ITD001",
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
**active_row,
|
||||
)
|
||||
bm_duty = Duty.find_or_create(
|
||||
duty_name="Business Manager",
|
||||
duty_code="BM0001",
|
||||
duty_description="Business Manager",
|
||||
**active_row,
|
||||
)
|
||||
it_duty = Duty.find_or_create(
|
||||
duty_name="IT Manager",
|
||||
duty_code="IT0001",
|
||||
duty_description="IT Manager",
|
||||
**active_row,
|
||||
)
|
||||
bulk_duty = Duty.find_or_create(
|
||||
duty_name="BULK",
|
||||
duty_code="BULK",
|
||||
duty_description="BULK RECORDS OF THE COMPANY",
|
||||
**active_row,
|
||||
)
|
||||
occu_duty = Duty.find_or_create(
|
||||
duty_name="OCCUPANT",
|
||||
duty_code="OCCUPANT",
|
||||
duty_description="OCCUPANT RECORDS OF THE COMPANY",
|
||||
**active_row,
|
||||
)
|
||||
cls.find_or_create(
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
duties_id=bm_duty.id,
|
||||
duties_uu_id=str(bm_duty.uu_id),
|
||||
department_id=execution.id,
|
||||
**active_row,
|
||||
)
|
||||
cls.find_or_create(
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
duties_id=it_duty.id,
|
||||
duties_uu_id=str(it_duty.uu_id),
|
||||
department_id=it_dept.id,
|
||||
department_uu_id=str(it_dept.uu_id),
|
||||
**active_row,
|
||||
)
|
||||
cls.find_or_create(
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
duties_id=bulk_duty.id,
|
||||
duties_uu_id=str(bulk_duty.uu_id),
|
||||
department_id=execution.id,
|
||||
department_uu_id=str(execution.uu_id),
|
||||
**active_row,
|
||||
)
|
||||
cls.find_or_create(
|
||||
company_id=company_id,
|
||||
company_uu_id=str(company_uu_id),
|
||||
duties_id=occu_duty.id,
|
||||
duties_uu_id=str(occu_duty.uu_id),
|
||||
department_id=execution.id,
|
||||
department_uu_id=str(execution.uu_id),
|
||||
**active_row,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_bulk_duties_of_a_company(cls, company_id):
|
||||
if bulk_duties := Duties.find_one(
|
||||
duties_id=Duty.find_one(duty_code="BULK").id, company_id=company_id
|
||||
):
|
||||
return bulk_duties
|
||||
raise Exception("Bulk Duty not found. Please contact with supervisor.")
|
||||
|
||||
# @classmethod
|
||||
# def create_action(cls, data: InsertCompanyDuty):
|
||||
# data_dict = data.model_dump()
|
||||
# if department := Departments.find_one(uu_id=data.department_uu_id):
|
||||
# data_dict["department_id"] = department.id
|
||||
# del data_dict["department_uu_id"]
|
||||
# return cls.find_or_create(**data_dict)
|
||||
|
||||
__table_args__ = (
|
||||
Index("duty_ndx_00", company_id, duties_id, department_id, unique=True),
|
||||
{"comment": "Duty & Company & Department Information"},
|
||||
)
|
||||
|
||||
# department: Mapped[List["CompanyDepartments"]] = relationship(
|
||||
# "CompanyDepartments", back_populates="duties", foreign_keys=[department_id]
|
||||
# )
|
||||
# employees: Mapped[List["CompanyEmployees"]] = relationship(
|
||||
# "CompanyEmployees",
|
||||
# back_populates="duty",
|
||||
# foreign_keys="CompanyEmployees.duty_id",
|
||||
# )
|
||||
# duty_app: Mapped["CompanyDutyApp"] = relationship(
|
||||
# "CompanyDutyApp", back_populates="duties", foreign_keys="CompanyDutyApp.company_duty_id"
|
||||
# )
|
||||
|
||||
# def get_language_of_duty(self, lang):
|
||||
# if erp_text := ErpText.find_one(lang=lang, text_code=self.duty_code):
|
||||
# return erp_text.text_name, erp_text.text_description
|
||||
# return None, None
|
||||
|
||||
# company: Mapped["Companies"] = relationship(
|
||||
# "Company", back_populates="departments", foreign_keys=[company_id]
|
||||
# )
|
||||
# duties: Mapped[List["CompanyDuty"]] = relationship(
|
||||
# "CompanyDuty",
|
||||
# back_populates="department",
|
||||
# foreign_keys="CompanyDuty.department_id",
|
||||
# )
|
||||
# app_item: Mapped["AppItems"] = relationship(
|
||||
# "AppItems", back_populates="department", foreign_keys="AppItems.department_id"
|
||||
# )
|
||||
120
databases/sql_models/company/employee.py
Normal file
120
databases/sql_models/company/employee.py
Normal file
@@ -0,0 +1,120 @@
|
||||
from sqlalchemy import (
|
||||
String,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Numeric,
|
||||
)
|
||||
from sqlalchemy.orm import mapped_column
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
from validations import InsertCompanyEmployees
|
||||
|
||||
|
||||
class Staff(CrudCollection):
|
||||
|
||||
__tablename__ = "staff"
|
||||
__exclude__fields__ = []
|
||||
|
||||
staff_description = mapped_column(
|
||||
String, server_default="", comment="Staff Description"
|
||||
)
|
||||
staff_name = mapped_column(String, nullable=False, comment="Staff Name")
|
||||
staff_code = mapped_column(String, nullable=False, comment="Staff Code")
|
||||
|
||||
duties_id = mapped_column(ForeignKey("duties.id"), nullable=False)
|
||||
duties_uu_id = mapped_column(String, nullable=False, comment="Duty UUID")
|
||||
|
||||
# people: Mapped["People"] = relationship(
|
||||
# "People", back_populates="employees", foreign_keys=[people_id], uselist=True
|
||||
# )
|
||||
# duty: Mapped["CompanyDuty"] = relationship(
|
||||
# "CompanyDuty", back_populates="employees", foreign_keys=[duty_id]
|
||||
# )
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, data: InsertCompanyEmployees):
|
||||
from database_sql_models import Duties
|
||||
|
||||
data_dict = data.model_dump()
|
||||
if duty := Duties.find_one(uu_id=data.duty_uu_id):
|
||||
data_dict["duty_id"] = duty.id
|
||||
# if person := People.find_one(uu_id=data.person_uu_id):
|
||||
# data_dict["people_id"] = person.id
|
||||
if data.start_date:
|
||||
data_dict["expiry_starts"] = data.start_date
|
||||
if data.stop_date:
|
||||
data_dict["expiry_ends"] = data.stop_date
|
||||
# del data_dict["duty_uu_id"], data_dict["person_uu_id"]
|
||||
del data_dict["start_date"], data_dict["stop_date"], data_dict["duty_uu_id"]
|
||||
return cls.find_or_create(**data_dict)
|
||||
|
||||
__table_args__ = ({"comment": "Staff Information"},)
|
||||
|
||||
|
||||
class Employees(CrudCollection):
|
||||
|
||||
__tablename__ = "employees"
|
||||
__exclude__fields__ = []
|
||||
|
||||
staff_id = mapped_column(ForeignKey("staff.id"))
|
||||
staff_uu_id = mapped_column(String, nullable=False, comment="Staff UUID")
|
||||
people_id = mapped_column(ForeignKey("people.id"), nullable=True)
|
||||
people_uu_id = mapped_column(String, nullable=True, comment="People UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index("employees_ndx_00", people_id, staff_id, unique=True),
|
||||
{"comment": "Employee Person Information"},
|
||||
)
|
||||
|
||||
|
||||
class EmployeeHistory(CrudCollection):
|
||||
|
||||
__tablename__ = "employee_history"
|
||||
__exclude__fields__ = []
|
||||
|
||||
staff_id = mapped_column(ForeignKey("staff.id"), nullable=False, comment="Staff ID")
|
||||
staff_uu_id = mapped_column(String, nullable=False, comment="Staff UUID")
|
||||
people_id = mapped_column(
|
||||
ForeignKey("people.id"), nullable=False, comment="People ID"
|
||||
)
|
||||
people_uu_id = mapped_column(String, nullable=False, comment="People UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index("_employee_history_ndx_00", people_id, staff_id),
|
||||
{"comment": "Employee History Information"},
|
||||
)
|
||||
|
||||
|
||||
class EmployeesSalaries(CrudCollection):
|
||||
|
||||
__tablename__ = "employee_salaries"
|
||||
__exclude__fields__ = []
|
||||
|
||||
gross_salary = mapped_column(Numeric(20, 6), nullable=False, comment="Gross Salary")
|
||||
net_salary = mapped_column(Numeric(20, 6), nullable=False, comment="Net Salary")
|
||||
|
||||
people_id = mapped_column(ForeignKey("people.id"), nullable=False)
|
||||
people_uu_id = mapped_column(String, nullable=False, comment="People UUID")
|
||||
|
||||
# people: Mapped["People"] = relationship(
|
||||
# "People", back_populates="employee_salaries", foreign_keys=[people_id]
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index("_employee_salaries_ndx_00", people_id, CrudCollection.expiry_starts),
|
||||
{"comment": "Employee Salaries Information"},
|
||||
)
|
||||
|
||||
|
||||
# class Events2Employees(CrudCollection):
|
||||
#
|
||||
# __tablename__ = "events2employees"
|
||||
# __exclude__fields__ = []
|
||||
#
|
||||
# event_id = mapped_column(ForeignKey("events.id"), nullable=False)
|
||||
# employees_id = mapped_column(ForeignKey("employees.id"), nullable=False)
|
||||
#
|
||||
# __table_args__ = (
|
||||
# Index("_events2employees_ndx_00", event_id, employees_id),
|
||||
# {"comment": "Events2Employees Information"},
|
||||
# )
|
||||
266
databases/sql_models/core_mixin.py
Normal file
266
databases/sql_models/core_mixin.py
Normal file
@@ -0,0 +1,266 @@
|
||||
from sqlalchemy import (
|
||||
TIMESTAMP,
|
||||
NUMERIC,
|
||||
func,
|
||||
Identity,
|
||||
UUID,
|
||||
String,
|
||||
Integer,
|
||||
Boolean,
|
||||
SmallInteger,
|
||||
)
|
||||
|
||||
from sqlalchemy.orm import (
|
||||
Mapped,
|
||||
mapped_column,
|
||||
InstrumentedAttribute,
|
||||
)
|
||||
from sqlalchemy_mixins.session import SessionMixin
|
||||
from sqlalchemy_mixins.serialize import SerializeMixin
|
||||
from sqlalchemy_mixins.repr import ReprMixin
|
||||
from sqlalchemy_mixins.smartquery import SmartQueryMixin
|
||||
|
||||
from api_library.date_time_actions.date_functions import DateTimeLocal
|
||||
from api_objects.auth.token_objects import Credentials
|
||||
|
||||
from databases.sql_models.sql_operations import FilterAttributes
|
||||
from databases.sql_models.postgres_database import Base
|
||||
|
||||
|
||||
class CrudMixin(Base, SmartQueryMixin, SessionMixin, FilterAttributes):
|
||||
|
||||
__abstract__ = True # The model is abstract not a database table.
|
||||
__session__ = Base.session # The session to use in the model.
|
||||
__system__fields__create__ = (
|
||||
"ref_id",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"cryp_uu_id",
|
||||
"created_by",
|
||||
"created_by_id",
|
||||
"updated_by",
|
||||
"updated_by_id",
|
||||
"replication_id",
|
||||
"confirmed_by",
|
||||
"confirmed_by_id",
|
||||
"is_confirmed",
|
||||
"deleted",
|
||||
"active",
|
||||
"is_notification_send",
|
||||
"is_email_send",
|
||||
"expiry_starts",
|
||||
"expiry_ends",
|
||||
) # The system fields to use in the model.
|
||||
__system__fields__update__ = (
|
||||
"cryp_uu_id",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"created_by",
|
||||
"created_by_id",
|
||||
"confirmed_by",
|
||||
"confirmed_by_id",
|
||||
"updated_by",
|
||||
"updated_by_id",
|
||||
"replication_id",
|
||||
)
|
||||
|
||||
creds: Credentials = None # The credentials 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_ends: Mapped[TIMESTAMP] = mapped_column(TIMESTAMP, default="2099-12-31", server_default="2099-12-31")
|
||||
|
||||
@classmethod
|
||||
def extract_system_fields(cls, filter_kwargs: dict, create: bool = True):
|
||||
"""
|
||||
Extracts the system fields from the given attributes.
|
||||
"""
|
||||
system_fields = filter_kwargs.copy()
|
||||
extract_fields = cls.__system__fields__create__ if create else cls.__system__fields__update__
|
||||
for field in extract_fields:
|
||||
system_fields.pop(field, None)
|
||||
return system_fields
|
||||
|
||||
@classmethod
|
||||
def find_or_create(cls, **kwargs):
|
||||
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.
|
||||
If found, sets is_found to True, otherwise False.
|
||||
is_found can be used to check if the record was found or created.
|
||||
"""
|
||||
check_kwargs = cls.extract_system_fields(kwargs)
|
||||
cls.pre_query = cls.query.filter(
|
||||
system_arrow.get(cls.expiry_ends).date() < system_arrow.now().date()
|
||||
)
|
||||
already_record = cls.filter_by_one(**check_kwargs)
|
||||
if already_record := already_record.data:
|
||||
if already_record.is_deleted:
|
||||
cls.raise_http_exception(
|
||||
status_code="HTTP_406_NOT_ACCEPTABLE",
|
||||
error_case="DeletedRecord",
|
||||
data=check_kwargs,
|
||||
message="Record exits but is deleted. Contact with authorized user",
|
||||
)
|
||||
elif already_record.is_confirmed:
|
||||
cls.raise_http_exception(
|
||||
status_code="HTTP_406_NOT_ACCEPTABLE",
|
||||
error_case="IsNotConfirmed",
|
||||
data=check_kwargs,
|
||||
message="Record exits but is not confirmed. Contact with authorized user",
|
||||
)
|
||||
cls.raise_http_exception(
|
||||
status_code="HTTP_406_NOT_ACCEPTABLE",
|
||||
error_case="AlreadyExists",
|
||||
data=check_kwargs,
|
||||
message="Record already exits. Refresh data and try again",
|
||||
)
|
||||
created_record = cls()
|
||||
for key, value in check_kwargs.items():
|
||||
setattr(created_record, key, value)
|
||||
created_record.flush()
|
||||
cls.created_by_id = cls.creds.person_id
|
||||
cls.created_by = cls.creds.person_name
|
||||
return created_record
|
||||
|
||||
@classmethod
|
||||
def iterate_over_variables(cls, val, key):
|
||||
key_ = cls.__annotations__.get(key, None)
|
||||
if val is None or key_ is None:
|
||||
return None
|
||||
elif key_ == Mapped[Identity]:
|
||||
return None
|
||||
elif key_ == Mapped[bool]:
|
||||
return bool(val)
|
||||
elif key_ == Mapped[float] or key_ == Mapped[NUMERIC]:
|
||||
return float(val)
|
||||
elif key_ == Mapped[int]:
|
||||
return int(val)
|
||||
elif key_ == Mapped[TIMESTAMP]:
|
||||
return str(cls.client_arrow.get(val).format("DD-MM-YYYY HH:mm:ss"))
|
||||
return str(val)
|
||||
|
||||
def update(self, **kwargs):
|
||||
"""Updates the record with the given attributes."""
|
||||
is_confirmed_argument = kwargs.get("is_confirmed", None)
|
||||
if is_confirmed_argument and not len(kwargs) == 1:
|
||||
self.raise_http_exception(
|
||||
status_code="HTTP_406_NOT_ACCEPTABLE",
|
||||
error_case="ConfirmError",
|
||||
data=kwargs,
|
||||
message="Confirm field can not be updated with other fields",
|
||||
)
|
||||
check_kwargs = self.extract_system_fields(kwargs, create=False)
|
||||
for key, value in check_kwargs.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
if is_confirmed_argument:
|
||||
self.confirmed_by_id = self.creds.person_id
|
||||
self.confirmed_by = self.creds.person_name
|
||||
else:
|
||||
self.updated_by_id = self.creds.person_id
|
||||
self.updated_by = self.creds.person_name
|
||||
self.flush()
|
||||
return self
|
||||
|
||||
def get_dict(self, exclude: list = None, include: list = None, include_joins: list = None):
|
||||
return_dict = {}
|
||||
if exclude:
|
||||
exclude.extend(list(set(self.__exclude__fields__).difference(exclude)))
|
||||
else:
|
||||
exclude = self.__exclude__fields__
|
||||
include = include or []
|
||||
if include:
|
||||
include.extend(["uu_id", "active"])
|
||||
include = list(set(include).difference(self.__exclude__fields__))
|
||||
for key, val in self.to_dict().items():
|
||||
if key in include:
|
||||
if value_of_database := self.iterate_over_variables(val, key):
|
||||
return_dict[key] = value_of_database
|
||||
else:
|
||||
exclude.extend(["is_confirmed", "deleted", "cryp_uu_id"])
|
||||
for key, val in self.to_dict().items():
|
||||
if key not in exclude:
|
||||
if value_of_database := self.iterate_over_variables(val, key):
|
||||
return_dict[key] = value_of_database
|
||||
|
||||
all_arguments = [
|
||||
record
|
||||
for record in self.__class__.__dict__
|
||||
if "_" not in record[0] and "id" not in record[-2:]
|
||||
]
|
||||
include_joins = include_joins or []
|
||||
for all_argument in all_arguments:
|
||||
column = getattr(self.__class__, all_argument)
|
||||
is_populate = isinstance(column, InstrumentedAttribute) and not hasattr(
|
||||
column, "foreign_keys"
|
||||
)
|
||||
if is_populate and all_argument in include_joins or []:
|
||||
populate_arg = getattr(self, all_argument, None)
|
||||
if isinstance(populate_arg, list):
|
||||
return_dict[all_argument] = [
|
||||
arg.get_dict() if arg else [] for arg in populate_arg
|
||||
]
|
||||
elif getattr(populate_arg, "get_dict", None):
|
||||
return_dict[all_argument] = (
|
||||
populate_arg.get_dict() if populate_arg else []
|
||||
)
|
||||
return return_dict
|
||||
|
||||
|
||||
class BaseMixin(CrudMixin, ReprMixin, SerializeMixin):
|
||||
|
||||
__abstract__ = True
|
||||
|
||||
|
||||
class BaseCollection(CrudMixin, BaseMixin):
|
||||
|
||||
__abstract__ = True
|
||||
__repr__ = ReprMixin.__repr__
|
||||
|
||||
id: Mapped[Identity] = mapped_column(primary_key=True)
|
||||
|
||||
|
||||
class CrudCollection(CrudMixin, BaseMixin, SmartQueryMixin):
|
||||
|
||||
__abstract__ = True
|
||||
__repr__ = ReprMixin.__repr__
|
||||
|
||||
id: Mapped[Identity] = mapped_column(primary_key=True)
|
||||
uu_id: Mapped[UUID] = mapped_column(
|
||||
UUID, server_default=func.text("gen_random_uuid()"), index=True, unique=True
|
||||
)
|
||||
|
||||
ref_id: Mapped[UUID] = mapped_column(String(100), nullable=True, index=True)
|
||||
created_at: Mapped[TIMESTAMP] = mapped_column(
|
||||
"created_at",
|
||||
TIMESTAMP(timezone=True),
|
||||
server_default=func.now(),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
|
||||
updated_at: Mapped[TIMESTAMP] = mapped_column(
|
||||
"updated_at",
|
||||
TIMESTAMP(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
cryp_uu_id: Mapped[UUID] = mapped_column(String, nullable=True, index=True)
|
||||
|
||||
created_by: Mapped[str] = mapped_column(String, nullable=True)
|
||||
created_by_id: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
updated_by: Mapped[str] = mapped_column(String, nullable=True)
|
||||
updated_by_id: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
|
||||
confirmed_by: Mapped[str] = mapped_column(String, nullable=True)
|
||||
confirmed_by_id: Mapped[int] = mapped_column(Integer, nullable=True)
|
||||
is_confirmed: Mapped[bool] = mapped_column(Boolean, server_default="0")
|
||||
|
||||
replication_id: Mapped[int] = mapped_column(SmallInteger, server_default="0")
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, server_default="0")
|
||||
active: Mapped[bool] = mapped_column(Boolean, server_default="1")
|
||||
is_notification_send: Mapped[bool] = mapped_column(Boolean, server_default="0")
|
||||
is_email_send: Mapped[bool] = mapped_column(Boolean, server_default="0")
|
||||
255
databases/sql_models/event/event.py
Normal file
255
databases/sql_models/event/event.py
Normal file
@@ -0,0 +1,255 @@
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
from sqlalchemy import (
|
||||
String,
|
||||
ForeignKey,
|
||||
Numeric,
|
||||
SmallInteger,
|
||||
Boolean,
|
||||
Integer,
|
||||
Index,
|
||||
)
|
||||
from sqlalchemy.orm import mapped_column
|
||||
|
||||
|
||||
class Events(CrudCollection):
|
||||
"""
|
||||
Events class based on declarative_base and BaseMixin via session
|
||||
If Events2Occupants and Events2Employees are not found for user request, response 401 Unauthorized
|
||||
"""
|
||||
|
||||
__tablename__ = "events"
|
||||
__exclude__fields__ = []
|
||||
|
||||
event_type = mapped_column(String, nullable=False, comment="default")
|
||||
function_code = mapped_column(String, nullable=False, comment="function code")
|
||||
function_class = mapped_column(String, nullable=False, comment="class name")
|
||||
|
||||
# name = mapped_column(String, nullable=True) # form or page title
|
||||
description = mapped_column(String, server_default="") # form or page description
|
||||
property_description = mapped_column(String, server_default="")
|
||||
|
||||
marketing_layer = mapped_column(SmallInteger, server_default="3")
|
||||
cost = mapped_column(Numeric(20, 2), server_default="0.00")
|
||||
unit_price = mapped_column(Numeric(20, 2), server_default="0.00")
|
||||
|
||||
endpoint_id = mapped_column(ForeignKey("endpoint_restriction.id"), nullable=True)
|
||||
endpoint_uu_id = mapped_column(String, nullable=True, comment="Endpoint UUID")
|
||||
|
||||
__table_args__ = ({"comment": "Events Information"},)
|
||||
|
||||
|
||||
class Modules(CrudCollection):
|
||||
"""
|
||||
Modules class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "modules"
|
||||
__exclude__fields__ = []
|
||||
|
||||
module_name = mapped_column(String, nullable=False, comment="Module Name")
|
||||
module_description = mapped_column(String, server_default="")
|
||||
module_code = mapped_column(String, nullable=False, comment="Module Code")
|
||||
module_layer = mapped_column(Integer, nullable=False, comment="Module Layer")
|
||||
is_default_module = mapped_column(Boolean, server_default="0")
|
||||
|
||||
__table_args__ = ({"comment": "Modules Information"},)
|
||||
|
||||
|
||||
class Services(CrudCollection):
|
||||
"""
|
||||
Services class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "services"
|
||||
__exclude__fields__ = []
|
||||
|
||||
module_id = mapped_column(ForeignKey("modules.id"), nullable=False)
|
||||
module_uu_id = mapped_column(String, nullable=False, comment="Module UUID")
|
||||
service_name = mapped_column(String, nullable=False, comment="Service Name")
|
||||
service_description = mapped_column(String, server_default="")
|
||||
service_code = mapped_column(String, nullable=True, comment="Service Code")
|
||||
related_responsibility = mapped_column(String, server_default="")
|
||||
|
||||
__table_args__ = ({"comment": "Services Information"},)
|
||||
|
||||
|
||||
class Service2Events(CrudCollection):
|
||||
"""
|
||||
Service2Actions class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "services2events"
|
||||
__exclude__fields__ = []
|
||||
|
||||
service_id = mapped_column(ForeignKey("services.id"), nullable=False)
|
||||
service_uu_id = mapped_column(String, nullable=False, comment="Service UUID")
|
||||
event_id = mapped_column(ForeignKey("events.id"), nullable=False)
|
||||
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
|
||||
|
||||
__table_args__ = ({"comment": "Service2Events Information"},)
|
||||
|
||||
|
||||
class Event2Employee(CrudCollection):
|
||||
"""
|
||||
Employee2Event class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "event2employee"
|
||||
__exclude__fields__ = []
|
||||
|
||||
employee_id = mapped_column(ForeignKey("employees.id"), nullable=False)
|
||||
employee_uu_id = mapped_column(String, nullable=False, comment="Employee UUID")
|
||||
event_id = mapped_column(ForeignKey("events.id"), nullable=False)
|
||||
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index("event2employee_employee_to_event", employee_id, event_id, unique=True),
|
||||
{"comment": "Employee to Event Information"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_event_id_by_employee_id(cls, employee_id) -> (list, list):
|
||||
active_events = cls.filter_active(cls.employee_id == employee_id)
|
||||
active_events_id = [event.event_id for event in active_events.data]
|
||||
active_events = Events.filter_active(Events.id.in_(active_events_id))
|
||||
active_events_uu_id = [str(event.uu_id) for event in active_events.data]
|
||||
return active_events_id, active_events_uu_id
|
||||
|
||||
|
||||
class Event2Occupant(CrudCollection):
|
||||
"""
|
||||
Occupant2Event class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "event2occupant"
|
||||
__exclude__fields__ = []
|
||||
|
||||
build_living_space_id = mapped_column(
|
||||
ForeignKey("build_living_space.id"), nullable=False
|
||||
)
|
||||
build_living_space_uu_id = mapped_column(
|
||||
String, nullable=False, comment="Build Living Space UUID"
|
||||
)
|
||||
event_id = mapped_column(ForeignKey("events.id"), nullable=False)
|
||||
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"event2occupant_bind_event_to_occupant",
|
||||
build_living_space_id,
|
||||
event_id,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Occupant2Event Information"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_event_id_by_build_living_space_id(
|
||||
cls, build_living_space_id
|
||||
) -> (list, list):
|
||||
active_events = cls.filter_by_active(
|
||||
build_living_space_id=build_living_space_id
|
||||
)
|
||||
active_events_id = [event.event_id for event in active_events.data]
|
||||
active_events = Events.filter_active(Events.id.in_(active_events_id))
|
||||
active_events_uu_id = [str(event.uu_id) for event in active_events.data]
|
||||
return active_events_id, active_events_uu_id
|
||||
|
||||
|
||||
# Delete later code
|
||||
class ModulePrice(CrudCollection):
|
||||
"""
|
||||
ModulePrice class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "module_price"
|
||||
__exclude__fields__ = []
|
||||
|
||||
campaign_code = mapped_column(String, nullable=False, comment="Campaign Code")
|
||||
module_id = mapped_column(ForeignKey("modules.id"), nullable=False)
|
||||
module_uu_id = mapped_column(String, nullable=False, comment="Module UUID")
|
||||
service_id = mapped_column(ForeignKey("services.id"), nullable=False)
|
||||
service_uu_id = mapped_column(String, nullable=False, comment="Service UUID")
|
||||
event_id = mapped_column(ForeignKey("events.id"), nullable=False)
|
||||
event_uu_id = mapped_column(String, nullable=False, comment="Event UUID")
|
||||
is_counted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22
|
||||
discounted_price = mapped_column(
|
||||
Numeric(20, 2), server_default="0.00"
|
||||
) # Normal: 78.00 TL
|
||||
calculated_price = mapped_column(
|
||||
Numeric(20, 2), server_default="0.00"
|
||||
) # sana düz 75.00 TL yapar
|
||||
|
||||
__table_args__ = ({"comment": "ModulePrice Information"},)
|
||||
|
||||
|
||||
#
|
||||
# class Modules2Occupant(CrudCollection):
|
||||
# """
|
||||
# ModulesOccupantPrices class based on declarative_base and BaseMixin via session
|
||||
# discounted_price - calculated_price = Pazarlamaya gider yazılır 3 TL
|
||||
# """
|
||||
#
|
||||
# __tablename__ = "modules2_occupant"
|
||||
#
|
||||
#
|
||||
# discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22
|
||||
# discounted_price = mapped_column(
|
||||
# Numeric(20, 2), server_default="0.00"
|
||||
# ) # Normal: 78.00 TL
|
||||
# calculated_price = mapped_column(
|
||||
# Numeric(20, 2), server_default="0.00"
|
||||
# ) # sana düz 75.00 TL yapar
|
||||
#
|
||||
# service_id = mapped_column(ForeignKey("services.id"), nullable=False)
|
||||
# build_living_space_id = mapped_column(
|
||||
# ForeignKey("build_living_space.id"), nullable=False, index=True
|
||||
# )
|
||||
#
|
||||
# __table_args__ = ({"comment": "ModulesOccupantPrices Information"},)
|
||||
#
|
||||
#
|
||||
# class Modules2Employee(CrudCollection):
|
||||
# """
|
||||
# Modules2EmployeeServices class based on declarative_base and BaseMixin via session
|
||||
# """
|
||||
#
|
||||
# __tablename__ = "modules2_employee"
|
||||
#
|
||||
# discounted_percentage = mapped_column(Numeric(6, 2), server_default="0.00") # %22
|
||||
# discounted_price = mapped_column(
|
||||
# Numeric(20, 2), server_default="0.00"
|
||||
# ) # Normal: 78.00 TL
|
||||
# calculated_price = mapped_column(
|
||||
# Numeric(20, 2), server_default="0.00"
|
||||
# ) # sana düz 75.00 TL yapar
|
||||
#
|
||||
# service_id = mapped_column(ForeignKey("services.id"), nullable=False)
|
||||
# employee_id = mapped_column(ForeignKey("employees.id"), nullable=False)
|
||||
#
|
||||
# __table_args__ = ({"comment": "Modules2EmployeeServices Information"},)
|
||||
# class Actions(CrudCollection):
|
||||
# """
|
||||
# Actions class based on declarative_base and BaseMixin via session
|
||||
# """
|
||||
#
|
||||
# __tablename__ = "actions"
|
||||
# __exclude__fields__ = []
|
||||
#
|
||||
# action_table = mapped_column(String, nullable=False, comment="Action Table")
|
||||
# action_type = mapped_column(String, nullable=False, comment="Action Type")
|
||||
# action_description = mapped_column(String, server_default="")
|
||||
# action_code = mapped_column(String, nullable=False, comment="Action Code")
|
||||
# endpoint_id = mapped_column(ForeignKey("endpoint_restriction.id"), nullable=True)
|
||||
# endpoint_uu_id = mapped_column(String, nullable=True, comment="Endpoint UUID")
|
||||
#
|
||||
# @property
|
||||
# def action_name(self):
|
||||
# return f"{self.action_table} {self.action_type}"
|
||||
#
|
||||
# @property
|
||||
# def total_cost(self):
|
||||
# return self.cost * self.unit_price
|
||||
#
|
||||
# __table_args__ = ({"comment": "Actions Information"},)
|
||||
972
databases/sql_models/identity/identity.py
Normal file
972
databases/sql_models/identity/identity.py
Normal file
@@ -0,0 +1,972 @@
|
||||
from api_library.date_time_actions.date_functions import DateTimeLocal
|
||||
from api_configs import Auth, ApiStatic, RelationAccess
|
||||
|
||||
from datetime import timedelta
|
||||
from fastapi import HTTPException
|
||||
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
from application.shared_classes import SelectAction, SelectActionWithEmployee
|
||||
|
||||
from sqlalchemy import (
|
||||
String,
|
||||
Boolean,
|
||||
TIMESTAMP,
|
||||
ForeignKey,
|
||||
func,
|
||||
Numeric,
|
||||
Index,
|
||||
BigInteger,
|
||||
Integer,
|
||||
Text,
|
||||
or_,
|
||||
)
|
||||
from sqlalchemy.orm import mapped_column, relationship
|
||||
|
||||
from validations import InsertUsers, InsertPerson
|
||||
from extensions.auth.login import UserLoginModule
|
||||
|
||||
|
||||
class UsersTokens(CrudCollection):
|
||||
|
||||
__tablename__ = "users_tokens"
|
||||
__exclude__fields__ = []
|
||||
|
||||
user_id = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
|
||||
token_type = mapped_column(String(16), server_default="RememberMe")
|
||||
token = mapped_column(String, server_default="")
|
||||
domain = mapped_column(String, server_default="")
|
||||
expires_at = mapped_column(TIMESTAMP, default=str(DateTimeLocal.shift(days=3)))
|
||||
|
||||
# users = relationship("Users", back_populates="tokens", foreign_keys=[user_id])
|
||||
|
||||
|
||||
class Users(CrudCollection, UserLoginModule, SelectAction):
|
||||
"""
|
||||
Application User frame to connect to API with assigned token-based HTTP connection
|
||||
"""
|
||||
|
||||
__tablename__ = "users"
|
||||
__exclude__fields__ = [
|
||||
"hash_password",
|
||||
"password_token",
|
||||
"expiry_begins",
|
||||
"related_company",
|
||||
]
|
||||
|
||||
user_tag = mapped_column(
|
||||
String(64), server_default="", comment="Unique tag for the user", index=True
|
||||
)
|
||||
email = mapped_column(
|
||||
String(128), server_default="", comment="Email address of the user", index=True
|
||||
)
|
||||
phone_number = mapped_column(
|
||||
String, server_default="", comment="Phone number of the user", index=True
|
||||
)
|
||||
via = mapped_column(
|
||||
String,
|
||||
server_default="111",
|
||||
comment="Email 1/ Phone 2/ User Tag 3 All 111 Only 100",
|
||||
)
|
||||
|
||||
avatar = mapped_column(String, server_default="", comment="Avatar URL for the user")
|
||||
hash_password = mapped_column(
|
||||
String(256), server_default="", comment="Hashed password for security"
|
||||
)
|
||||
password_token = mapped_column(
|
||||
String(256), server_default="", comment="Token for password reset"
|
||||
)
|
||||
remember_me = mapped_column(
|
||||
Boolean, server_default="0", comment="Flag to remember user login"
|
||||
)
|
||||
|
||||
password_expires_day = mapped_column(
|
||||
"expires_day",
|
||||
String,
|
||||
server_default=str(Auth.PASSWORD_EXPIRE_DAY),
|
||||
comment="Password expires in days",
|
||||
)
|
||||
password_expiry_begins = mapped_column(
|
||||
"expiry_begins",
|
||||
TIMESTAMP,
|
||||
server_default=func.now(),
|
||||
comment="Timestamp when password expiry begins",
|
||||
)
|
||||
related_company = mapped_column(String, comment="Related Company UUID")
|
||||
|
||||
person_id = mapped_column(
|
||||
ForeignKey("people.id"), nullable=False, comment="Foreign key to person table"
|
||||
)
|
||||
person_uu_id = mapped_column(
|
||||
String, server_default="", comment="Person UUID", index=True
|
||||
)
|
||||
person = relationship("People", back_populates="user", foreign_keys=[person_id])
|
||||
|
||||
@property
|
||||
def is_occupant(self):
|
||||
return not str(self.email).split("@")[1] == Auth.ACCESS_EMAIL_EXT
|
||||
|
||||
@property
|
||||
def password_expiry_ends(self):
|
||||
"""Calculates the expiry end date based on expiry begins and expires day"""
|
||||
return self.password_expiry_begins + timedelta(
|
||||
days=int(
|
||||
"".join(
|
||||
[
|
||||
_
|
||||
for _ in str(self.password_expires_day).split(",")[0]
|
||||
if _.isdigit()
|
||||
]
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
def is_super_user(self):
|
||||
"""Checks if the user is a superuser based on priority code"""
|
||||
return getattr(self.priority, "priority_code", 0) == 78
|
||||
|
||||
@property
|
||||
def is_user(self):
|
||||
"""Checks if the user is a regular user based on priority code"""
|
||||
return getattr(self.priority, "priority_code", 0) == 0
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, create_user: InsertUsers):
|
||||
|
||||
found_person = People.find_one(uu_id=create_user.people_uu_id)
|
||||
if not found_person:
|
||||
raise HTTPException(status_code=400, detail="Person not found.")
|
||||
if (
|
||||
not any(i in str(create_user.email) for i in ["@", "."])
|
||||
and not len(str(create_user.phone_number)) >= 10
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Please enter at least one valid email or phone number.",
|
||||
)
|
||||
if not create_user.avatar:
|
||||
create_user.avatar = ApiStatic.PLACEHOLDER
|
||||
create_dict = create_user.model_dump()
|
||||
del create_dict["people_uu_id"]
|
||||
create_dict["person_id"] = found_person.id
|
||||
create_dict["person_uu_id"] = str(found_person.uu_id)
|
||||
created_user = cls.find_or_create(**create_dict)
|
||||
created_user.reset_password_token()
|
||||
return created_user
|
||||
|
||||
@classmethod
|
||||
def created_creds(cls, create_creds: bool = True):
|
||||
person_object = People.find_one(id=cls.person_id)
|
||||
if create_creds:
|
||||
return {
|
||||
"created_by_id": person_object.id,
|
||||
"created_by": str(person_object.firstname)
|
||||
+ " "
|
||||
+ str(person_object.surname),
|
||||
}
|
||||
return {
|
||||
"updated_by_id": person_object.id,
|
||||
"updated_by": str(person_object.firstname)
|
||||
+ " "
|
||||
+ str(person_object.surname),
|
||||
}
|
||||
|
||||
#
|
||||
# def prepare_employee_token_object(self, selected_duty_uu_id):
|
||||
# from database_sql_models import (
|
||||
# Companies,
|
||||
# Employees,
|
||||
# Duties,
|
||||
# Departments,
|
||||
# )
|
||||
# found_person = People.find_one(id=self.person_id)
|
||||
# found_employee = Employees.find_one(people_id=found_person.id)
|
||||
# found_duty = Duties.find_one(uu_id=selected_duty_uu_id)
|
||||
# found_department = Departments.find_one(id=found_duty.department_id)
|
||||
# found_company = Companies.find_one(id=found_department.company_id)
|
||||
# return {
|
||||
# "people": {
|
||||
# "people_id": found_person.id,
|
||||
# "people_uu_id": found_person.uu_id.__str__(),
|
||||
# },
|
||||
# "user": {
|
||||
# "user_id": self.id,
|
||||
# "user_uu_id": self.uu_id.__str__(),
|
||||
# },
|
||||
# "duty": {
|
||||
# "duty_id": found_duty.id,
|
||||
# "duty_uu_id": found_duty.uu_id.__str__()
|
||||
# },
|
||||
# "employee": {
|
||||
# "employee_id": found_employee.id,
|
||||
# "employee_uu_id": found_employee.uu_id.__str__(),
|
||||
# "people_id": found_employee.people_id,
|
||||
# },
|
||||
# "department": {
|
||||
# "department_id": found_department.id,
|
||||
# "department_uu_id": found_department.uu_id.__str__(),
|
||||
# },
|
||||
# "company": {
|
||||
# "company_id": found_company.id,
|
||||
# "company_uu_id": found_company.uu_id.__str__()
|
||||
# },
|
||||
# }
|
||||
|
||||
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_employees = Employees.filter_by_active(
|
||||
people_id=found_person.id, is_confirmed=True
|
||||
)
|
||||
found_duties = Duties.filter_active(
|
||||
Duties.is_confirmed == True,
|
||||
Duties.id.in_(
|
||||
list(found_employee.duty_id for found_employee in found_employees.data)
|
||||
),
|
||||
)
|
||||
if not found_employees.count:
|
||||
raise HTTPException(
|
||||
status_code=401,
|
||||
detail={
|
||||
"message": "Person has no confirmed duty. No employee match please register "
|
||||
"your super admin",
|
||||
"completed": False,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"duty_list": [
|
||||
{
|
||||
"duty_id": duty.id,
|
||||
"duty_uu_id": duty.uu_id.__str__(),
|
||||
"duty_code": duty.duty_code,
|
||||
"duty_name": duty.duty_name,
|
||||
"duty_description": duty.duty_description,
|
||||
}
|
||||
for duty in found_duties.data
|
||||
],
|
||||
}
|
||||
|
||||
def get_main_domain_and_other_domains(self, get_main_domain: bool = True):
|
||||
from databases import MongoQueryIdentity
|
||||
|
||||
query_engine = MongoQueryIdentity(company_uuid=self.related_company)
|
||||
domain_via_user = query_engine.get_domain_via_user(user_uu_id=str(self.uu_id))
|
||||
if get_main_domain:
|
||||
return domain_via_user.get("main_domain")
|
||||
return domain_via_user.get("other_domains_list")
|
||||
|
||||
|
||||
class RelationshipDutyPeople(CrudCollection):
|
||||
|
||||
__tablename__ = "relationship_duty_people"
|
||||
__exclude__fields__ = []
|
||||
__access_by__ = RelationAccess.SuperAccessList
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"), nullable=False) # 1, 2, 3
|
||||
duties_id = mapped_column(
|
||||
ForeignKey("duties.id"), nullable=False
|
||||
) # duty -> (n)person Evyos LTD
|
||||
member_id = mapped_column(ForeignKey("people.id"), nullable=False) # 2, 3, 4
|
||||
|
||||
relationship_type = mapped_column(
|
||||
String, nullable=True, server_default="Employee"
|
||||
) # Commercial
|
||||
show_only = mapped_column(Boolean, server_default="0")
|
||||
|
||||
# related_company: Mapped[List["Company"]] = relationship(
|
||||
# "Company",
|
||||
# back_populates="related_companies",
|
||||
# foreign_keys=[related_company_id],
|
||||
# )
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"person_relationship_ndx_01",
|
||||
company_id,
|
||||
duties_id,
|
||||
member_id,
|
||||
relationship_type,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Person Relationship Information"},
|
||||
)
|
||||
|
||||
|
||||
class People(CrudCollection, SelectAction):
|
||||
"""
|
||||
People that are related to users in the application
|
||||
"""
|
||||
|
||||
__tablename__ = "people"
|
||||
__exclude__fields__ = []
|
||||
__many__table__ = RelationshipDutyPeople
|
||||
__encrypt_list__ = [
|
||||
"father_name",
|
||||
"mother_name",
|
||||
"country_code",
|
||||
"national_identity_id",
|
||||
"birth_place",
|
||||
"birth_date",
|
||||
"tax_no",
|
||||
]
|
||||
|
||||
firstname = mapped_column(
|
||||
String, nullable=False, comment="First name of the person"
|
||||
)
|
||||
surname = mapped_column(String(24), nullable=False, comment="Surname of the person")
|
||||
middle_name = mapped_column(
|
||||
String, server_default="", comment="Middle name of the person"
|
||||
)
|
||||
sex_code = mapped_column(
|
||||
String(1), nullable=False, comment="Sex code of the person (e.g., M/F)"
|
||||
)
|
||||
person_ref = mapped_column(
|
||||
String, server_default="", comment="Reference ID for the person"
|
||||
)
|
||||
person_tag = mapped_column(
|
||||
String, server_default="", comment="Unique tag for the person"
|
||||
)
|
||||
|
||||
# ENCRYPT DATA
|
||||
father_name = mapped_column(
|
||||
String, server_default="", comment="Father's name of the person"
|
||||
)
|
||||
mother_name = mapped_column(
|
||||
String, server_default="", comment="Mother's name of the person"
|
||||
)
|
||||
country_code = mapped_column(
|
||||
String(4), server_default="TR", comment="Country code of the person"
|
||||
)
|
||||
national_identity_id = mapped_column(
|
||||
String, server_default="", comment="National identity ID of the person"
|
||||
)
|
||||
birth_place = mapped_column(
|
||||
String, server_default="", comment="Birth place of the person"
|
||||
)
|
||||
birth_date = mapped_column(
|
||||
TIMESTAMP, server_default="1900-01-01", comment="Birth date of the person"
|
||||
)
|
||||
tax_no = mapped_column(
|
||||
String, server_default="", comment="Tax number of the person"
|
||||
)
|
||||
# ENCRYPT DATA
|
||||
user = relationship(
|
||||
"Users", back_populates="person", foreign_keys="Users.person_id"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"person_ndx_001",
|
||||
national_identity_id,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Person Information"},
|
||||
)
|
||||
|
||||
|
||||
@property
|
||||
def full_name(self):
|
||||
return f"{self.firstname} {self.middle_name} {self.surname}"
|
||||
|
||||
@classmethod
|
||||
def create_action(cls, data: InsertPerson, token):
|
||||
from database_sql_models import Duties
|
||||
|
||||
token_duties_id, token_company_id = (
|
||||
token.selected_company.duty_id,
|
||||
token.selected_company.company_id,
|
||||
)
|
||||
bulk_duty = Duties.get_bulk_duties_of_a_company(company_id=token_company_id)
|
||||
|
||||
if str(data.country_code) == "TR":
|
||||
if not len(data.national_identity_id) == 11:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Please enter a valid national identity number.",
|
||||
)
|
||||
if data.tax_no and not len(str(data.tax_no)) == 10:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Please enter a valid tax number.",
|
||||
)
|
||||
|
||||
create_dict = data.model_dump()
|
||||
create_dict["firstname"] = str(create_dict["firstname"]).capitalize()
|
||||
create_dict["middle_name"] = str(create_dict["middle_name"]).capitalize()
|
||||
create_dict["surname"] = str(create_dict["surname"]).upper()
|
||||
create_dict["birth_place"] = str(create_dict["birth_place"]).upper()
|
||||
created_people = cls.find_or_create(**create_dict)
|
||||
if not created_people.is_found:
|
||||
RelationshipDutyPeople.find_or_create(
|
||||
company_id=token.selected_company.company_id,
|
||||
duties_id=bulk_duty.id,
|
||||
member_id=created_people.id,
|
||||
)
|
||||
return created_people
|
||||
|
||||
|
||||
class RelationshipEmployee2PostCode(CrudCollection):
|
||||
"""
|
||||
Build2EmployeeRelationship class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "relationship_employee2postcode"
|
||||
__exclude__fields__ = []
|
||||
__include__fields__ = []
|
||||
|
||||
company_id = mapped_column(ForeignKey("companies.id"), nullable=True) # 1, 2, 3
|
||||
employee_id = mapped_column(ForeignKey("employees.id"), nullable=False)
|
||||
member_id = mapped_column(ForeignKey("address_postcode.id"), nullable=False)
|
||||
|
||||
relationship_type = mapped_column(
|
||||
String, nullable=True, server_default="Employee"
|
||||
) # Commercial
|
||||
show_only = mapped_column(Boolean, server_default="0")
|
||||
|
||||
__table_args__ = ({"comment": "Build2Employee Relationship Information"},)
|
||||
|
||||
|
||||
class AddressPostcode(CrudCollection, SelectActionWithEmployee):
|
||||
"""
|
||||
Postcode class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_postcode"
|
||||
__exclude__fields__ = []
|
||||
__access_by__ = []
|
||||
__many__table__ = RelationshipEmployee2PostCode
|
||||
|
||||
street_id = mapped_column(ForeignKey("address_street.id"))
|
||||
street_uu_id = mapped_column(String, server_default="", comment="Street UUID")
|
||||
postcode = mapped_column(String(32), nullable=False, comment="Postcode")
|
||||
|
||||
__table_args__ = ({"comment": "Postcode Information"},)
|
||||
|
||||
|
||||
class Addresses(CrudCollection):
|
||||
"""
|
||||
Address class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "addresses"
|
||||
__exclude__fields__ = []
|
||||
|
||||
build_number = mapped_column(String(24), nullable=False, comment="Build Number")
|
||||
door_number = mapped_column(String(24), nullable=True, comment="Door Number")
|
||||
floor_number = mapped_column(String(24), nullable=True, comment="Floor Number")
|
||||
|
||||
comment_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")
|
||||
|
||||
latitude = mapped_column(Numeric(20, 12), server_default="0")
|
||||
longitude = mapped_column(Numeric(20, 12), server_default="0")
|
||||
|
||||
street_id = mapped_column(ForeignKey("address_street.id"), nullable=False)
|
||||
street_uu_id = mapped_column(String, server_default="", comment="Street UUID")
|
||||
|
||||
@classmethod
|
||||
def list_via_employee(cls, token_dict, filter_expr):
|
||||
post_code_list = RelationshipEmployee2PostCode.filter_active(
|
||||
RelationshipEmployee2PostCode.employee_id
|
||||
== token_dict.selected_company.employee_id,
|
||||
).data
|
||||
post_code_id_list = [post_code.member_id for post_code in post_code_list]
|
||||
if not post_code_id_list:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="User has no post code registered. User can not list addresses.",
|
||||
)
|
||||
cls.pre_query = Addresses.filter_active(
|
||||
cls.post_code_id.in_(post_code_id_list)
|
||||
).query
|
||||
return cls.filter_active(*filter_expr)
|
||||
|
||||
# buildings: Mapped["Build"] = relationship(
|
||||
# "Build", back_populates="addresses", foreign_keys="Build.address_id"
|
||||
# )
|
||||
# site: Mapped["BuildSites"] = relationship(
|
||||
# "BuildSites", back_populates="addresses", foreign_keys="BuildSites.address_id"
|
||||
# )
|
||||
# official_companies: Mapped["Companies"] = relationship(
|
||||
# "Company",
|
||||
# back_populates="official_address",
|
||||
# foreign_keys="Company.official_address_id",
|
||||
# )
|
||||
|
||||
# @classmethod
|
||||
# def create_action(cls, request, create_address: InsertAddress):
|
||||
# from services.redis.auth_actions.token import parse_token_object_to_dict
|
||||
#
|
||||
# token_dict = parse_token_object_to_dict(request=request)
|
||||
# data_dict = create_address.model_dump()
|
||||
# post_code = AddressPostcode.find_one(uu_id=create_address.post_code_uu_id)
|
||||
# if not post_code:
|
||||
# raise HTTPException(
|
||||
# status_code=404,
|
||||
# detail="Post code not found.",
|
||||
# )
|
||||
# if Employee2AddressRelationship.post_code_id.find_one(
|
||||
# employee_id=token_dict.selected_company.employee_id,
|
||||
# post_code_id=post_code.id,
|
||||
# ):
|
||||
# data_dict["post_code_id"] = post_code.id
|
||||
# del data_dict["post_code_uu_id"]
|
||||
# return cls.find_or_create(**create_address.model_dump())
|
||||
# raise HTTPException(
|
||||
# status_code=401,
|
||||
# detail=f"User is not qualified to create address at this post code {post_code.postcode}",
|
||||
# )
|
||||
|
||||
# __table_args__ = (
|
||||
# Index("_address_ndx_00", country_code, b_state, city, district),
|
||||
# {"comment": "Address Information"},
|
||||
# )
|
||||
|
||||
|
||||
class AddressGeographicLocations(CrudCollection):
|
||||
"""
|
||||
Country class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_geographic_locations"
|
||||
__exclude__fields__ = []
|
||||
|
||||
geo_table = mapped_column(String, nullable=False, comment="Address Table Name")
|
||||
geo_id = mapped_column(Integer, nullable=False, comment="Address Table ID")
|
||||
geo_name = mapped_column(String, nullable=False, comment="Geographic Location Name")
|
||||
geo_latitude = mapped_column(
|
||||
Numeric(20, 6), server_default="0", comment="Geographic Location Name"
|
||||
)
|
||||
geo_longitude = mapped_column(
|
||||
Numeric(20, 6), server_default="0", comment="Geographic Location Latitude"
|
||||
)
|
||||
geo_altitude = mapped_column(
|
||||
Numeric(20, 6), server_default="0", comment="Geographic Location Longitude"
|
||||
)
|
||||
geo_description = mapped_column(
|
||||
Text, nullable=False, comment="Geographic Location Description"
|
||||
)
|
||||
geo_area_size = mapped_column(
|
||||
Numeric(20, 2),
|
||||
nullable=True,
|
||||
server_default="0",
|
||||
comment="Geographic Location Area Size",
|
||||
)
|
||||
geo_population = mapped_column(
|
||||
BigInteger, nullable=True, comment="Geographic Location Population"
|
||||
)
|
||||
# geo_geom_point = mapped_column(Geometry('POINT', srid=4326), nullable=True, comment="Geographic Location Points")
|
||||
# geo_geom_polygon = mapped_column(Geometry('POLYGON', srid=4326), nullable=True,
|
||||
# comment="Geographic Location Vector geographic information (polygon)")
|
||||
# geo_centroid = mapped_column( GEOMETRY(POINT, 4326), nullable=True,
|
||||
# comment="Geographic Location center of gravity of the region(points)")
|
||||
|
||||
__table_args__ = (
|
||||
Index("_address_geographic_locations_ndx_00", geo_table, geo_id),
|
||||
Index("_address_geographic_locations_ndx_01", geo_latitude, geo_longitude),
|
||||
{"comment": "Geographic Location Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressCountry(CrudCollection):
|
||||
"""
|
||||
Country class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_country"
|
||||
__exclude__fields__ = []
|
||||
|
||||
country_code = mapped_column(String(16), nullable=False, comment="Country Code")
|
||||
country_name = mapped_column(String, nullable=False, comment="Country Name")
|
||||
money_code = mapped_column(String(12), nullable=True, comment="Money Code")
|
||||
language = mapped_column(String, nullable=True, comment="Language Code")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_address_country_ndx_00", money_code),
|
||||
Index("_address_country_ndx_01", country_code, unique=True),
|
||||
{"comment": "Country Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressState(CrudCollection):
|
||||
"""
|
||||
State class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_state"
|
||||
__exclude__fields__ = []
|
||||
|
||||
state_code = mapped_column(String(16), nullable=False, comment="State Code")
|
||||
state_name = mapped_column(String, nullable=False, comment="State Name")
|
||||
licence_plate = mapped_column(String(24), nullable=True, comment="Sign Code")
|
||||
phone_code = mapped_column(String(36), nullable=True, comment="Phone Code")
|
||||
gov_code = mapped_column(String(128), nullable=True, comment="Government Code")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
country_id = mapped_column(ForeignKey("address_country.id"))
|
||||
country_uu_id = mapped_column(String, server_default="", comment="Country UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_address_state_ndx_01",
|
||||
country_id,
|
||||
state_code,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "State Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressCity(CrudCollection):
|
||||
"""
|
||||
City class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_city"
|
||||
__exclude__fields__ = []
|
||||
|
||||
city_code = mapped_column(String(24), nullable=False, comment="City Code")
|
||||
city_name = mapped_column(String, nullable=False, comment="City Name")
|
||||
licence_plate = mapped_column(String(24), nullable=True, comment="Sign Code")
|
||||
phone_code = mapped_column(String(36), nullable=True, comment="Phone Code")
|
||||
gov_code = mapped_column(String(128), nullable=True, comment="Government Code")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
state_id = mapped_column(ForeignKey("address_state.id"))
|
||||
state_uu_id = mapped_column(String, server_default="", comment="State UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_address_city_ndx_01",
|
||||
state_id,
|
||||
city_code,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "City Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressDistrict(CrudCollection):
|
||||
"""
|
||||
District class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_district"
|
||||
__exclude__fields__ = []
|
||||
|
||||
district_code = mapped_column(String(16), nullable=False, comment="District Code")
|
||||
district_name = mapped_column(String, nullable=False, comment="District Name")
|
||||
phone_code = mapped_column(String(36), nullable=True, comment="Phone Code")
|
||||
gov_code = mapped_column(String(128), nullable=True, comment="Government Code")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
city_id = mapped_column(
|
||||
ForeignKey("address_city.id"), nullable=False, comment="City ID"
|
||||
)
|
||||
city_uu_id = mapped_column(String, server_default="", comment="City UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_address_district_ndx_01",
|
||||
city_id,
|
||||
district_code,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "District Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressLocality(CrudCollection):
|
||||
"""
|
||||
Locality class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_locality"
|
||||
__exclude__fields__ = []
|
||||
|
||||
locality_code = mapped_column(String(16), nullable=False, comment="Locality Code")
|
||||
locality_name = mapped_column(String, nullable=False, comment="Locality Name")
|
||||
type_code = 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")
|
||||
address_show = mapped_column(Boolean, server_default="1")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
district_id = mapped_column(
|
||||
ForeignKey("address_district.id"), nullable=False, comment="District ID"
|
||||
)
|
||||
district_uu_id = mapped_column(String, server_default="", comment="District UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_address_locality_ndx_01",
|
||||
district_id,
|
||||
locality_code,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Locality Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressNeighborhood(CrudCollection):
|
||||
"""
|
||||
Neighborhood class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_neighborhood"
|
||||
__exclude__fields__ = []
|
||||
|
||||
neighborhood_code = mapped_column(
|
||||
String(16), nullable=False, comment="Neighborhood Code"
|
||||
)
|
||||
neighborhood_name = mapped_column(
|
||||
String, nullable=False, comment="Neighborhood Name"
|
||||
)
|
||||
type_code = 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")
|
||||
address_show = mapped_column(Boolean, server_default="1")
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
|
||||
district_id = mapped_column(
|
||||
ForeignKey("address_district.id"), nullable=True, comment="District ID"
|
||||
)
|
||||
district_uu_id = mapped_column(String, server_default="", comment="District UUID")
|
||||
locality_id = mapped_column(
|
||||
ForeignKey("address_locality.id"), nullable=True, comment="Locality ID"
|
||||
)
|
||||
locality_uu_id = mapped_column(String, server_default="", comment="Locality UUID")
|
||||
|
||||
__table_args__ = (
|
||||
Index(
|
||||
"_address_neighborhood_ndx_01",
|
||||
locality_id,
|
||||
neighborhood_code,
|
||||
unique=True,
|
||||
),
|
||||
{"comment": "Neighborhood Information"},
|
||||
)
|
||||
|
||||
|
||||
class AddressStreet(CrudCollection):
|
||||
"""
|
||||
Street class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "address_street"
|
||||
__exclude__fields__ = []
|
||||
|
||||
street_code = mapped_column(String(16), nullable=False, comment="Street Code")
|
||||
street_name = mapped_column(String, nullable=False, comment="Street Name")
|
||||
type_code = 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")
|
||||
|
||||
address_geographic_id = mapped_column(
|
||||
BigInteger, nullable=True, comment="Address Geographic Id"
|
||||
)
|
||||
neighborhood_id = mapped_column(
|
||||
ForeignKey("address_neighborhood.id"), nullable=False, comment="Neighborhood ID"
|
||||
)
|
||||
neighborhood_uu_id = mapped_column(
|
||||
String, server_default="", comment="Neighborhood UUID"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("_address_street_ndx_01", neighborhood_id, street_code, unique=True),
|
||||
{"comment": "Street Information"},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def search_address_text(cls, search_text, token_dict=None):
|
||||
field_dict = {
|
||||
"AddressStreet.uu_id": cls.uu_id,
|
||||
"AddressCountry.uu_id": AddressCountry.uu_id,
|
||||
"AddressState.uu_id": AddressState.uu_id,
|
||||
"AddressCity.uu_id": AddressCity.uu_id,
|
||||
"AddressDistrict.uu_id": AddressDistrict.uu_id,
|
||||
"AddressLocality.uu_id": AddressLocality.uu_id,
|
||||
"AddressNeighborhood.uu_id": AddressNeighborhood.uu_id,
|
||||
"AddressCountry.country_name": AddressCountry.country_name,
|
||||
"AddressState.state_name": AddressState.state_name,
|
||||
"AddressCity.city_name": AddressCity.city_name,
|
||||
"AddressDistrict.district_name": AddressDistrict.district_name,
|
||||
"AddressLocality.locality_name": AddressLocality.locality_name,
|
||||
"AddressNeighborhood.neighborhood_name": AddressNeighborhood.neighborhood_name,
|
||||
"AddressStreet.street_name": cls.street_name,
|
||||
}
|
||||
joined_data = (
|
||||
cls.session.query(*list(field_dict.values()))
|
||||
.select_from(cls)
|
||||
.join(AddressNeighborhood, AddressNeighborhood.id == cls.neighborhood_id)
|
||||
.join(
|
||||
AddressLocality, AddressLocality.id == AddressNeighborhood.locality_id
|
||||
)
|
||||
.join(AddressDistrict, AddressDistrict.id == AddressLocality.district_id)
|
||||
.join(AddressCity, AddressCity.id == AddressDistrict.city_id)
|
||||
.join(AddressState, AddressState.id == AddressCity.state_id)
|
||||
.join(AddressCountry, AddressCountry.id == AddressState.country_id)
|
||||
.filter(
|
||||
or_(
|
||||
AddressNeighborhood.neighborhood_name.ilike(
|
||||
f"%{str(search_text).upper()}%"
|
||||
),
|
||||
AddressLocality.locality_name.ilike(
|
||||
f"%{str(search_text).upper()}%"
|
||||
),
|
||||
AddressDistrict.district_name.ilike(
|
||||
f"%{str(search_text).upper()}%"
|
||||
),
|
||||
# AddressCity.city_name.ilike(f"%{str(search_text).upper()}%"),
|
||||
# AddressState.state_name.ilike(f"%{str(search_text).upper()}%"),
|
||||
# AddressCountry.country_name.ilike(f"%{str(search_text).upper()}%"),
|
||||
cls.street_name.ilike(f"%{str(search_text).upper()}%"),
|
||||
),
|
||||
)
|
||||
)
|
||||
# select([mytable.c.id]).where(
|
||||
# func.to_tsvector('english', mytable.c.title) \
|
||||
# .match('somestring', postgresql_regconfig='english')
|
||||
# )
|
||||
joined_statement = joined_data
|
||||
joined_data = joined_data.first()
|
||||
if not joined_data:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="No address found with the given search text.",
|
||||
)
|
||||
return dict(
|
||||
query=joined_statement,
|
||||
schema=list(field_dict.keys()),
|
||||
)
|
||||
|
||||
|
||||
class OccupantTypes(CrudCollection):
|
||||
"""
|
||||
Occupant Types class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
|
||||
__tablename__ = "occupant_types"
|
||||
__exclude__fields__ = []
|
||||
|
||||
occupant_type = mapped_column(String, nullable=False, comment="Occupant Type")
|
||||
occupant_description = mapped_column(String, server_default="")
|
||||
occupant_code = mapped_column(String, server_default="")
|
||||
occupant_category = mapped_column(String, server_default="")
|
||||
occupant_category_type = mapped_column(String, server_default="")
|
||||
occupant_is_unique = mapped_column(Boolean, server_default="0")
|
||||
|
||||
__table_args__ = ({"comment": "Occupant Types Information"},)
|
||||
|
||||
@classmethod
|
||||
def get_manager_occupant_type(cls):
|
||||
if occupant_types := cls.filter_active(
|
||||
cls.occupant_is_unique == True, cls.occupant_category_type == "MT"
|
||||
).data:
|
||||
return [occupant.uu_id.__str__() for occupant in occupant_types]
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="No manager type found.",
|
||||
)
|
||||
|
||||
|
||||
class Contracts(CrudCollection):
|
||||
"""
|
||||
Contract class based on declarative_base and BaseMixin via session
|
||||
"""
|
||||
__tablename__ = 'contracts'
|
||||
__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_title = mapped_column(String(255))
|
||||
contract_details = mapped_column(Text)
|
||||
contract_terms = mapped_column(Text)
|
||||
|
||||
contract_code = mapped_column(
|
||||
String(100), nullable=False, comment="contract_code is the unique code given by the system."
|
||||
)
|
||||
contract_date = mapped_column(
|
||||
TIMESTAMP, server_default="2099-12-31 23:59:59",
|
||||
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."
|
||||
)
|
||||
|
||||
company_id = mapped_column(Integer, ForeignKey('companies.id'), nullable=True)
|
||||
company_uu_id = mapped_column(String, server_default="", comment="Company UUID")
|
||||
|
||||
person_id = mapped_column(Integer, ForeignKey('people.id'), nullable=True)
|
||||
person_uu_id = mapped_column(String, server_default="", comment="Person UUID")
|
||||
|
||||
@classmethod
|
||||
def retrieve_contact_no(cls):
|
||||
import arrow
|
||||
# todo When create record contract_code == below string
|
||||
related_date, counter = arrow.now(), 1
|
||||
return f"{related_date.date().year}{str(cls.contract_type)}{str(counter).zfill(6)}"
|
||||
|
||||
__table_args__ = (
|
||||
Index("_contract_ndx_01", contract_code, unique=True),
|
||||
{"comment": "Contract Information"}
|
||||
)
|
||||
|
||||
# def selected_employee_and_duty_details(self, selected_duty_uu_id):
|
||||
# from database_sql_models import (
|
||||
# Companies,
|
||||
# Employees,
|
||||
# Duties,
|
||||
# Departments,
|
||||
# )
|
||||
#
|
||||
# found_person = People.find_one(id=self.person_id)
|
||||
# found_employee = Employees.find_one(
|
||||
# people_id=found_person.id, is_confirmed=True
|
||||
# )
|
||||
# found_duty = Duties.find_one(uu_id=selected_duty_uu_id)
|
||||
# found_department = Departments.find_one(id=found_duty.department_id)
|
||||
# found_company = Companies.find_one(id=found_department.company_id)
|
||||
# return {
|
||||
# "duty_list": {
|
||||
# "duty_id": found_duty.id,
|
||||
# "duty_uu_id": found_duty.uu_id.__str__(),
|
||||
# "duty_code": found_duty.duty_code,
|
||||
# "duty_name": found_duty.duty_name,
|
||||
# "duty_description": found_duty.duty_description,
|
||||
# },
|
||||
# "employee_list": {
|
||||
# "employee_id": found_employee.id,
|
||||
# "employee_uu_id": found_employee.uu_id.__str__(),
|
||||
# "people_id": found_employee.people_id,
|
||||
# "duty_id": found_employee.duty_id,
|
||||
# "employee_description": found_employee.employee_description,
|
||||
# },
|
||||
# "department_list": {
|
||||
# "department_id": found_department.id,
|
||||
# "department_uu_id": found_department.uu_id.__str__(),
|
||||
# "company_id": found_department.company_id,
|
||||
# "department_name": found_department.department_name,
|
||||
# "department_description": found_department.department_description,
|
||||
# },
|
||||
# "companies_list": {
|
||||
# "company_id": found_company.id,
|
||||
# "company_uu_id": found_company.uu_id.__str__(),
|
||||
# "formal_name": found_company.formal_name,
|
||||
# "company_tag": found_company.company_tag,
|
||||
# },
|
||||
# }
|
||||
95
databases/sql_models/others/enums.py
Normal file
95
databases/sql_models/others/enums.py
Normal file
@@ -0,0 +1,95 @@
|
||||
from fastapi.exceptions import HTTPException
|
||||
|
||||
from sqlalchemy import (
|
||||
UUID,
|
||||
String,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import (
|
||||
Mapped,
|
||||
mapped_column,
|
||||
)
|
||||
from databases.sql_models.core_mixin import BaseCollection
|
||||
|
||||
|
||||
class ApiEnumDropdown(BaseCollection):
|
||||
__tablename__ = "api_enum_dropdown"
|
||||
__exclude__fields__ = ["enum_class"]
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
uu_id: Mapped[str] = mapped_column(
|
||||
UUID, server_default=text("gen_random_uuid()"), index=True, unique=True
|
||||
)
|
||||
enum_class = mapped_column(String, nullable=False, comment="Enum Constant Name")
|
||||
key = mapped_column(String, nullable=False, comment="Enum Key")
|
||||
value = mapped_column(String, nullable=False, comment="Enum Value")
|
||||
description = mapped_column(String, nullable=True)
|
||||
|
||||
__table_args__ = ({"comment": "Enum objets that are linked to tables"},)
|
||||
|
||||
@classmethod
|
||||
def get_by_uuid(cls, uuid: str):
|
||||
return cls.query.filter(cls.uu_id == uuid).first()
|
||||
|
||||
@classmethod
|
||||
def get_debit_search(cls, search_debit: str = None, search_uu_id: str = None):
|
||||
if search_uu_id:
|
||||
if search := cls.query.filter(
|
||||
cls.enum_class.in_(["DebitTypes"]),
|
||||
cls.uu_id == search_uu_id,
|
||||
).first():
|
||||
return search
|
||||
elif search_debit:
|
||||
if search := cls.query.filter(
|
||||
cls.enum_class.in_(["DebitTypes"]),
|
||||
cls.key == search_debit,
|
||||
).first():
|
||||
return search
|
||||
return cls.query.filter(
|
||||
cls.enum_class.in_(["DebitTypes"]),
|
||||
).all()
|
||||
|
||||
@classmethod
|
||||
def get_due_types(cls):
|
||||
if due_list := cls.filter_active(
|
||||
cls.enum_class == "BuildDuesTypes", cls.key.in_(["BDT-A", "BDT-D"])
|
||||
).data:
|
||||
return [due.uu_id.__str__() for due in due_list]
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="No dues types found",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def due_type_search(cls, search_management: str = None, search_uu_id: str = None):
|
||||
if search_uu_id:
|
||||
if search := cls.query.filter(
|
||||
cls.enum_class.in_(["BuildDuesTypes"]),
|
||||
cls.uu_id == search_uu_id,
|
||||
).first():
|
||||
return search
|
||||
elif search_management:
|
||||
if search := cls.query.filter(
|
||||
cls.enum_class.in_(["BuildDuesTypes"]),
|
||||
cls.key == search_management,
|
||||
).first():
|
||||
return search
|
||||
return cls.query.filter(
|
||||
cls.enum_class.in_(["BuildDuesTypes"]),
|
||||
).all()
|
||||
|
||||
def get_enum_dict(self):
|
||||
return {
|
||||
"uu_id": str(self.uu_id),
|
||||
"enum_class": self.enum_class,
|
||||
"key": self.key,
|
||||
"value": self.value,
|
||||
"description": self.description,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def uuid_of_enum(cls, enum_class: str, key: str):
|
||||
return str(getattr(cls.find_one(enum_class=enum_class, key=key), "uu_id", None))
|
||||
|
||||
|
||||
ApiEnumDropdown.set_session(ApiEnumDropdown.__session__)
|
||||
22
databases/sql_models/postgres_database.py
Normal file
22
databases/sql_models/postgres_database.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from api_configs import WagDatabase
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
|
||||
engine_config = {
|
||||
"url": WagDatabase.DATABASE_URL,
|
||||
"pool_size": 10,
|
||||
"max_overflow": 0,
|
||||
"echo": False,
|
||||
}
|
||||
|
||||
engine = create_engine(**engine_config)
|
||||
session_config = {"autoflush": True, "bind": engine, "echo": True}
|
||||
SessionLocal = sessionmaker(**session_config)
|
||||
session = scoped_session(sessionmaker(bind=engine))
|
||||
session.expunge_all()
|
||||
|
||||
Base = declarative_base()
|
||||
Base.session = session
|
||||
34
databases/sql_models/response_model.py
Normal file
34
databases/sql_models/response_model.py
Normal file
@@ -0,0 +1,34 @@
|
||||
|
||||
|
||||
|
||||
class AlchemyResponse:
|
||||
"""
|
||||
alchemy_object = [AlchemyObject].filter_non_deleted() -> AlchemyResponse
|
||||
alchemy_object.get(1) -> Get the first object in the list
|
||||
alchemy_object.data -> Get the list of objects
|
||||
alchemy_object.count -> Get the count of objects
|
||||
"""
|
||||
|
||||
def __init__(self, query, first: bool = False):
|
||||
self.first = first
|
||||
self.__query = query
|
||||
|
||||
def get(self, index: int):
|
||||
count = self.count
|
||||
if count and not index > count:
|
||||
return self.data[index - 1]
|
||||
return None
|
||||
|
||||
@property
|
||||
def data(self):
|
||||
if self.first:
|
||||
return self.__query.first()
|
||||
return self.__query.all()
|
||||
|
||||
@property
|
||||
def count(self):
|
||||
return self.__query.count()
|
||||
|
||||
@property
|
||||
def query(self):
|
||||
return self.__query
|
||||
27
databases/sql_models/rules/rules.py
Normal file
27
databases/sql_models/rules/rules.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from sqlalchemy import Column, String
|
||||
from databases.sql_models.core_mixin import CrudCollection
|
||||
|
||||
|
||||
class EndpointRestriction(CrudCollection):
|
||||
"""
|
||||
Initialize Endpoint Restriction with default values
|
||||
"""
|
||||
|
||||
__tablename__ = "endpoint_restriction"
|
||||
__exclude__fields__ = []
|
||||
|
||||
endpoint_function = Column(
|
||||
String, server_default="", comment="Function name of the API endpoint"
|
||||
)
|
||||
endpoint_name = Column(
|
||||
String, server_default="", comment="Name of the API endpoint"
|
||||
)
|
||||
endpoint_method = Column(
|
||||
String, server_default="", comment="HTTP method used by the endpoint"
|
||||
)
|
||||
endpoint_desc = Column(
|
||||
String, server_default="", comment="Description of the endpoint"
|
||||
)
|
||||
endpoint_code = Column(
|
||||
String, server_default="", unique=True, comment="Unique code for the endpoint"
|
||||
)
|
||||
155
databases/sql_models/sql_operations.py
Normal file
155
databases/sql_models/sql_operations.py
Normal file
@@ -0,0 +1,155 @@
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from databases.sql_models.response_model import AlchemyResponse
|
||||
from databases.sql_models.postgres_database import Base
|
||||
|
||||
|
||||
class FilterAttributes:
|
||||
"""
|
||||
The class to use in the model for filtering.
|
||||
Usage:
|
||||
alchemy_objects = Model.filter_by_all(name="Something").data [<AlchemyObject>, <AlchemyObject>]
|
||||
alchemy_object = Model.filter_by_one(name="Something").data <AlchemyObject>
|
||||
alchemy_objects = Model.filter_all(Model.name == "Something").data [<AlchemyObject>, <AlchemyObject>]
|
||||
alchemy_object = Model.filter_one(Model.name == "Something").data <AlchemyObject>
|
||||
"""
|
||||
|
||||
__abstract__ = True
|
||||
__session__ = Base.session # The session to use in the model.
|
||||
|
||||
pre_query = None # The query to use before the filtering such as: query = cls.query.filter_by(active=True)
|
||||
filter_attr = None # The filter attributes to use in the model.
|
||||
|
||||
def flush(self):
|
||||
"""Flush the current session."""
|
||||
try:
|
||||
self.__session__.add(self)
|
||||
self.__session__.flush()
|
||||
except SQLAlchemyError as e:
|
||||
self.raise_http_exception(
|
||||
status_code="HTTP_304_NOT_MODIFIED",
|
||||
error_case=e.__class__.__name__,
|
||||
data={},
|
||||
message=str(e.__context__).split('\n')[0],
|
||||
)
|
||||
|
||||
def destroy(self):
|
||||
"""Delete the record from the database."""
|
||||
self.__session__.delete(self)
|
||||
self.__session__.commit()
|
||||
|
||||
@classmethod
|
||||
def save(cls):
|
||||
"""Saves the updated model to the current entity db."""
|
||||
try:
|
||||
cls.__session__.commit()
|
||||
except SQLAlchemyError as e:
|
||||
cls.raise_http_exception(
|
||||
status_code="HTTP_304_NOT_MODIFIED",
|
||||
error_case=e.__class__.__name__,
|
||||
data={},
|
||||
message=str(e.__context__).split('\n')[0],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _query(cls):
|
||||
"""Returns the query to use in the model."""
|
||||
return cls.pre_query if cls.pre_query else cls.query
|
||||
|
||||
@classmethod
|
||||
def add_query_to_filter(cls, filter_query, filter_list):
|
||||
return (
|
||||
filter_query.order_by(
|
||||
getattr(cls, filter_list.get("order_field")).desc()
|
||||
if str(filter_list.get("order_type"))[0] == "d"
|
||||
else getattr(cls, filter_list.get("order_field")).asc()
|
||||
)
|
||||
.limit(filter_list.get("size"))
|
||||
.offset(int((filter_list.get("page")) - 1) * int(filter_list.get("size")))
|
||||
.populate_existing()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_filter_attributes(cls):
|
||||
"""
|
||||
Returns the filter to use pagination and ordering.
|
||||
page is the current page number.
|
||||
size is the number of records per page.
|
||||
order_field is the field to order by.
|
||||
order_type is the order type (asc or desc).
|
||||
include_joins returns the joined tables when related field names are given as a list.
|
||||
"""
|
||||
return {
|
||||
"page": getattr(cls.filter_attr, "page", 1),
|
||||
"size": getattr(cls.filter_attr, "size", 10),
|
||||
"order_field": getattr(cls.filter_attr, "order_field", "id"),
|
||||
"order_type": getattr(cls.filter_attr, "order_type", "asc"),
|
||||
"include_joins": getattr(cls.filter_attr, "include_joins", []),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_not_expired_query_arg(cls, *arg, expired=True):
|
||||
"""Add expiry_starts and expiry_ends to the query."""
|
||||
from api_library.date_time_actions.date_functions import system_arrow
|
||||
if expired:
|
||||
arg_add = (
|
||||
*arg[0],
|
||||
system_arrow.get(cls.expiry_ends) >= system_arrow.now(),
|
||||
system_arrow.now() >= system_arrow.get(cls.expiry_starts),
|
||||
)
|
||||
return arg_add
|
||||
return arg[0]
|
||||
|
||||
@classmethod
|
||||
def filter_by_all(cls, **kwargs):
|
||||
"""
|
||||
Filters all the records regardless of is_deleted, is_confirmed.
|
||||
"""
|
||||
filter_list = cls.get_filter_attributes()
|
||||
query = cls._query().filter_by(**kwargs)
|
||||
data = cls.add_query_to_filter(query, filter_list)
|
||||
return AlchemyResponse(query=data, first=False)
|
||||
|
||||
@classmethod
|
||||
def filter_by_one(cls, **kwargs):
|
||||
"""
|
||||
Filters one record regardless of is_deleted, is_confirmed.
|
||||
"""
|
||||
query = cls._query().filter_by(**kwargs)
|
||||
return AlchemyResponse(query=query, first=True)
|
||||
|
||||
@classmethod
|
||||
def filter_all(cls, *args, expired: bool = False):
|
||||
"""
|
||||
Filters all the records regardless of is_deleted, is_confirmed.
|
||||
"""
|
||||
filter_list = cls.get_filter_attributes()
|
||||
query = cls._query()
|
||||
data = cls.add_query_to_filter(query, filter_list)
|
||||
return AlchemyResponse(query=data, first=False)
|
||||
|
||||
@classmethod
|
||||
def filter_one(cls, *args, expired: bool = False):
|
||||
"""
|
||||
Filters one record regardless of is_deleted, is_confirmed.
|
||||
"""
|
||||
|
||||
arg = cls.get_not_expired_query_arg(args, expired=expired)
|
||||
query = cls._query().filter(*arg)
|
||||
return AlchemyResponse(query=query, first=True)
|
||||
|
||||
@classmethod
|
||||
def raise_http_exception(cls, status_code, error_case, data, message):
|
||||
from fastapi.exceptions import HTTPException
|
||||
from fastapi import status
|
||||
from json import dumps
|
||||
|
||||
cls.__session__.rollback()
|
||||
raise HTTPException(
|
||||
status_code=getattr(status, status_code, 'HTTP_404_NOT_FOUND'),
|
||||
detail=dumps({
|
||||
"data": data,
|
||||
"error": error_case,
|
||||
"message": message,
|
||||
})
|
||||
)
|
||||
Reference in New Issue
Block a user