latest version of apis event and cahce ablitites added

This commit is contained in:
berkay 2025-02-10 11:41:38 +03:00
parent e832ec7603
commit 26f601f01a
396 changed files with 34981 additions and 2 deletions

162
.gitignore copy Normal file
View File

@ -0,0 +1,162 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

View File

@ -0,0 +1,18 @@
from ApiLayers.AllConfigs import HostConfig
class EmailConfig:
EMAIL_HOST: str = HostConfig.EMAIL_HOST
EMAIL_USERNAME: str = "karatay@mehmetkaratay.com.tr"
EMAIL_PASSWORD: str = "system"
EMAIL_PORT: int = 587
EMAIL_SEND: bool = False
@classmethod
def as_dict(cls):
return dict(
host=EmailConfig.EMAIL_HOST,
port=EmailConfig.EMAIL_PORT,
username=EmailConfig.EMAIL_USERNAME,
password=EmailConfig.EMAIL_PASSWORD,
)

View File

@ -0,0 +1,13 @@
from pydantic import BaseModel
from typing import List, Dict, Optional
class EmailSendModel(BaseModel):
subject: str
html: str = ""
receivers: List[str]
text: Optional[str] = ""
cc: Optional[List[str]] = None
bcc: Optional[List[str]] = None
headers: Optional[Dict] = None
attachments: Optional[Dict] = None

View File

@ -0,0 +1,10 @@
from ApiLayers.AllConfigs import HostConfig
class MongoConfig:
PASSWORD = "mongo_password"
USER_NAME = "mongo_user"
DATABASE_NAME = "mongo_database"
HOST = HostConfig.MAIN_HOST
PORT = 11777
URL = f"mongodb://{USER_NAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE_NAME}?retryWrites=true&w=majority"

View File

@ -0,0 +1,125 @@
from ApiLayers.AllConfigs import HostConfig
class WagRedis:
REDIS_HOST = HostConfig.MAIN_HOST
REDIS_PASSWORD: str = "commercial_redis_password"
REDIS_PORT: int = 11222
REDIS_DB: int = 0
@classmethod
def as_dict(cls):
return dict(
host=WagRedis.REDIS_HOST,
password=WagRedis.REDIS_PASSWORD,
port=WagRedis.REDIS_PORT,
db=WagRedis.REDIS_DB,
)
class RedisValidationKeys:
ENDPOINTS: str = "ENDPOINTS"
VALIDATIONS: str = "VALIDATIONS"
HEADERS: str = "HEADERS"
ERRORCODES: str = "ERRORCODES"
RESPONSES: str = "RESPONSES"
REQUESTS: str = "REQUESTS"
RESPONSE: str = "RESPONSE"
LANGUAGE_MODELS: str = "LANGUAGE_MODELS"
STATIC: str = "STATIC"
DYNAMIC: str = "DYNAMIC"
# REQUEST: str = "REQUEST"
# VALIDATION_USER: str = "VALIDATION_USER"
class RedisAuthKeys:
AUTH: str = "AUTH"
OCCUPANT: str = "OCCUPANT"
EMPLOYEE: str = "EMPLOYEE"
CACHE: str = "CACHE"
class RedisCategoryKeys:
REBUILD: str = "REBUILD"
ENDPOINT2CLASS: str = "ENDPOINT2CLASS"
CLUSTER_INDEX: str = "CLUSTER_INDEX"
CLUSTER_FUNCTION_CODES: str = "CLUSTER_FUNCTION_CODES"
METHOD_FUNCTION_CODES: str = "METHOD_FUNCTION_CODES"
MENU_FIRST_LAYER: str = "MENU_FIRST_LAYER"
PAGE_MAPPER: str = "PAGE_MAPPER"
MENU_MAPPER: str = "MENU_MAPPER"
class RedisCategoryPageInfoKeys:
"""
### /create?site=BuildingCluster, #/update?site=BuildingCluster, #/dashboard?site=BuildingCluster
PAGE_URL: /dashboard?site=BuildingCluster
PAGE_NAME: BuildingCluster
PAGE_INFO: {LANGUAGE_MODELS: "", ICON: "", URL: ""}
PAGE_MENU_INDEX: 1 # {build_living_space: "uuid4", LAYER: 1, MENU_INDEX: 1}
PAGE_MENU_COMPONENT: {..., lang: {"tr"}: {...}, lang: {"en"}: {...}}
PAGE_LANGUAGE: {{"tr"}: {...},{"en"}: {...}}
"""
PAGE_URL: str = "PAGE_URL"
PAGE_NAME: str = "PAGE_NAME"
PAGE_INFO: str = "PAGE_INFO"
PAGE_COMPONENT: str = "PAGE_COMPONENT"
PAGE_MENU_INDEX: str = "PAGE_MENU_INDEX"
PAGE_MENU_COMPONENT: str = "PAGE_MENU_COMPONENT"
PAGE_LANGUAGE: str = "PAGE_LANGUAGE"
class RedisCategoryPageInfoKeysAction:
"""
PAGE_MAPPER: {PAGE_URL: /dashboard?site=BuildingCluster, PAGE_NAME: BuildingCluster, PAGE_INFO: {LANGUAGE_MODELS: "", ICON: "", URL: ""}}
value : {RedisCategoryPageInfoKeys.PAGE_INFO}
MENU_MAPPER: {PAGE_MENU_INDEX: 1, PAGE_MENU_COMPONENT: {..., lang: {"tr"}: {...}, lang: {"en"}: {...}}}
value : {RedisCategoryPageInfoKeys.PAGE_INFO}
"""
page_index: str = (
f"{RedisCategoryPageInfoKeys.PAGE_MENU_INDEX}:{RedisCategoryPageInfoKeys.PAGE_URL}"
)
page_mapper_key: str = (
f"{RedisCategoryPageInfoKeys.PAGE_MENU_INDEX}:{RedisCategoryPageInfoKeys.PAGE_URL}"
)
page_mapper_key: str = (
f"{page_mapper_key}:{RedisCategoryPageInfoKeys.PAGE_LANGUAGE}"
)
menu_mapper_key: str = (
f"{RedisCategoryPageInfoKeys.PAGE_URL}:{RedisCategoryPageInfoKeys.PAGE_MENU_INDEX}"
)
menu_mapper_key: str = (
f"{menu_mapper_key}:{RedisCategoryPageInfoKeys.PAGE_MENU_COMPONENT}"
)
class RedisValidationKeysAction:
# LANGUAGE_MODELS:DYNAMIC:VALIDATIONS:
dynamic_validation_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.DYNAMIC}:{RedisValidationKeys.VALIDATIONS}"
)
# LANGUAGE_MODELS:DYNAMIC:HEADERS:REQUEST
dynamic_header_request_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.DYNAMIC}:{RedisValidationKeys.HEADERS}:{RedisValidationKeys.REQUESTS}"
)
# LANGUAGE_MODELS:DYNAMIC:HEADERS:RESPONSE
dynamic_header_response_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.DYNAMIC}:{RedisValidationKeys.HEADERS}:{RedisValidationKeys.RESPONSES}"
)
# LANGUAGE_MODELS:STATIC:ERRORCODES:
static_error_code_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.STATIC}:{RedisValidationKeys.ERRORCODES}"
)
# LANGUAGE_MODELS:STATIC:RESPONSES:
static_response_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.STATIC}:{RedisValidationKeys.RESPONSES}"
)
# LANGUAGE_MODELS:STATIC:REQUESTS:
static_request_key: str = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.STATIC}:{RedisValidationKeys.REQUESTS}"
)

View File

@ -0,0 +1,17 @@
from ApiLayers.AllConfigs import HostConfig
class WagDatabase:
HOST: str = HostConfig.MAIN_HOST
PORT: str = "5444"
SQL: str = "postgresql+psycopg2"
USERNAME: str = "berkay_wag_user"
PASSWORD: str = "berkay_wag_user_password"
DATABASE_NAME: str = "wag_database"
DATABASE_URL: str = f"{SQL}://{USERNAME}:{PASSWORD}@{HOST}:{PORT}/{DATABASE_NAME}"
class PaginateConfig:
DEFAULT_SIZE = 10
MIN_SIZE = 10
MAX_SIZE = 50

View File

@ -0,0 +1,243 @@
import datetime
def change_your_password_template(**kwargs):
user_name, forgot_link, current_year = (
kwargs["user_name"],
kwargs["forgot_link"],
str(datetime.datetime.now().year),
)
template = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.email-container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
padding-bottom: 20px;
border-bottom: 1px solid #dddddd;
}
.header img {
max-width: 100px;
}
.content {
padding: 20px 0;
}
.footer {
text-align: center;
padding: 10px;
font-size: 12px;
color: #777777;
}
.btn-success {
color: #fff;
background-color: #198754;
border-color: #198754;
text-align: center;
text-decoration: none;
vertical-align: middle;
width: 150px;
height: 40px;
border-radius: 5px;
font-weight: 400;
padding: .375rem .75rem;
}
</style>
</head>
<body>
<div class="email-container">
<div class="header">
<img src="" alt="Company Logo">
<h2>Reset Password</h2>
</div>
<div class="content">
<p>Dear %s,</p>
<p>We have received a request to reset your password for your account with Let's Program Blog. To complete the password reset process, please click on the button below:</p>
<p>Please note that this link is only valid for a day only. If you did not request a password reset, please disregard this message.</p>
<a href="%s"><button type="button" class="btn-success">Reset Password</button></a>
</div>
<div class="footer">
<p>&copy; %s Evyos Ltd Şti. All rights reserved.</p>
</div>
</div>
</body>
</html>
""" % (
user_name,
forgot_link,
current_year,
)
return template
def password_is_changed_template(**kwargs):
user_name, current_year = kwargs["user_name"], str(datetime.datetime.now().year)
template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thank You for Changing Your Password</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.email-container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
padding-bottom: 20px;
border-bottom: 1px solid #dddddd;
}
.header img {
max-width: 100px;
}
.content {
padding: 20px 0;
}
.footer {
text-align: center;
padding: 10px;
font-size: 12px;
color: #777777;
}
</style>
</head>
<body>
<div class="email-container">
<div class="header">
<img src="" alt="Company Logo">
<h2>Your Password has changed</h2>
</div>
<div class="content">
<p>Dear %s,</p>
<p>We wanted to let you know that your password has been successfully updated.
If you did not make this change or if you believe an unauthorized person has accessed your account,
please contact our support team immediately.</p>
<p>Thank you for helping us keep your account secure.</p>
</div>
<div class="footer">
<p>&copy; %s Evyos Ltd Şti. All rights reserved.</p>
</div>
</div>
</body>
</html>
""" % (
user_name,
current_year,
)
return template
def invalid_ip_or_address_found(**kwargs):
user_name, current_year, address = (
kwargs["user_name"],
str(datetime.datetime.now().year),
kwargs.get("address"),
)
template = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thank You for Changing Your Password</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.email-container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
padding-bottom: 20px;
border-bottom: 1px solid #dddddd;
}
.header img {
max-width: 100px;
}
.content {
padding: 20px 0;
}
.footer {
text-align: center;
padding: 10px;
font-size: 12px;
color: #777777;
}
</style>
</head>
<body>
<div class="email-container">
<div class="header">
<img src="" alt="Company Logo">
<h2>An Unknown login has been attempted</h2>
</div>
<div class="content">
<p>Dear %s,</p>
<p>We wanted to let you know that an unusual login attempt has been tried from address below.
If you have login from address below please ignore this message</p>
<p>Thank you for helping us keep your account secure.</p>
<h1>Address of ip attempt</h1>
<p>City : %s</p>
<p>Zip Code : %s</p>
<p>Country : %s</p>
<p>Region : %s</p>
<p>Region Name : %s</p>
<p>If you are not login from this address lets us now by clicking link below</p>
<a href="%s"><button type="button" class="btn-success">Reset Password</button></a>
</div>
<div class="footer">
<p>&copy; %s Evyos Ltd Şti. All rights reserved.</p>
</div>
</div>
</body>
</html>
""" % (
user_name,
address["city"],
address["zip"],
address["country"],
address["region"],
address["regionName"],
kwargs["notice_link"],
current_year,
)
return template

View File

@ -0,0 +1,27 @@
import datetime
class Auth:
ACCESS_EMAIL_EXT = "evyos.com.tr"
ACCESS_TOKEN_TAG = "evyos-session-key"
REFRESHER_TOKEN_TAG = "eys-session-refresher"
SECRET_KEY_72 = (
"t3sUAmjTGeTgDc6dAUrB41u2SNg0ZHzj4HTjem95y3fRH1nZXOHIBj163kib6iLybT0gLaxq"
)
SECRET_KEY_96 = "7ct8VpiwaP1hR2bVSet4dEEAgepuTZUOnO1QxOgKyDqBR2PkqNhcubSrbUUigQKoQA1PBoeeQn5ZCo24pESmVtKs76nA4EKq"
SECRET_KEY_144 = (
"R2p5Rq6KCr6PCfjFYUeH1keF2VWHFEuqINVjBGGnvRA2m10pYUKqfOtIGBcaj2v5wZmElDndzSHGOS7roQsoTelPSok0"
+ "qqMucurMWE0FGexGpFuJkfPEm9tH2OjMOqegvEetpSVywH0W4Kh4"
)
ALGORITHM = "HS256"
ACCESS_TOKEN_LENGTH: int = 90
REFRESHER_TOKEN_LENGTH: int = 144
PASSWORD_EXPIRE_DAY = datetime.timedelta(days=30)
TOKEN_EXPIRE_MINUTES_1 = datetime.timedelta(minutes=1)
TOKEN_EXPIRE_MINUTES_15 = datetime.timedelta(minutes=15)
TOKEN_EXPIRE_MINUTES_30 = datetime.timedelta(minutes=30)
TOKEN_EXPIRE_DAY_1 = datetime.timedelta(days=1)
TOKEN_EXPIRE_DAY_5 = datetime.timedelta(days=5)
TOKEN_EXPIRE_DAY_15 = datetime.timedelta(days=15)
TOKEN_EXPIRE_DAY_30 = datetime.timedelta(days=30)

View File

@ -0,0 +1,3 @@
from .main import HostConfig
__all__ = ["HostConfig"]

View File

@ -0,0 +1,31 @@
class HostConfig:
MAIN_HOST = "10.10.2.36" # http://10.10.2.36
EMAIL_HOST = "10.10.2.34" # http://10.10.2.34
class MainConfig:
APP_NAME = "evyos-web-api-gateway"
TITLE = "WAG API Web Api Gateway"
DESCRIPTION = "This api is serves as web api gateway only to evyos web services."
APP_URL = "https://www.wag.eys.gen.tr"
DATETIME_FORMAT = "YYYY-MM-DD HH:mm:ss Z"
DATETIME_FORMAT_JS = "YYYY-MM-DD HH:mm:ss +0"
# Timezone Configuration
DEFAULT_TIMEZONE = "GMT+3" # Default timezone for the application
SYSTEM_TIMEZONE = "GMT+0" # System timezone (used for internal operations)
SUPPORTED_TIMEZONES = ["GMT+0", "GMT+3"] # List of supported timezones
class LanguageConfig:
SUPPORTED_LANGUAGES = ["en", "tr"]
DEFAULT_LANGUAGE = "tr"
class ValidationsConfig:
SUPPORTED_VALIDATIONS = ["header", "validation", "all"]
DEFAULT_VALIDATION = "all"

View File

@ -0,0 +1,19 @@
from ApiLayers.ApiLibrary.date_time_actions.date_functions import (
DateTimeLocal,
system_arrow,
client_arrow,
)
from ApiLayers.ApiLibrary.extensions.select import (
SelectActionWithEmployee,
SelectAction,
)
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
__all__ = [
"DateTimeLocal",
"system_arrow",
"client_arrow",
"get_line_number_for_error",
"SelectActionWithEmployee",
"SelectAction",
]

View File

@ -0,0 +1,14 @@
"""Utility functions for getting line numbers and file locations."""
from inspect import currentframe, getframeinfo, stack
def get_line_number_for_error() -> str:
"""Get the file name and line number of where an error occurred.
Returns:
str: A string in the format 'filename | line_number' showing where the error occurred
"""
caller = stack()[1] # Get the caller's frame
frameinfo = getframeinfo(caller[0])
return f"{frameinfo.filename} | {frameinfo.lineno}"

View File

@ -0,0 +1,117 @@
import arrow
import calendar
from ApiLayers.AllConfigs.main import MainConfig as Config
class DateTimeLocal:
def __init__(self, timezone: str = None, is_client: bool = True):
if timezone and timezone not in Config.SUPPORTED_TIMEZONES:
raise ValueError(
f"Unsupported timezone: {timezone}. Must be one of {Config.SUPPORTED_TIMEZONES}"
)
self.timezone = Config.SYSTEM_TIMEZONE
if is_client:
self.timezone = (timezone or Config.DEFAULT_TIMEZONE).replace("-", "+")
def find_last_day_of_month(self, date_value):
today = self.get(date_value).date()
_, last_day = calendar.monthrange(today.year, today.month)
return self.get(today.year, today.month, last_day, 23, 59, 59).to(self.timezone)
def find_first_day_of_month(self, date_value):
today = self.get(date_value).date()
return self.get(today.year, today.month, 1).to(self.timezone)
def get(self, *args):
return arrow.get(*args).to(str(self.timezone))
def now(self):
return arrow.now().to(str(self.timezone))
def shift(self, date, **kwargs):
return self.get(date).shift(**kwargs)
def date(self, date):
return self.get(date).date()
def time(self, date):
return self.get(date).time()
def string_date(self, date, splitter: str = "-"):
return str(self.get(date).date()).replace("-", splitter)
def string_time_only(self, date):
return self.get(date).format("HH:mm:ss")
def string_date_only(self, date):
return self.get(date).format("YYYY-MM-DD")
def to_timestamp(self, date):
"""Convert datetime to UTC timestamp"""
return self.get(date).timestamp()
def from_timestamp(self, timestamp):
"""Convert timestamp to timezone-aware datetime"""
return arrow.get(timestamp).to(str(self.timezone))
def is_timezone_aware(self, date):
"""Check if a date is timezone-aware"""
return self.get(date).tzinfo is not None
def standardize_timezone(self, date):
"""Ensure date is in the correct timezone"""
if not self.is_timezone_aware(date):
return self.get(date).to(str(self.timezone))
return self.get(date)
def get_expiry_time(self, **kwargs):
"""Get future time for cache expiry
Example: get_expiry_time(hours=1, minutes=30)
"""
return self.now().shift(**kwargs)
def is_expired(self, timestamp):
"""Check if a timestamp is expired"""
if not timestamp:
return True
return self.from_timestamp(timestamp) < self.now()
def get_cache_key(self, base_key, *args):
"""Generate a cache key with timezone info
Example: get_cache_key('user_profile', user_id, 'details')
"""
components = [str(base_key)]
components.extend(str(arg) for arg in args)
components.append(f"tz_{self.timezone}")
return ":".join(components)
def format_for_db(self, date):
"""Format date for database storage"""
return self.get(date).format("YYYY-MM-DD HH:mm:ss.SSSZZ")
def parse_from_db(self, date_str):
"""Parse date from database format"""
if not date_str:
return None
return self.get(date_str)
def get_day_boundaries(self, date=None):
"""Get start and end of day in current timezone"""
dt = self.get(date) if date else self.now()
start = dt.floor("day")
end = dt.ceil("day")
return start, end
def get_month_boundaries(self, date=None):
"""Get start and end of month in current timezone"""
dt = self.get(date) if date else self.now()
start = dt.floor("month")
end = dt.ceil("month")
return start, end
client_arrow = DateTimeLocal(is_client=True)
system_arrow = DateTimeLocal(is_client=False)

View File

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

View File

@ -0,0 +1,43 @@
import hashlib
import uuid
import secrets
import random
from ApiLayers.AllConfigs.Token.config import Auth
class PasswordModule:
@staticmethod
def generate_random_uu_id(str_std: bool = True):
return str(uuid.uuid4()) if str_std else uuid.uuid4()
@staticmethod
def generate_token(length=32) -> str:
letters = "abcdefghijklmnopqrstuvwxyz"
merged_letters = [letter for letter in letters] + [
letter.upper() for letter in letters
]
token_generated = secrets.token_urlsafe(length)
for i in str(token_generated):
if i not in merged_letters:
token_generated = token_generated.replace(
i, random.choice(merged_letters), 1
)
return token_generated
@staticmethod
def generate_access_token() -> str:
return secrets.token_urlsafe(Auth.ACCESS_TOKEN_LENGTH)
@staticmethod
def generate_refresher_token() -> str:
return secrets.token_urlsafe(Auth.REFRESHER_TOKEN_LENGTH)
@staticmethod
def create_hashed_password(domain: str, id_: str, password: str) -> str:
return hashlib.sha256(f"{domain}:{id_}:{password}".encode("utf-8")).hexdigest()
@classmethod
def check_password(cls, domain, id_, password, password_hashed) -> bool:
return cls.create_hashed_password(domain, id_, password) == password_hashed

View File

@ -0,0 +1,39 @@
from fastapi import APIRouter
import uuid
from Events.Engine.abstract_class import CategoryCluster, MethodToEvent
class CreateRouterFromCluster:
def __init__(self, **kwargs):
self.prefix = kwargs.get("prefix")
self.tags = kwargs.get("tags")
self.include_in_schema = bool(kwargs.get("include_in_schema", True))
self.router = APIRouter(
prefix=self.prefix, tags=self.tags, include_in_schema=self.include_in_schema
)
class CreateEndpointFromCluster:
def __init__(self, **kwargs):
self.router: CategoryCluster = kwargs.get("router")
self.method_endpoint: MethodToEvent = kwargs.get("method_endpoint")
self.attach_router()
def attach_router(self):
method = getattr(self.router, self.method_endpoint.METHOD.lower())
# Create a unique operation ID based on the endpoint path, method, and a unique identifier
kwargs = {
"path": self.method_endpoint.URL,
"summary": self.method_endpoint.SUMMARY,
"description": self.method_endpoint.DESCRIPTION,
}
if (
hasattr(self.method_endpoint, "RESPONSE_MODEL")
and self.method_endpoint.RESPONSE_MODEL is not None
):
kwargs["response_model"] = self.method_endpoint.RESPONSE_MODEL
method(**kwargs)(self.method_endpoint.endpoint_callable)

View File

@ -0,0 +1,4 @@
from Services.Redis import RedisActions, AccessToken
from Services.Redis.Models.cluster import RedisList
redis_list = RedisList(redis_key="test")

View File

@ -0,0 +1,95 @@
from ApiLayers.ApiValidations.Request.authentication import Login
from ApiLayers.ApiLibrary.token.password_module import PasswordModule
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
from ApiLayers.ErrorHandlers import HTTPExceptionApi
class UserLoginModule:
def __init__(self, request: "Request"):
self.request = request
self.user = None
self.access_object = None
self.access_token = None
self.refresh_token = None
@property
def as_dict(self) -> dict:
return {
"user": self.user,
"access_object": self.access_object,
"access_token": self.access_token,
"refresh_token": self.refresh_token,
}
@staticmethod
def check_user_exists(access_key: str):
from ApiLayers.Schemas import Users
"""
Check if the user exists in the database.
"""
db_session = Users.new_session() # Check if user exists.
if "@" in access_key:
found_user: Users = Users.filter_one(
Users.email == access_key.lower(), db=db_session
).data
else:
found_user: Users = Users.filter_one(
Users.phone_number == access_key.replace(" ", ""), db=db_session
).data
if not found_user:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang="en",
loc=get_line_number_for_error(),
sys_msg="check_user_exists: User not found",
)
return found_user
def login_user_via_credentials(self, access_data: "Login") -> None:
from ApiLayers.ApiServices.Token.token_handler import TokenService
from ApiLayers.Schemas import Users
"""
Login the user via the credentials.
"""
# Get the actual data from the BaseRequestModel if needed
found_user: Users = self.check_user_exists(access_key=access_data.access_key)
if len(found_user.hash_password) < 5:
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang=found_user.lang,
loc=get_line_number_for_error(),
sys_msg="login_user_via_credentials: Invalid password create a password to user first",
)
# Check if the password is correct
if PasswordModule.check_password(
domain=access_data.domain,
id_=found_user.uu_id,
password=access_data.password,
password_hashed=found_user.hash_password,
):
# Set the access token to the redis
token_response = TokenService.set_access_token_to_redis(
request=self.request,
user=found_user,
domain=access_data.domain,
remember=access_data.remember_me,
)
# Set the user and token information to the instance
self.user = found_user.get_dict()
self.access_token = token_response.get("access_token")
self.refresh_token = token_response.get("refresh_token")
self.access_object = {
"user_type": token_response.get("user_type", None),
"selection_list": token_response.get("selection_list", {}),
}
return None
raise HTTPExceptionApi(
error_code="HTTP_400_BAD_REQUEST",
lang="tr",
loc=get_line_number_for_error(),
sys_msg="login_user_via_credentials: raised an unknown error",
)

View File

@ -0,0 +1,457 @@
"""Token service for handling authentication tokens and user sessions."""
from typing import List, Union, TypeVar, Dict, Any, TYPE_CHECKING
import arrow
from ApiLayers.AllConfigs.Token.config import Auth
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
from ApiLayers.ApiLibrary.date_time_actions.date_functions import DateTimeLocal
from ApiLayers.ApiLibrary.token.password_module import PasswordModule
from ApiLayers.ErrorHandlers import HTTPExceptionApi
from ApiLayers.ApiValidations.Custom.token_objects import (
EmployeeTokenObject,
OccupantTokenObject,
UserType,
CompanyToken,
OccupantToken,
)
from ApiLayers.Schemas import (
Users,
BuildLivingSpace,
BuildParts,
Employees,
Addresses,
Companies,
Staff,
Duty,
Duties,
Departments,
OccupantTypes,
)
from Services.Redis.Models.response import RedisResponse
from Services.Redis import RedisActions, AccessToken
if TYPE_CHECKING:
from fastapi import Request
T = TypeVar("T", EmployeeTokenObject, OccupantTokenObject)
class TokenService:
"""Service class for handling authentication tokens and user sessions."""
@classmethod
def _create_access_token(cls, access: bool = True) -> str:
"""Generate a new access token."""
if not access:
return PasswordModule.generate_token(Auth.REFRESHER_TOKEN_LENGTH)
return PasswordModule.generate_token(Auth.ACCESS_TOKEN_LENGTH)
@classmethod
def _get_user_tokens(cls, user: Users) -> RedisResponse:
"""Get all tokens for a user from Redis."""
return RedisActions.get_json(list_keys=[f"*:{str(user.uu_id)}"])
@classmethod
def do_employee_login(
cls, request: "Request", user: Users, domain: str
) -> Dict[str, Any]:
"""Handle employee login process and return login information."""
from ApiLayers.Schemas.identity.identity import UsersTokens, People
db_session = Employees.new_session()
list_employee = Employees.filter_all(
Employees.people_id == user.person_id, db=db_session
).data
companies_uu_id_list: List[str] = []
companies_id_list: List[int] = []
companies_list: List[Dict[str, Any]] = []
duty_uu_id_list: List[str] = []
duty_id_list: List[int] = []
for employee in list_employee:
staff = Staff.filter_one(Staff.id == employee.staff_id, db=db_session).data
if duties := Duties.filter_one(
Duties.id == staff.duties_id, db=db_session
).data:
if duty_found := Duty.filter_by_one(
id=duties.duties_id, db=db_session
).data:
duty_uu_id_list.append(str(duty_found.uu_id))
duty_id_list.append(duty_found.id)
department = Departments.filter_one(
Departments.id == duties.department_id, db=db_session
).data
if company := Companies.filter_one(
Companies.id == department.company_id, db=db_session
).data:
companies_uu_id_list.append(str(company.uu_id))
companies_id_list.append(company.id)
company_address = Addresses.filter_by_one(
id=company.official_address_id, db=db_session
).data
companies_list.append(
{
"uu_id": str(company.uu_id),
"public_name": company.public_name,
"company_type": company.company_type,
"company_address": company_address,
}
)
person = People.filter_one(People.id == user.person_id, db=db_session).data
model_value = EmployeeTokenObject(
domain=domain,
user_type=UserType.employee.value,
user_uu_id=str(user.uu_id),
credentials=user.credentials(),
user_id=user.id,
person_id=person.id,
person_uu_id=str(person.uu_id),
full_name=person.full_name,
request=dict(request.headers),
companies_uu_id_list=companies_uu_id_list,
companies_id_list=companies_id_list,
duty_uu_id_list=duty_uu_id_list,
duty_id_list=duty_id_list,
timezone=user.local_timezone or "GMT+0",
lang="tr",
).model_dump()
if access_token := cls.set_object_to_redis(user, model_value):
return {
"access_token": access_token,
"user_type": UserType.employee.name,
"selection_list": companies_list,
}
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Creating Token failed...",
)
@classmethod
def do_occupant_login(
cls, request: "Request", user: Users, domain: str
) -> Dict[str, Any]:
"""Handle occupant login process and return login information."""
db_session = BuildLivingSpace.new_session()
living_spaces: list[BuildLivingSpace] = BuildLivingSpace.filter_all(
BuildLivingSpace.person_id == user.person_id, db=db_session
).data
if not living_spaces:
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="User does not have any living space",
)
occupants_selection_dict: Dict[str, Any] = {}
for living_space in living_spaces:
build_parts_selection = BuildParts.filter_all(
BuildParts.id == living_space.build_parts_id,
db=db_session,
).data
if not build_parts_selection:
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="User does not have any living space",
)
build_part = build_parts_selection.get(1)
build = build_part.buildings
occupant_type = OccupantTypes.filter_by_one(
id=living_space.occupant_type,
db=db_session,
system=True,
).data
occupant_data = {
"part_uu_id": str(build_part.uu_id),
"part_name": build_part.part_name,
"part_level": build_part.part_level,
"uu_id": str(occupant_type.uu_id),
"description": occupant_type.occupant_description,
"code": occupant_type.occupant_code,
}
build_key = str(build.uu_id)
if build_key not in occupants_selection_dict:
occupants_selection_dict[build_key] = {
"build_uu_id": build_key,
"build_name": build.build_name,
"build_no": build.build_no,
"occupants": [occupant_data],
}
else:
occupants_selection_dict[build_key]["occupants"].append(occupant_data)
person = user.person
model_value = OccupantTokenObject(
domain=domain,
user_type=UserType.occupant.value,
user_uu_id=str(user.uu_id),
credentials=user.credentials(),
user_id=user.id,
person_id=person.id,
person_uu_id=str(person.uu_id),
full_name=person.full_name,
request=dict(request.headers),
available_occupants=occupants_selection_dict,
timezone=user.local_timezone or "GMT+0",
lang="tr",
).model_dump()
if access_token := cls.set_object_to_redis(user, model_value):
return {
"access_token": access_token,
"user_type": UserType.occupant.name,
"available_occupants": occupants_selection_dict,
}
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Creating Token failed...",
)
@classmethod
def set_object_to_redis(cls, user, model: Dict):
access_object = AccessToken(
userUUID=user.uu_id,
accessToken=cls._create_access_token(),
)
cls.remove_token_with_domain(user=user, domain=model.get("domain"))
redis_action = RedisActions.set_json(
list_keys=access_object.to_list(),
value=model,
expires={"seconds": int(Auth.TOKEN_EXPIRE_MINUTES_30.seconds)},
)
if redis_action.status:
return access_object.accessToken
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Saving Token failed...",
)
@classmethod
def update_object_to_redis(cls, access_token: str, user_uu_id: str, model: Dict):
access_object = AccessToken(
userUUID=user_uu_id,
accessToken=access_token,
)
redis_action = RedisActions.set_json(
list_keys=access_object.to_list(),
value=model,
expires={"seconds": int(Auth.TOKEN_EXPIRE_MINUTES_30.seconds)},
)
if redis_action.status:
return access_object.accessToken
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Saving Token failed...",
)
@classmethod
def remove_token_with_domain(cls, user: Users, domain: str) -> None:
"""Remove all tokens for a user with specific domain."""
redis_rows = cls._get_user_tokens(user)
for redis_row in redis_rows.all:
if redis_row.row.get("domain") == domain:
RedisActions.delete([redis_row.key])
@classmethod
def remove_all_token(cls, user: Users) -> None:
"""Remove all tokens for a user."""
redis_rows = cls._get_user_tokens(user)
RedisActions.delete([redis_row.key for redis_row in redis_rows.all])
@classmethod
def set_access_token_to_redis(
cls,
request: "Request",
user: Users,
domain: str,
remember: bool,
) -> Dict[str, Any]:
"""Set access token to redis and handle user session."""
from ApiLayers.AllConfigs.Token.config import Auth
from ApiLayers.Schemas.identity.identity import UsersTokens, People
cls.remove_token_with_domain(user=user, domain=domain)
# Users.client_arrow = DateTimeLocal(is_client=True, timezone=user.local_timezone)
login_dict, db_session = {}, UsersTokens.new_session()
if user.is_occupant: # Handle login based on user type
login_dict = cls.do_occupant_login(
request=request, user=user, domain=domain
)
elif user.is_employee:
login_dict = cls.do_employee_login(
request=request, user=user, domain=domain
)
# Handle remember me functionality
user.remember_me = bool(remember)
if remember:
users_token_created = cls._create_access_token(access=False)
login_dict["refresh_token"] = users_token_created
users_token = UsersTokens.find_or_create(
db=db_session,
user_id=user.id,
token_type="RememberMe",
domain=domain,
)
if users_token.meta_data.created:
users_token.token = users_token_created
users_token.save(db=db_session)
else:
if arrow.now() > arrow.get(
str(users_token.expires_at)
): # Check if token is expired
users_token.token = users_token_created
users_token.expires_at = str(
arrow.now().datetime + Auth.TOKEN_EXPIRE_DAY_1
)
users_token.save(db=db_session)
else:
login_dict["refresh_token"] = users_token.token
else:
already_refresher = UsersTokens.filter_all(
UsersTokens.user_id == user.id,
UsersTokens.token_type == "RememberMe",
UsersTokens.domain == domain,
db=db_session,
)
if already_refresher.count:
already_refresher.query.delete(synchronize_session=False)
user.save(db=db_session)
return {**login_dict, "user": user.get_dict()}
@classmethod
def update_token_at_redis(
cls, request: "Request", add_payload: Union[CompanyToken, OccupantToken]
) -> Dict[str, Any]:
"""Update token at Redis."""
access_token = cls.get_access_token_from_request(request=request)
token_object = cls.get_object_via_access_key(access_token=access_token)
if isinstance(token_object, EmployeeTokenObject) and isinstance(
add_payload, CompanyToken
):
token_object.selected_company = add_payload
cls.update_object_to_redis(
access_token=access_token,
user_uu_id=token_object.user_uu_id,
model=token_object.model_dump(),
)
return token_object.selected_company.model_dump()
elif isinstance(token_object, OccupantTokenObject) and isinstance(
add_payload, OccupantToken
):
token_object.selected_occupant = add_payload
cls.update_object_to_redis(
access_token=access_token,
user_uu_id=token_object.user_uu_id,
model=token_object.model_dump(),
)
return token_object.selected_occupant.model_dump()
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Token not found",
)
@classmethod
def raise_error_if_request_has_no_token(cls, request: "Request") -> None:
"""Validate request has required token headers."""
if not hasattr(request, "headers"):
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Request has no headers",
)
if not request.headers.get(Auth.ACCESS_TOKEN_TAG):
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Request has no access token presented",
)
@classmethod
def access_token_is_valid(cls, request: "Request") -> bool:
"""Check if access token in request is valid."""
access_token = cls.get_access_token_from_request(request=request)
return RedisActions.get_json(
list_keys=AccessToken(accessToken=access_token).to_list()
).status
@classmethod
def get_access_token_from_request(cls, request: "Request") -> str:
"""Extract access token from request headers."""
cls.raise_error_if_request_has_no_token(request=request)
return request.headers.get(Auth.ACCESS_TOKEN_TAG)
@classmethod
def _process_redis_object(cls, redis_object: Dict[str, Any]) -> T:
"""Process Redis object and return appropriate token object."""
if not redis_object.get("selected_company"):
redis_object["selected_company"] = None
if not redis_object.get("selected_occupant"):
redis_object["selected_occupant"] = None
if redis_object.get("user_type") == UserType.employee.value:
return EmployeeTokenObject(**redis_object)
elif redis_object.get("user_type") == UserType.occupant.value:
return OccupantTokenObject(**redis_object)
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Unknown user type",
)
@classmethod
def get_object_via_access_key(cls, access_token: str) -> T:
"""Get token object using access key."""
access_token_obj = AccessToken(accessToken=access_token)
redis_response = RedisActions.get_json(list_keys=access_token_obj.to_list())
if not redis_response.status:
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Access token token is not found or unable to retrieve",
)
if redis_object := redis_response.first:
access_token_obj.userUUID = redis_object.get("user_uu_id")
return cls._process_redis_object(redis_object)
@classmethod
def get_object_via_user_uu_id(cls, user_id: str) -> T:
"""Get token object using user UUID."""
access_token = AccessToken(userUUID=user_id)
redis_response = RedisActions.get_json(list_keys=access_token.to_list())
if redis_object := redis_response.first.row:
access_token.userUUID = redis_object.get("user_uu_id")
return cls._process_redis_object(redis_object)
raise HTTPExceptionApi(
error_code="",
lang="en",
loc=get_line_number_for_error(),
sys_msg="Invalid access token",
)

View File

@ -0,0 +1,5 @@
from ApiLayers.ApiServices.Token.token_handler import TokenService
__all__ = [
"TokenService",
]

View File

@ -0,0 +1,119 @@
import enum
from typing import Optional, List, Any
from pydantic import BaseModel
# Company / Priority / Department / Duty / Employee / Occupant / Module / Endpoint are changeable dynamics
class UserType(enum.Enum):
employee = 1
occupant = 2
class Credentials(BaseModel):
person_id: int
person_name: str
class ApplicationToken(BaseModel):
# Application Token Object -> is the main object for the user
domain: Optional[str] = "app.evyos.com.tr"
lang: Optional[str] = "TR"
timezone: Optional[str] = "GMT+3"
user_type: int = UserType.occupant.value
credentials: dict = None
user_uu_id: str
user_id: int
person_id: int
person_uu_id: str
full_name: Optional[str] = None
request: Optional[dict] = None # Request Info of Client
expires_at: Optional[float] = None # Expiry timestamp
class OccupantToken(BaseModel):
# Selection of the occupant type for a build part is made by the user
living_space_id: int # Internal use
living_space_uu_id: str # Outer use
occupant_type_id: int
occupant_type_uu_id: str
occupant_type: str
build_id: int
build_uuid: str
build_part_id: int
build_part_uuid: str
responsible_company_id: Optional[int] = None
responsible_company_uuid: Optional[str] = None
responsible_employee_id: Optional[int] = None
responsible_employee_uuid: Optional[str] = None
reachable_event_codes: Optional[list[str]] = None # ID list of reachable modules
class CompanyToken(BaseModel):
# Selection of the company for an employee is made by the user
company_id: int
company_uu_id: str
department_id: int # ID list of departments
department_uu_id: str # ID list of departments
duty_id: int
duty_uu_id: str
staff_id: int
staff_uu_id: str
employee_id: int
employee_uu_id: str
bulk_duties_id: int
reachable_event_codes: Optional[list[str]] = None # ID list of reachable modules
class OccupantTokenObject(ApplicationToken):
# Occupant Token Object -> Requires selection of the occupant type for a specific build part
available_occupants: dict = None
selected_occupant: Optional[OccupantToken] = None # Selected Occupant Type
@property
def is_employee(self) -> bool:
return False
@property
def is_occupant(self) -> bool:
return True
class EmployeeTokenObject(ApplicationToken):
# Full hierarchy Employee[staff_id] -> Staff -> Duty -> Department -> Company
companies_id_list: List[int] # List of company objects
companies_uu_id_list: List[str] # List of company objects
duty_id_list: List[int] # List of duty objects
duty_uu_id_list: List[str] # List of duty objects
selected_company: Optional[CompanyToken] = None # Selected Company Object
@property
def is_employee(self) -> bool:
return True
@property
def is_occupant(self) -> bool:
return False

View File

@ -0,0 +1,83 @@
import json
from typing import Any, ClassVar, TypeVar, Dict, Tuple, List
from pydantic import BaseModel
from ErrorHandlers import HTTPExceptionApi
from ApiLibrary.common.line_number import get_line_number_for_error
from ApiValidations.Request.base_validations import CrudRecords, PydanticBaseModel
class ValidationParser:
def __init__(self, active_validation: BaseModel):
self.core_validation = active_validation
self.annotations = active_validation.model_json_schema()
self.annotations = json.loads(json.dumps(self.annotations))
self.schema = {}
self.parse()
def parse(self):
from ApiValidations.Request.base_validations import (
CrudRecords,
PydanticBaseModel,
)
properties = dict(self.annotations.get("properties")).items()
total_class_annotations = {
**self.core_validation.__annotations__,
**PydanticBaseModel.__annotations__,
**CrudRecords.__annotations__,
}
for key, value in properties:
default, required, possible_types = (
dict(value).get("default", None),
True,
[],
)
if dict(value).get("anyOf", None):
for _ in dict(value).get("anyOf") or []:
type_opt = json.loads(json.dumps(_))
if not type_opt.get("type") == "null":
possible_types.append(type_opt.get("type"))
field_type = possible_types[0]
required = False
else:
field_type = dict(value).get("type", "string")
attribute_of_class = total_class_annotations.get(key, None)
aoc = str(attribute_of_class) if attribute_of_class else None
if attribute_of_class:
if aoc in ("<class 'str'>", "typing.Optional[str]"):
field_type, required = "string", aoc == "<class 'str'>"
elif aoc in ("<class 'int'>", "typing.Optional[int]"):
field_type, required = "integer", aoc == "<class 'int'>"
elif aoc in ("<class 'bool'>", "typing.Optional[bool]"):
field_type, required = "boolean", aoc == "<class 'bool'>"
elif aoc in ("<class 'float'>", "typing.Optional[float]"):
field_type, required = "float", aoc == "<class 'float'>"
elif aoc in (
"<class 'datetime.datetime'>",
"typing.Optional[datetime.datetime]",
):
field_type, required = (
"datetime",
aoc == "<class 'datetime.datetime'>",
)
self.schema[key] = {
"type": field_type,
"required": required,
"default": default,
}
class ValidationModel:
def __init__(self, response_model: BaseModel, language_model, language_models):
self.response_model = response_model
self.validation = None
self.headers = language_model
self.language_models = language_models
self.get_validation()
def get_validation(self) -> Tuple:
self.headers = self.language_models
self.validation = ValidationParser(self.response_model).schema

View File

@ -0,0 +1,28 @@
from typing import Optional, Any
from pydantic import BaseModel
class DefaultContext(BaseModel): ...
class EventContext(DefaultContext):
auth: Any
code: str
url: str
request: Optional[Any] = None
@property
def base(self) -> dict[str, Any]:
return {"url": self.url, "code": self.code}
class AuthContext(DefaultContext):
auth: Any
url: str
request: Optional[Any] = None
@property
def base(self) -> dict[str, Any]:
return {"url": self.url}

View File

@ -0,0 +1,239 @@
from .base_validations import (
BaseModelRegular,
PydanticBaseModel,
ListOptions,
CrudRecords,
)
from .address import (
InsertAddress,
UpdateAddress,
UpdatePostCode,
InsertPostCode,
SearchAddress,
)
from .application import (
SingleEnumUUID,
SingleEnumClassKey,
SingleEnumOnlyClass,
SingleOccupantTypeUUID,
SingleOccupantTypeClassKey,
)
from .area import (
InsertBuildArea,
InsertBuildSites,
UpdateBuildArea,
UpdateBuildSites,
)
from .authentication import (
Login,
Logout,
ChangePassword,
Remember,
Forgot,
CreatePassword,
OccupantSelection,
EmployeeSelection,
)
from .account_records import (
InsertAccountRecord,
UpdateAccountRecord,
)
from .build_living_space import (
InsertBuildLivingSpace,
UpdateBuildLivingSpace,
)
from .build_part import (
InsertBuildParts,
InsertBuildTypes,
UpdateBuildParts,
UpdateBuildTypes,
)
from .building import (
InsertBuild,
UpdateBuild,
)
from .company import (
MatchCompany2Company,
InsertCompany,
UpdateCompany,
)
from .decision_book import (
DecisionBookDecisionBookInvitations,
DecisionBookDecisionBookInvitationsUpdate,
DecisionBookDecisionBookInvitationsAttend,
DecisionBookDecisionBookInvitationsAssign,
UpdateDecisionBook,
UpdateBuildDecisionBookItems,
UpdateBuildDecisionBookItemDebits,
InsertBuildDecisionBookItems,
InsertBuildDecisionBookItemDebits,
InsertDecisionBookCompleted,
InsertDecisionBook,
InsertDecisionBookPerson,
ListDecisionBook,
RemoveDecisionBookPerson,
)
from .departments import (
DepartmentsPydantic,
)
from .employee import (
InsertDuties,
UpdateDuties,
InsertEmployees,
SelectDuties,
UnBindEmployees2People,
BindEmployees2People,
UpdateCompanyEmployees,
InsertCompanyEmployees,
InsertCompanyEmployeesSalaries,
InsertCompanyDuty,
UpdateCompanyEmployeesSalaries,
UpdateCompanyDuty,
)
from .events import (
# CreateEvents,
RegisterEvents2Employee,
RegisterEvents2Occupant,
)
from .people import (
UpdatePerson,
InsertPerson,
)
from .project_decision_book import (
InsertBuildDecisionBookProjectItemDebits,
UpdateBuildDecisionBookProjectItemDebits,
InsertBuildDecisionBookProjects,
UpdateBuildDecisionBookProjects,
InsertBuildDecisionBookProjectPerson,
UpdateBuildDecisionBookProjectPerson,
InsertBuildDecisionBookProjectItems,
UpdateBuildDecisionBookProjectItems,
ApprovalsBuildDecisionBookProjects,
)
from .rules import (
UpdateEndpointAccess,
UpdateEndpointAccessList,
InsertEndpointAccess,
CheckEndpointAccess,
)
from .services import (
RegisterServices2Employee,
RegisterServices2Occupant,
)
from .staff import (
InsertStaff,
SelectStaff,
)
from .user import (
InsertUsers,
UpdateUsers,
QueryUsers,
# ActiveUsers,
# ListUsers,
# DeleteUsers,
)
from .modules import (
RegisterModules2Occupant,
RegisterModules2Employee,
)
__all__ = [
"BaseModelRegular",
"PydanticBaseModel",
"ListOptions",
"CrudRecords",
"ListOptions",
"CrudRecords",
"PydanticBaseModel",
"BaseModelRegular",
"InsertAddress",
"UpdateAddress",
"UpdatePostCode",
"InsertPostCode",
"SearchAddress",
"SingleEnumUUID",
"SingleEnumClassKey",
"SingleEnumOnlyClass",
"SingleOccupantTypeUUID",
"SingleOccupantTypeClassKey",
"InsertBuildArea",
"InsertBuildSites",
"UpdateBuildArea",
"UpdateBuildSites",
"Login",
"Logout",
"ChangePassword",
"Remember",
"Forgot",
"CreatePassword",
"OccupantSelection",
"EmployeeSelection",
"InsertAccountRecord",
"UpdateAccountRecord",
"InsertBuildLivingSpace",
"UpdateBuildLivingSpace",
"InsertBuildParts",
"InsertBuildTypes",
"UpdateBuildParts",
"UpdateBuildTypes",
"InsertBuild",
"UpdateBuild",
"MatchCompany2Company",
"InsertCompany",
"UpdateCompany",
"DecisionBookDecisionBookInvitations",
"DecisionBookDecisionBookInvitationsUpdate",
"DecisionBookDecisionBookInvitationsAttend",
"DecisionBookDecisionBookInvitationsAssign",
"UpdateDecisionBook",
"UpdateBuildDecisionBookItems",
"UpdateBuildDecisionBookItemDebits",
"InsertBuildDecisionBookItems",
"InsertBuildDecisionBookItemDebits",
"InsertDecisionBookCompleted",
"InsertDecisionBook",
"InsertDecisionBookPerson",
"ListDecisionBook",
"RemoveDecisionBookPerson",
"DepartmentsPydantic",
"InsertDuties",
"UpdateDuties",
"InsertEmployees",
"SelectDuties",
"UnBindEmployees2People",
"BindEmployees2People",
"UpdateCompanyEmployees",
"InsertCompanyEmployees",
"InsertCompanyEmployeesSalaries",
"InsertCompanyDuty",
"UpdateCompanyEmployeesSalaries",
"UpdateCompanyDuty",
"RegisterEvents2Employee",
"RegisterEvents2Occupant",
"UpdatePerson",
"InsertPerson",
"InsertBuildDecisionBookProjectItems",
"UpdateBuildDecisionBookProjectItems",
"ApprovalsBuildDecisionBookProjects",
"InsertBuildDecisionBookProjectItemDebits",
"UpdateBuildDecisionBookProjectItemDebits",
"InsertBuildDecisionBookProjects",
"UpdateBuildDecisionBookProjects",
"InsertBuildDecisionBookProjectPerson",
"UpdateBuildDecisionBookProjectPerson",
"UpdateEndpointAccess",
"UpdateEndpointAccessList",
"InsertEndpointAccess",
"CheckEndpointAccess",
"RegisterServices2Employee",
"RegisterServices2Occupant",
"InsertStaff",
"SelectStaff",
"InsertUsers",
"UpdateUsers",
"QueryUsers",
"RegisterModules2Occupant",
"RegisterModules2Employee",
]

View File

@ -0,0 +1,159 @@
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
from typing import Optional
class AccountValidation:
tr = {
"iban": "IBAN Numarası",
"bank_date": "Bank Tarih",
"currency_value": "Para Değeri",
"bank_balance": "Banka Bakiye",
"currency": "Para Birimi",
"additional_balance": "Ek Bakiye",
"channel_branch": "Kanal Şubesi",
"process_name": "İşlem Adı",
"process_type": "İşlem Tipi",
"process_comment": "İşlem Yorum",
"bank_reference_code": "Banka Referans Kodu",
"add_comment_note": "Yorum Not",
"is_receipt_mail_send": "Fiş Mail Gönderildi",
"found_from": "Bulunduğu Yer",
"similarity": "Benzerlik",
"remainder_balance": "Kalan Bakiye",
"bank_date_y": "Bank Tarih Yıl",
"bank_date_m": "Bank Tarih Ay",
"bank_date_w": "Bank Tarih Hafta",
"bank_date_d": "Bank Tarih Gün",
"approving_accounting_record": "Onaylayan Muhasebe Kaydı",
"accounting_receipt_date": "Muhasebe Fiş Tarihi",
"accounting_receipt_number": "Muhasebe Fiş Numarası",
"approved_record": "Onaylanmış Kayıt",
"import_file_name": "İçe Aktarım Dosya Adı",
"receive_debit_uu_id": "Alacak UUID",
"budget_type_uu_id": "Bütçe Tipi UUID",
"company_uu_id": "Şirket UUID",
"send_company_uu_id": "Gönderen Şirket UUID",
"customer_id": "Müşteri ID",
"customer_uu_id": "Müşteri UUID",
"send_person_uu_id": "Gönderen Kişi UUID",
"approving_accounting_person_uu_id": "Onaylayan Muhasebe Kişi UUID",
"build_parts_uu_id": "Daire UUID",
"build_decision_book_uu_id": "Karar Defteri UUID",
}
en = {
"iban": "IBAN Number",
"bank_date": "Bank Date",
"currency_value": "Currency Value",
"bank_balance": "Bank Balance",
"currency": "Currency",
"additional_balance": "Additional Balance",
"channel_branch": "Channel Branch",
"process_name": "Process Name",
"process_type": "Process Type",
"process_comment": "Process Comment",
"bank_reference_code": "Bank Reference Code",
"add_comment_note": "Comment Note",
"is_receipt_mail_send": "Receipt Mail Send",
"found_from": "Found From",
"similarity": "Similarity",
"remainder_balance": "Remainder Balance",
"bank_date_y": "Bank Date Year",
"bank_date_m": "Bank Date Month",
"bank_date_w": "Bank Date Week",
"bank_date_d": "Bank Date Day",
"approving_accounting_record": "Approving Accounting Record",
"accounting_receipt_date": "Accounting Receipt Date",
"accounting_receipt_number": "Accounting Receipt Number",
"approved_record": "Approved Record",
"import_file_name": "Import File Name",
"receive_debit_uu_id": "Receive Debit UUID",
"budget_type_uu_id": "Budget Type UUID",
"company_uu_id": "Company UUID",
"send_company_uu_id": "Send Company UUID",
"customer_id": "Customer ID",
"customer_uu_id": "Customer UUID",
"send_person_uu_id": "Send Person UUID",
"approving_accounting_person_uu_id": "Approving Accounting Person UUID",
"build_parts_uu_id": "Build Parts UUID",
"build_decision_book_uu_id": "Build Decision Book UUID",
}
class InsertAccountRecord(BaseModelRegular, AccountValidation):
iban: str
bank_date: str
currency_value: float
bank_balance: float
currency: str
additional_balance: float
channel_branch: str
process_name: str
process_type: str
process_comment: str
bank_reference_code: str
add_comment_note: Optional[str] = None
is_receipt_mail_send: Optional[bool] = None
found_from: Optional[str] = None
similarity: Optional[float] = None
remainder_balance: Optional[float] = None
bank_date_y: Optional[int] = None
bank_date_m: Optional[int] = None
bank_date_w: Optional[int] = None
bank_date_d: Optional[int] = None
approving_accounting_record: Optional[bool] = None
accounting_receipt_date: Optional[str] = None
accounting_receipt_number: Optional[int] = None
approved_record: Optional[bool] = None
import_file_name: Optional[str] = None
# receive_debit_uu_id: Optional[str] = None
budget_type_uu_id: Optional[str] = None
company_uu_id: Optional[str] = None
send_company_uu_id: Optional[str] = None
customer_id: Optional[str] = None
customer_uu_id: Optional[str] = None
send_person_uu_id: Optional[str] = None
approving_accounting_person_uu_id: Optional[str] = None
build_parts_uu_id: Optional[str] = None
build_decision_book_uu_id: Optional[str] = None
class UpdateAccountRecord(PydanticBaseModel, AccountValidation):
iban: Optional[str] = None
bank_date: Optional[str] = None
currency_value: Optional[float] = None
bank_balance: Optional[float] = None
currency: Optional[str] = None
additional_balance: Optional[float] = None
channel_branch: Optional[str] = None
process_name: Optional[str] = None
process_type: Optional[str] = None
process_comment: Optional[str] = None
bank_reference_code: Optional[str] = None
add_comment_note: Optional[str] = None
is_receipt_mail_send: Optional[bool] = None
found_from: Optional[str] = None
similarity: Optional[float] = None
remainder_balance: Optional[float] = None
bank_date_y: Optional[int] = None
bank_date_m: Optional[int] = None
bank_date_w: Optional[int] = None
bank_date_d: Optional[int] = None
approving_accounting_record: Optional[bool] = None
accounting_receipt_date: Optional[str] = None
accounting_receipt_number: Optional[int] = None
approved_record: Optional[bool] = None
import_file_name: Optional[str] = None
receive_debit_uu_id: Optional[str] = None
budget_type_uu_id: Optional[str] = None
company_uu_id: Optional[str] = None
send_company_uu_id: Optional[str] = None
customer_id: Optional[str] = None
customer_uu_id: Optional[str] = None
send_person_uu_id: Optional[str] = None
approving_accounting_person_uu_id: Optional[str] = None
build_parts_uu_id: Optional[str] = None
build_decision_book_uu_id: Optional[str] = None

View File

@ -0,0 +1,128 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import PydanticBaseModel, ListOptions
from ApiLayers.ApiValidations.handler import BaseModelRegular
class PostCodeValidation:
tr = {
"post_code": "Posta Kodu",
"street_uu_id": "Sokak UUID",
}
en = {
"post_code": "Post Code",
"street_uu_id": "Street UUID",
}
class InsertPostCode(BaseModelRegular, PostCodeValidation):
street_uu_id: str
post_code: str
class UpdatePostCode(PydanticBaseModel, PostCodeValidation):
street_uu_id: Optional[str] = None
post_code: Optional[str] = None
class SearchAddressValidation:
tr = {
"search": "Ara",
"list_options": "Liste Seçenekleri",
}
en = {
"search": "Search",
"list_options": "List Options",
}
class SearchAddress(PydanticBaseModel, SearchAddressValidation):
search: str
list_options: ListOptions
class StreetValidation:
tr = {
"street_code": "Sokak Kodu",
"street_name": "Sokak Adı",
"postcode": "Posta Kodu",
"type_code": "Tip Kodu",
"type_description": "Tip Açıklaması",
"gov_code": "Devlet Kodu",
"address_geographic_uu_id": "Coğrafi UUID",
}
en = {
"street_code": "Street Code",
"street_name": "Street Name",
"postcode": "Post Code",
"type_code": "Type Code",
"type_description": "Type Description",
"gov_code": "Government Code",
"address_geographic_uu_id": "Address Geographic UUID",
}
class InsertStreet(PydanticBaseModel, StreetValidation):
street_code: str
street_name: str
postcode: str
type_code: Optional[str] = None
type_description: Optional[str] = None
gov_code: Optional[str] = None
address_geographic_uu_id: Optional[str] = None
class AddressValidation:
tr = {
"post_code_uu_id": "Posta Kodu UUID",
"comment_address": "Adres Yorumu",
"letter_address": "Mektup Adresi",
"build_number": "Bina Numarası",
"door_number": "Kapı Numarası",
"floor_number": "Kat Numarası",
"short_letter_address": "Kısa Mektup Adresi",
"latitude": "Enlem",
"longitude": "Boylam",
}
en = {
"post_code_uu_id": "Post Code UUID",
"comment_address": "Address Comment",
"letter_address": "Letter Address",
"build_number": "Build Number",
"door_number": "Door Number",
"floor_number": "Floor Number",
"short_letter_address": "Short Letter Address",
"latitude": "Latitude",
"longitude": "Longitude",
}
class InsertAddress(BaseModelRegular, AddressValidation):
post_code_uu_id: str
comment_address: Optional[str] = None
letter_address: Optional[str] = None
build_number: str
door_number: Optional[str] = None
floor_number: Optional[str] = None
short_letter_address: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None
class UpdateAddress(PydanticBaseModel, AddressValidation):
post_code_uu_id: Optional[str] = None
comment_address: Optional[str] = None
letter_address: Optional[str] = None
build_number: Optional[str] = None
door_number: Optional[str] = None
floor_number: Optional[str] = None
short_letter_address: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None

View File

@ -0,0 +1,69 @@
from ApiLayers.ApiValidations.Request import BaseModelRegular
class SingleEnumClassKeyValidation:
tr = {
"class_name": "Sınıf Adı",
"key_name": "Anahtar Adı",
}
en = {
"class_name": "Class Name",
"key_name": "Key Name",
}
class SingleEnumClassKey(BaseModelRegular):
class_name: str
key_name: str
class SingleEnumUUIDValidation:
tr = {
"uu_id": "UUID",
}
en = {
"uu_id": "UUID",
}
class SingleEnumUUID(BaseModelRegular):
uu_id: str
class SingleEnumOnlyClassValidation:
tr = {
"class_name": "Sınıf Adı",
}
en = {
"class_name": "Class Name",
}
class SingleEnumOnlyClass(BaseModelRegular):
class_name: str
class SingleOccupantTypeClassKeyValidation:
tr = {
"type_code": "Tip Kodu",
}
en = {
"type_code": "Type Code",
}
class SingleOccupantTypeClassKey(BaseModelRegular):
type_code: str
class SingleOccupantTypeUUIDValidation:
tr = {
"uu_id": "Görev UUID",
}
en = {
"uu_id": "Occupant UUID",
}
class SingleOccupantTypeUUID(BaseModelRegular):
uu_id: str

View File

@ -0,0 +1,73 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class BuildAreaValidation:
tr = {
"area_name": "Alan Adı",
"area_code": "Alan Kodu",
"area_type": "Alan Tipi",
"area_direction": "Alan Yönü",
"area_gross_size": "Brüt Alan",
"area_net_size": "Net Alan",
"width": "Genişlik",
"size": "En",
}
en = {
"area_name": "Area Name",
"area_code": "Area Code",
"area_type": "Area Type",
"area_direction": "Area Direction",
"area_gross_size": "Gross Size",
"area_net_size": "Net Size",
"width": "Width",
"size": "Size",
}
class InsertBuildArea(BaseModelRegular, BuildAreaValidation):
build_uu_id: str
area_name: str
area_code: str
area_type: str
area_direction: Optional[str] = None
area_gross_size: Optional[float] = None
area_net_size: Optional[float] = None
width: Optional[int] = None
size: Optional[int] = None
class UpdateBuildArea(PydanticBaseModel, BuildAreaValidation):
area_name: Optional[str] = None
area_code: Optional[str] = None
area_type: Optional[str] = None
area_direction: Optional[str] = None
area_gross_size: Optional[float] = None
area_net_size: Optional[float] = None
width: Optional[int] = None
size: Optional[int] = None
class BuildSites:
tr = {"address_uu_id": "Adres UU ID", "site_name": "Site Adı", "site_no": "Site No"}
en = {
"address_uu_id": "Address UU ID",
"site_name": "Site Name",
"site_no": "Site No",
}
class InsertBuildSites(BaseModelRegular, BuildSites):
address_uu_id: str
site_name: str
site_no: str
class UpdateBuildSites(PydanticBaseModel, BuildSites):
site_name: Optional[str] = None
site_no: Optional[str] = None

View File

@ -0,0 +1,174 @@
from ApiLayers.ApiValidations.Request import BaseModelRegular
from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
class ChangePasswordValidation:
tr = {"old_password": "Eski Şifre", "new_password": "Yeni Şifre"}
en = {"old_password": "Old Password", "new_password": "New Password"}
class ChangePassword(BaseModelRegular, ChangePasswordValidation):
old_password: str = Field(..., example="current123")
new_password: str = Field(..., example="newpass456")
model_config = ConfigDict(
json_schema_extra={
"example": {"old_password": "current123", "new_password": "newpass456"}
}
)
class CreatePasswordValidation:
tr = {
"password_token": "Şifre Token",
"password": "Şifre",
"re_password": "Şifre Tekrar",
}
en = {
"password_token": "Password Token",
"password": "Password",
"re_password": "Re-Password",
}
class CreatePassword(BaseModelRegular, CreatePasswordValidation):
password_token: str = Field(..., example="abc123token")
password: str = Field(..., example="newpass123")
re_password: str = Field(..., example="newpass123")
model_config = ConfigDict(
json_schema_extra={
"example": {
"password_token": "abc123token",
"password": "newpass123",
"re_password": "newpass123",
}
}
)
class OccupantSelection(BaseModel):
build_living_space_uu_id: str = Field(
..., example="987fcdeb-51a2-43e7-9876-543210987654"
)
model_config = ConfigDict(
json_schema_extra={
"example": [
{"company_uu_id": "abcdef12-3456-7890-abcd-ef1234567890"},
{"build_living_space_uu_id": "987fcdeb-51a2-43e7-9876-543210987654"},
],
}
)
@property
def is_employee(self):
return False
@property
def is_occupant(self):
return True
class EmployeeSelection(BaseModel):
company_uu_id: str = Field(..., example="abcdef12-3456-7890-abcd-ef1234567890")
model_config = ConfigDict(
json_schema_extra={
"example": [
{"company_uu_id": "abcdef12-3456-7890-abcd-ef1234567890"},
{"build_living_space_uu_id": "987fcdeb-51a2-43e7-9876-543210987654"},
],
}
)
@property
def is_employee(self):
return True
@property
def is_occupant(self):
return False
class LoginValidation:
tr = {
"domain": "Domain",
"access_key": "Erişim Anahtarı",
"password": "Şifre",
"remember_me": "Beni Hatırla",
}
en = {
"domain": "Domain",
"access_key": "Access Key",
"password": "Password",
"remember_me": "Remember Me",
}
class Login(BaseModelRegular, LoginValidation):
domain: str = Field(..., example="example.com")
access_key: str = Field(..., example="user@example.com")
password: str = Field(..., example="password123")
remember_me: Optional[bool] = Field(False, example=True)
model_config = ConfigDict(
json_schema_extra={
"example": {
"domain": "evyos.com.tr",
"access_key": "karatay.berkay.sup@evyos.com.tr",
"password": "string",
"remember_me": False,
}
}
)
class LogoutValidation:
tr = {"domain": "Domain"}
en = {"domain": "Domain"}
class Logout(BaseModelRegular, LogoutValidation):
domain: str = Field(..., example="example.com")
model_config = ConfigDict(json_schema_extra={"example": {"domain": "example.com"}})
class RememberValidation:
tr = {"domain": "Domain", "refresh_token": "Yenileme Anahtarı"}
en = {"domain": "Domain", "refresh_token": "Refresh Token"}
class Remember(BaseModelRegular, RememberValidation):
domain: str = Field(..., example="example.com")
refresh_token: str = Field(..., example="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
model_config = ConfigDict(
json_schema_extra={
"example": {
"domain": "example.com",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
}
}
)
class ForgotValidation:
tr = {"domain": "Domain", "access_key": "Erişim Anahtarı"}
en = {"domain": "Domain", "access_key": "Access Key"}
class Forgot(BaseModelRegular, ForgotValidation):
domain: str = Field(..., example="example.com")
access_key: str = Field(..., example="user@example.com")
model_config = ConfigDict(
json_schema_extra={
"example": {"domain": "example.com", "access_key": "user@example.com"}
}
)

View File

@ -0,0 +1,32 @@
from typing import Optional
from ApiLayers.ApiValidations.handler import BaseModelRegular
class ListOptions(BaseModelRegular):
page: Optional[int] = 1
size: Optional[int] = 10
order_field: Optional[list[str]] = None
order_type: Optional[list[str]] = None
query: Optional[dict] = None
class CrudRecords:
uu_id: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
created_by: Optional[str] = None
updated_by: Optional[str] = None
confirmed_by: Optional[str] = None
is_confirmed: Optional[bool] = None
active: Optional[bool] = None
is_notification_send: Optional[bool] = None
is_email_send: Optional[bool] = None
class PydanticBaseModel(BaseModelRegular):
active: Optional[bool] = None
deleted: Optional[bool] = None
expiry_starts: Optional[str] = None
# expiry_ends: Optional[str] = None
is_confirmed: Optional[bool] = None

View File

@ -0,0 +1,22 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular
# from api_validations.validations_request import (
# PydanticBaseModel,
# PydanticBaseModelValidation,
# )
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertBuildLivingSpace(BaseModelRegular):
person_uu_id: str
build_parts_uu_id: str
occupant_type_uu_id: str
expiry_starts: str
expiry_ends: Optional[str] = None
class UpdateBuildLivingSpace(PydanticBaseModel):
is_tenant_live: Optional[bool] = None
build_parts_uu_id: Optional[str] = None
person_uu_id: Optional[str] = None

View File

@ -0,0 +1,43 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertBuildTypes(BaseModelRegular):
function_code: str
type_code: str
lang: str
type_name: str
class UpdateBuildTypes(PydanticBaseModel): ...
class InsertBuildParts(BaseModelRegular):
build_uu_id: str
address_gov_code: str
part_no: int
part_level: int
build_part_type_uu_id: str
part_gross_size: Optional[int] = None
part_net_size: Optional[int] = None
default_accessory: Optional[str] = None
human_livable: Optional[bool] = False
part_direction_uu_id: Optional[str] = None
ref_id: Optional[str] = None
class UpdateBuildParts(PydanticBaseModel):
address_gov_code: Optional[str] = None
part_no: Optional[int] = None
part_level: Optional[int] = None
build_part_type_uu_id: Optional[str] = None
part_code: Optional[int] = None
part_gross_size: Optional[int] = None
part_net_size: Optional[int] = None
default_accessory: Optional[str] = None
human_livable: Optional[bool] = False
part_direction: Optional[str] = None
current_owner_person_uu_id: Optional[str] = None
current_tenant_person_uu_id: Optional[str] = None

View File

@ -0,0 +1,43 @@
from typing import Optional
from datetime import datetime
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertBuild(BaseModelRegular):
gov_address_code: str
build_name: str
build_types_uu_id: str
max_floor: int
underground_floor: int
address_uu_id: str
build_date: datetime
decision_period_date: datetime
tax_no: Optional[str] = None
lift_count: Optional[int] = None
heating_system: Optional[bool] = None
cooling_system: Optional[bool] = None
hot_water_system: Optional[bool] = None
block_service_man_count: Optional[int] = None
security_service_man_count: Optional[int] = None
garage_count: Optional[int] = None
class UpdateBuild(PydanticBaseModel):
gov_address_code: Optional[str] = None
build_name: Optional[str] = None
build_no: Optional[str] = None
build_types_uu_id: Optional[str] = None
max_floor: Optional[int] = None
underground_floor: Optional[int] = None
build_date: Optional[datetime] = None
tax_no: Optional[str] = None
lift_count: Optional[int] = None
heating_system: Optional[bool] = None
cooling_system: Optional[bool] = None
hot_water_system: Optional[bool] = None
block_service_man_count: Optional[int] = None
security_service_man_count: Optional[int] = None
garage_count: Optional[int] = None
address_uu_id: Optional[str] = None

View File

@ -0,0 +1,32 @@
from typing import Optional, List
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertCompany(BaseModelRegular):
formal_name: str
company_type: str
commercial_type: str
tax_no: str
public_name: Optional[str] = None
company_tag: Optional[str] = None
default_lang_type: Optional[str] = None
default_money_type: Optional[str] = None
official_address_uu_id: Optional[str] = None
# parent_uu_id: Optional[int] = None
class UpdateCompany(PydanticBaseModel):
company_uu_id: str
public_name: Optional[str] = None
formal_name: Optional[str] = None
tax_no: Optional[str] = None
company_tag: Optional[str] = None
default_lang_type: Optional[str] = None
default_money_type: Optional[str] = None
official_address_uu_id: Optional[str] = None
class MatchCompany2Company(PydanticBaseModel):
match_company_uu_id: List[str]
duty_uu_id: str
show_only: Optional[bool] = None

View File

@ -0,0 +1,116 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular
class ListOptionsValidation:
tr = {
"page": "Sayfa",
"size": "Boyut",
"order_field": "Sıralama Alanı",
"order_type": "Sıralama Türü",
"include_joins": "Alt İçerikleri",
"query": "Sorgu",
}
en = {
"page": "Page",
"size": "Size",
"order_field": "Order Field",
"order_type": "Order Type",
"include_joins": "Include Joins",
"query": "Query",
}
class ListOptions(BaseModelRegular, ListOptionsValidation):
page: Optional[int] = 1
size: Optional[int] = 10
order_field: Optional[str] = "id"
order_type: Optional[str] = "asc"
include_joins: Optional[list] = None
query: Optional[dict] = None
class CrudRecordValidation:
tr = {
"uu_id": "UUID",
"created_at": "Oluşturulma Tarihi",
"updated_at": "Güncellenme Tarihi",
"created_by": "Oluşturan",
"updated_by": "Güncelleyen",
"confirmed_by": "Onaylayan",
"is_confirmed": "Onay",
"expiry_starts": "Geçerlilik Başlangıç Tarihi",
"expiry_ends": "Geçerlilik Bitiş Tarihi",
"active": "Aktif",
"is_notification_send": "Bildirim Gönderildi",
"is_email_send": "E-posta Gönderildi",
}
en = {
"uu_id": "UUID",
"created_at": "Created At",
"updated_at": "Updated At",
"created_by": "Created By",
"updated_by": "Updated By",
"confirmed_by": "Confirmed By",
"is_confirmed": "Confirmed",
"expiry_starts": "Expiry Starts",
"expiry_ends": "Expiry Ends",
"active": "Active",
"is_notification_send": "Notification Send",
"is_email_send": "Email Send",
}
class CrudRecords:
uu_id: Optional[str] = None
created_at: Optional[str] = None
updated_at: Optional[str] = None
created_by: Optional[str] = None
updated_by: Optional[str] = None
confirmed_by: Optional[str] = None
is_confirmed: Optional[bool] = None
active: Optional[bool] = None
is_notification_send: Optional[bool] = None
is_email_send: Optional[bool] = None
class PydanticBaseModelValidation:
tr = {
"active": "Aktif",
"deleted": "Silinmiş",
"expiry_starts": "Geçerlilik Başlangıç Tarihi",
"expiry_ends": "Geçerlilik Bitiş Tarihi",
"is_confirmed": "Onay",
}
en = {
"active": "Active",
"deleted": "Deleted",
"expiry_starts": "Expiry Starts",
"expiry_ends": "Expiry Ends",
"is_confirmed": "Confirmed",
}
class PydanticBaseModel(BaseModelRegular):
active: Optional[bool] = None
deleted: Optional[bool] = None
expiry_starts: Optional[str] = None
# expiry_ends: Optional[str] = None
is_confirmed: Optional[bool] = None
class EndpointPydantic(BaseModelRegular):
data: Optional[dict] = None
class EndpointValidation(BaseModelRegular):
endpoint: Optional[str] = None
class PatchRecord(BaseModelRegular):
confirm: Optional[bool] = None
delete: Optional[bool] = None
active: Optional[bool] = None

View File

@ -0,0 +1,73 @@
import typing
from datetime import datetime
class ConvertField:
def __init__(self, match, default_val=None):
self.match = match
self.default_val = default_val
def typing_return(self):
typing_dict = {
"<class 'float'>": float,
"<class 'bool'>": bool,
"<class 'int'>": int,
"<class 'str'>": str,
"<class 'dict'>": dict,
"<class 'list'>": list,
"<class 'datetime.datetime'>": datetime,
"typing.Optional[datetime.datetime]": typing.Optional[datetime],
"typing.Optional[bool]": typing.Optional[bool],
"typing.Optional[list]": typing.Optional[list],
"typing.Optional[str]": typing.Optional[str],
"typing.Optional[int]": typing.Optional[int],
"typing.Optional[float]": typing.Optional[float],
"typing.Optional[dict]": typing.Optional[dict],
}
matches_with = typing_dict.get(self.match, typing.Optional[str])
default_value = getattr(self.default_val, "field_default_value", None)
return matches_with, default_value
#
# def create_model_from_database(model_id: typing.Union[int, str]):
# if isinstance(model_id, int):
# selected_model = Models.find_one(id=model_id)
# else:
# selected_model = Models.find_one(uu_id=str(model_id))
#
# if not selected_model:
# raise HTTPException(
# status_code=202,
# detail=f"Model {selected_model.model_name} not found in database. Please add model to api.",
# )
# pydantic_class = getattr(root_validates, selected_model.model_type, None)
# if not pydantic_class:
# raise HTTPException(
# status_code=202,
# detail=f"Pydantic class {selected_model.model_type} not found in database. Please add model to api.",
# )
#
# model_entities_records = ModelEntities.filter_all(
# ModelEntities.model_id == selected_model.id
# ).data
#
# if not model_entities_records:
# raise HTTPException(
# status_code=202,
# detail="Model has no entities registered. Please add entities to model.",
# )
#
# fields = {}
# for entity in model_entities_records:
# fields[entity.field_name] = ConvertField(
# entity.field_type, entity.field_default_value
# ).typing_return()
#
# return create_model(
# __model_name=selected_model.model_name, # pydantic_name(User)
# __module__=pydantic_class.__module__, # field_name(uu_id)
# **fields, # field_name = (field_type (Optional[str]), default_value(None))
# )

View File

@ -0,0 +1,114 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import (
BaseModelRegular,
PydanticBaseModel,
ListOptions,
)
class DecisionBookDecisionBookInvitations(BaseModelRegular):
build_decision_book_uu_id: str
message: str
planned_date: str
class DecisionBookDecisionBookInvitationsAttend(BaseModelRegular):
token: str
is_attend: bool
class DecisionBookDecisionBookInvitationsAssign(BaseModelRegular):
token: str
build_living_space_uu_id: str
occupant_type_uu_id: str
class DecisionBookDecisionBookInvitationsUpdate(PydanticBaseModel):
token: str
occupant_type_uu_id: Optional[str] = None
class ListDecisionBook(ListOptions):
build_decision_book_uu_id: Optional[str] = None
class InsertDecisionBook(PydanticBaseModel):
build_uu_id: str
decision_type: str
meeting_date: str
is_out_sourced: bool
resp_company_fix_wage: Optional[float] = None
resp_company_uu_id: Optional[str] = None
class InsertDecisionBookCompleted(BaseModelRegular):
build_decision_book_uu_id: str
meeting_completed_date: str
class InsertDecisionBookPerson(BaseModelRegular):
person_uu_id: str
build_decision_book_uu_id: str
management_typecode_uu_id: str
dues_discount_approval_date: Optional[str] = None
dues_fix_discount: Optional[float] = None
dues_percent_discount: Optional[int] = None
class UpdateDecisionBookPerson(PydanticBaseModel):
dues_fix_discount: Optional[float] = None
dues_percent_discount: Optional[int] = None
class RemoveDecisionBookPerson(PydanticBaseModel):
person_uu_id: str
build_decision_book_person_uu_id: str
class UpdateDecisionBook(PydanticBaseModel):
decision_book_pdf_path: Optional[str] = None
is_out_sourced: Optional[bool] = None
contact_agreement_path: Optional[str] = None
contact_agreement_date: Optional[str] = None
meeting_date: Optional[str] = None
decision_type: Optional[str] = None
resp_company_fix_wage: Optional[float] = None
resp_company_uu_id: Optional[str] = None
class InsertBuildDecisionBookItems(BaseModelRegular):
token: str
info_type_uu_id: str
item_comment: str
currency: Optional[str] = "TL"
unit_type: Optional[str] = "M2"
debit_start_date: Optional[str] = None
debit_end_date: Optional[str] = None
unit_price_is_fixed: Optional[bool] = False
unit_price: Optional[float] = 0.00
# build_decision_book_uu_id: str
# item_objection: Optional[str] = None
class UpdateBuildDecisionBookItems(PydanticBaseModel):
item_comment: Optional[str] = None
item_objection: Optional[str] = None
class InsertBuildDecisionBookItemDebits(BaseModelRegular):
build_decision_book_item_uu_id: str
dues_values: dict
# dues_types_uu_id: str
# decision_taken: Optional[bool] = None
class UpdateBuildDecisionBookItemDebits(PydanticBaseModel):
dues_types_uu_id: Optional[str] = None
dues_values: Optional[dict] = None
decision_taken: Optional[bool] = None

View File

@ -0,0 +1,20 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import PydanticBaseModel
class DepartmentsPydantic(PydanticBaseModel):
department_code: Optional[str]
department_name: Optional[str]
department_description: Optional[str] = None
company_uu_id: Optional[str] = None
parent_department_uu_id: Optional[int] = None
# class UpdateDepartments(PydanticBaseModel):
#
# department_code: Optional[str] = None
# department_name: Optional[str] = None
# department_description: Optional[str] = None
# company_uu_id: Optional[str] = None
# parent_department_uu_id: Optional[int] = None

View File

@ -0,0 +1,77 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class BindEmployees2People(PydanticBaseModel):
staff_uu_id: str
people_uu_id: str
expiry_starts: Optional[str] = None
class UnBindEmployees2People(PydanticBaseModel):
people_uu_id: str
expiry_ends: str
class InsertEmployees(BaseModelRegular):
staff_uu_id: str
people_uu_id: Optional[str] = None
class InsertCompanyDuty(BaseModelRegular):
duty_code: str
duty_name: str
duty_description: Optional[str] = None
class SelectDuties(BaseModelRegular):
duty_uu_id: Optional[str] = None
class InsertDuties(BaseModelRegular):
duties_uu_id: str
department_uu_id: str
is_default_duty: Optional[bool] = False
class UpdateDuties(PydanticBaseModel):
duties_uu_id: Optional[str] = None
department_uu_id: Optional[str] = None
is_default_duty: Optional[bool] = None
class UpdateCompanyDuty(PydanticBaseModel):
duty_code: Optional[str] = None
duty_name: Optional[str] = None
duty_description: Optional[str] = None
class InsertCompanyEmployeesSalaries(BaseModelRegular):
gross_salary: float
net_salary: float
start_date: str
stop_date: Optional[str] = None
people_id: int
class UpdateCompanyEmployeesSalaries(PydanticBaseModel):
gross_salary: Optional[float] = None
net_salary: Optional[float] = None
start_date: Optional[str] = None
stop_date: Optional[str] = None
people_id: Optional[int] = None
class InsertCompanyEmployees(BaseModelRegular):
employee_description: Optional[str] = None
person_uu_id: str
duty_uu_id: str
start_date: Optional[str] = None
stop_date: Optional[str] = None
class UpdateCompanyEmployees(PydanticBaseModel):
stop_date: Optional[str] = None
employee_description: Optional[str] = None

View File

@ -0,0 +1,37 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular
class RegisterEvents2EmployeeValidation:
tr = {
"event_uu_id_list": "Etkinlikler Listesi",
"employee_uu_id": "Çalışan UU ID",
}
en = {
"event_uu_id_list": "Event List",
"employee_uu_id": "Employee UU ID",
}
class RegisterEvents2Employee(BaseModelRegular, RegisterEvents2EmployeeValidation):
event_uu_id_list: list[str] = None
employee_uu_id: Optional[str] = None
class RegisterEvents2OccupantValidation:
tr = {
"event_uu_id_list": "Etkinlikler Listesi",
"build_part_uu_id": "Bina Parça UU ID",
"occupant_uu_id": "Apartman Sakini UU ID",
}
en = {
"event_uu_id_list": "Event List",
"build_part_uu_id": "Building Part UU ID",
"occupant_uu_id": "Occupant UU ID",
}
class RegisterEvents2Occupant(BaseModelRegular, RegisterEvents2OccupantValidation):
event_uu_id_list: list[str] = None
build_part_uu_id: Optional[str] = None
occupant_uu_id: Optional[str] = None

View File

@ -0,0 +1,36 @@
from ApiLayers.ApiValidations.Request import BaseModelRegular
class RegisterModules2OccupantValidation:
tr = {
"modules_uu_id": "Modül Listesi",
"occupant_uu_id": "Mülk Sahibi",
"build_part_uu_id": "Daire UUID",
}
en = {
"modules_uu_id": "Module List",
"occupant_uu_id": "Occupant",
"build_part_uu_id": "Flat UUID",
}
class RegisterModules2Occupant(BaseModelRegular, RegisterModules2OccupantValidation):
modules_uu_id: str
occupant_uu_id: str
build_part_uu_id: str
class RegisterModules2EmployeeValidation:
tr = {
"modules_uu_id": "Modül Listesi",
"employee_uu_id": "Çalışan",
}
en = {
"modules_uu_id": "Module List",
"employee_uu_id": "Employee",
}
class RegisterModules2Employee(BaseModelRegular, RegisterModules2EmployeeValidation):
modules_uu_id: str
employee_uu_id: str

View File

@ -0,0 +1,66 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertPerson(BaseModelRegular):
firstname: str
surname: str
sex_code: str
national_identity_id: str
middle_name: Optional[str] = None
father_name: Optional[str] = None
mother_name: Optional[str] = None
country_code: Optional[str] = "TR"
birth_place: Optional[str] = None
birth_date: Optional[str] = None
tax_no: Optional[str] = None
ref_id: Optional[str] = None
class UpdatePerson(PydanticBaseModel):
firstname: Optional[str] = None
surname: Optional[str] = None
middle_name: Optional[str]
father_name: Optional[str] = None
mother_name: Optional[str] = None
sex_code: Optional[str] = None
country_code: Optional[str] = None
national_identity_id: Optional[str] = None
birth_place: Optional[str] = None
birth_date: Optional[str] = None
tax_no: Optional[str] = None
#
# class QueryPeople(PydanticBaseModel):
# uu_id: Optional[str] = None
#
#
# class InsertPeople(PydanticBaseModel):
# key_id: Optional[str] = None
# query: Optional[dict] = None
# data: Optional[_InsertPerson] = None
#
#
# class UpdatePeople(PydanticBaseModel):
# key_id: Optional[str] = None
# query: Optional[QueryPeople] = None
# data: Optional[_UpdatePerson] = None
#
#
# class DeletePeople(PydanticBaseModel):
# key_id: Optional[str] = None
# query: Optional[List[QueryPeople]] = None
# data: Optional[dict] = None
#
#
# class ListPeople(PydanticBaseModel):
# key_id: Optional[str] = None
# query: Optional[QueryPeople] = None
# data: Optional[ListOptions] = None
#
#
# class ActivePeople(PydanticBaseModel):
# key_id: Optional[str] = None
# query: Optional[List[QueryPeople]] = None
# data: Optional[dict] = None

View File

@ -0,0 +1,99 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertBuildDecisionBookProjectItems(BaseModelRegular):
build_decision_book_project_uu_id: str
item_header: str
item_comment: str
attachment_pdf_path: Optional[str] = None
item_objection: Optional[str] = None
class UpdateBuildDecisionBookProjectItems(PydanticBaseModel):
item_header: Optional[str] = None
item_comment: Optional[str] = None
attachment_pdf_path: Optional[str] = None
item_estimated_cost: Optional[float] = None
build_decision_book_project_uu_id: Optional[str] = None
class InsertBuildDecisionBookProjectPerson(BaseModelRegular):
dues_percent_discount: Optional[int] = None
job_fix_wage: Optional[float] = None
bid_price: Optional[float] = None
decision_price: Optional[float] = None
build_decision_book_project_uu_id: str
living_space_uu_id: str
project_team_type_uu_id: str
class UpdateBuildDecisionBookProjectPerson(PydanticBaseModel):
dues_percent_discount: Optional[int] = None
job_fix_wage: Optional[float] = None
bid_price: Optional[float] = None
decision_price: Optional[float] = None
build_decision_book_project_uu_id: Optional[str] = None
living_space_uu_id: Optional[str] = None
project_team_type_uu_id: Optional[str] = None
class InsertBuildDecisionBookProjects(BaseModelRegular):
build_decision_book_item_uu_id: str
project_responsible_person_uu_id: str
project_name: str
project_start_date: str
project_stop_date: str
project_type: str
is_out_sourced: Optional[bool] = False
project_note: Optional[str] = None
decision_book_pdf_path: Optional[str] = None
resp_company_fix_wage: Optional[float] = None
contact_agreement_path: Optional[str] = None
contact_agreement_date: Optional[str] = None
meeting_date: Optional[str] = None
currency: Optional[str] = None
bid_price: Optional[float] = None
resp_company_uu_id: Optional[str] = None
class UpdateBuildDecisionBookProjects(PydanticBaseModel):
build_decision_book_project_uu_id: str
is_out_sourced: Optional[bool] = False
project_note: Optional[str] = None
# decision_book_pdf_path: Optional[str] = None
status_id: Optional[int] = None
resp_company_fix_wage: Optional[float] = None
contact_agreement_path: Optional[str] = None
contact_agreement_date: Optional[str] = None
contact_uu_id: Optional[str] = None
resp_company_uu_id: Optional[str] = None
approved_price: Optional[float] = None
class ApprovalsBuildDecisionBookProjects(PydanticBaseModel):
build_decision_book_project_uu_id: str
project_stop_date: str
status_code: Optional[int] = None
final_price_list: Optional[list[dict]] = (
None # {"date": "2021-01-01", "price": 1000}
)
class InsertBuildDecisionBookProjectItemDebits(PydanticBaseModel):
build_decision_book_project_item_uu_id: str
payment_date: str
dues_values: dict
is_official: Optional[bool] = False
discount_value: Optional[float] = None
discount_fix: Optional[float] = None
decision_taken: Optional[bool] = None
class UpdateBuildDecisionBookProjectItemDebits(PydanticBaseModel):
dues_values: Optional[str] = None
discount_value: Optional[float] = None
discount_fix: Optional[float] = None
decision_taken: Optional[bool] = None
is_official: Optional[bool] = None

View File

@ -0,0 +1,23 @@
from typing import Optional, List
from ApiLayers.ApiValidations.Request import BaseModelRegular
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class CheckEndpointAccess(BaseModelRegular):
endpoint: str
class InsertEndpointAccess(PydanticBaseModel):
duty_uu_id: str
endpoint_restriction_list_uu_ids: list
class UpdateEndpointAccess(PydanticBaseModel):
endpoint_restriction_uu_id: Optional[str] = None
deleted: Optional[bool] = None
active: Optional[bool] = None
is_confirmed: Optional[bool] = None
class UpdateEndpointAccessList(PydanticBaseModel):
endpoint_restriction_list: List[UpdateEndpointAccess]

View File

@ -0,0 +1,36 @@
from ApiLayers.ApiValidations.Request import BaseModelRegular
class RegisterServices2OccupantValidation:
tr = {
"service_uu_id": "Hizmet UUID",
"occupant_uu_id": "Müşteri UUID",
"build_part_uu_id": "Bina Parça UUID",
}
en = {
"service_uu_id": "Service UUID",
"occupant_uu_id": "Occupant UUID",
"build_part_uu_id": "Building Part UUID",
}
class RegisterServices2Occupant(BaseModelRegular, RegisterServices2OccupantValidation):
service_uu_id: str
occupant_uu_id: str
build_part_uu_id: str
class RegisterServices2EmployeeValidation:
tr = {
"service_uu_id": "Hizmet UUID",
"employee_uu_id": "Personel UUID",
}
en = {
"service_uu_id": "Service UUID",
"employee_uu_id": "Employee UUID",
}
class RegisterServices2Employee(BaseModelRegular, RegisterServices2EmployeeValidation):
service_uu_id: str
employee_uu_id: str

View File

@ -0,0 +1,39 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import BaseModelRegular, PydanticBaseModel
class InsertStaffValidation:
tr = {
"staff_name": "Kadro Adı",
"staff_description": "Kadro Açıklaması",
"staff_code": "Kadro Kodu",
"duties_uu_id": "Görev UUID",
}
en = {
"staff_name": "Staff Name",
"staff_description": "Staff Description",
"staff_code": "Staff Code",
"duties_uu_id": "Duties UUID",
}
class InsertStaff(BaseModelRegular, InsertStaffValidation):
staff_name: str
staff_description: Optional[str] = None
staff_code: Optional[str] = None
duties_uu_id: str
class SelectStaffValidation:
tr = {
"duties_uu_id": "Görev UUID",
}
en = {
"duties_uu_id": "Duties UUID",
}
class SelectStaff(PydanticBaseModel, SelectStaffValidation):
duties_uu_id: str

View File

@ -0,0 +1,68 @@
from typing import Optional
from ApiLayers.ApiValidations.Request import PydanticBaseModel
class InsertUsersValidation:
tr = {
"people_uu_id": "Kişi UUID",
"user_tag": "Kullanıcı Etiketi",
"email": "E-posta",
"phone_number": "Telefon Numarası",
"avatar": "Avatar",
}
en = {
"people_uu_id": "People UUID",
"user_tag": "User Tag",
"email": "Email",
"phone_number": "Phone Number",
"avatar": "Avatar",
}
class InsertUsers(PydanticBaseModel, InsertUsersValidation):
people_uu_id: str
user_tag: str
email: Optional[str] = None
phone_number: Optional[str] = None
avatar: Optional[str] = None
class UpdateUsersValidation:
tr = {
"people_uu_id": "Kişi UUID",
"nick_name": "Kullanıcı Etiketi",
"domain_name": "Domain Adı",
"email": "E-posta",
"phone_number": "Telefon Numarası",
"avatar": "Avatar",
}
en = {
"people_uu_id": "People UUID",
"nick_name": "User Tag",
"domain_name": "Domain Name",
"email": "Email",
"phone_number": "Phone Number",
"avatar": "Avatar",
}
class UpdateUsers(PydanticBaseModel, UpdateUsersValidation):
people_uu_id: Optional[str] = None
nick_name: Optional[str] = None
domain_name: Optional[str] = None
email: Optional[str] = None
phone_number: Optional[str] = None
avatar: Optional[str] = None
class QueryUsersValidation:
tr = {
"uu_id": "UUID",
}
en = {
"uu_id": "UUID",
}
class QueryUsers(PydanticBaseModel):
uu_id: Optional[str] = None

View File

@ -0,0 +1,16 @@
from .account_responses import AccountRecordResponse
from .address_responses import ListAddressResponse
from .auth_responses import (
AuthenticationLoginResponse,
AuthenticationRefreshResponse,
AuthenticationUserInfoResponse,
)
__all__ = [
"AccountRecordResponse",
"ListAddressResponse",
"AuthenticationLoginResponse",
"AuthenticationRefreshResponse",
"AuthenticationUserInfoResponse",
]

View File

@ -0,0 +1,260 @@
from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime
from decimal import Decimal
from uuid import UUID
from pydantic import BaseModel
class AccountBooksResponse(BaseModel):
"""Response model for account books"""
country: str
branch_type: int
company_id: int
company_uu_id: str
branch_id: Optional[int]
branch_uu_id: Optional[str]
class AccountCodesResponse(BaseModel):
"""Response model for account codes"""
account_code: str
comment_line: str
is_receive_or_debit: bool
product_id: int = 0
nvi_id: str = ""
status_id: int = 0
account_code_seperator: str = "."
system_id: int = 0
locked: bool = False
company_id: Optional[int]
company_uu_id: str
customer_id: Optional[int]
customer_uu_id: str
person_id: Optional[int]
person_uu_id: str
class AccountCodeParserResponse(BaseModel):
"""Response model for account code parser"""
account_code_1: str
account_code_2: str
account_code_3: str
account_code_4: str = ""
account_code_5: str = ""
account_code_6: str = ""
account_code_id: int
account_code_uu_id: str
class AccountMasterResponse(BaseModel):
"""Response model for account master"""
doc_date: datetime
plug_type: str
plug_number: int
special_code: str = ""
authorization_code: str = ""
doc_code: str = ""
doc_type: int = 0
comment_line1: str = ""
comment_line2: str = ""
comment_line3: str = ""
comment_line4: str = ""
comment_line5: str = ""
comment_line6: str = ""
project_code: str = ""
module_no: str = ""
journal_no: int = 0
status_id: int = 0
canceled: bool = False
print_count: int = 0
total_active: Decimal = Decimal("0")
total_passive: Decimal = Decimal("0")
total_active_1: Decimal = Decimal("0")
total_passive_1: Decimal = Decimal("0")
total_active_2: Decimal = Decimal("0")
total_passive_2: Decimal = Decimal("0")
total_active_3: Decimal = Decimal("0")
total_passive_3: Decimal = Decimal("0")
total_active_4: Decimal = Decimal("0")
total_passive_4: Decimal = Decimal("0")
cross_ref: int = 0
data_center_id: str = ""
data_center_rec_num: int = 0
account_header_id: int
account_header_uu_id: str
project_item_id: Optional[int]
project_item_uu_id: Optional[str]
department_id: Optional[int]
department_uu_id: Optional[str]
class AccountDetailResponse(BaseModel):
"""Response model for account detail"""
doc_date: datetime
line_no: int
receive_debit: str
debit: Decimal
department: str = ""
special_code: str = ""
account_ref: int = 0
account_fiche_ref: int = 0
center_ref: int = 0
general_code: str = ""
credit: Decimal = Decimal("0")
currency_type: str = "TL"
exchange_rate: Decimal = Decimal("0")
debit_cur: Decimal = Decimal("0")
credit_cur: Decimal = Decimal("0")
discount_cur: Decimal = Decimal("0")
amount: Decimal = Decimal("0")
cross_account_code: str = ""
inf_index: Decimal = Decimal("0")
not_inflated: int = 0
not_calculated: int = 0
comment_line1: str = ""
comment_line2: str = ""
comment_line3: str = ""
comment_line4: str = ""
comment_line5: str = ""
comment_line6: str = ""
owner_acc_ref: int = 0
from_where: int = 0
orj_eid: int = 0
canceled: int = 0
cross_ref: int = 0
data_center_id: str = ""
data_center_rec_num: str = "0"
status_id: int = 0
plug_type_id: Optional[int]
plug_type_uu_id: str
account_header_id: int
account_header_uu_id: str
account_code_id: int
account_code_uu_id: str
account_master_id: int
account_master_uu_id: str
project_id: Optional[int]
project_uu_id: Optional[str]
class AccountRecordResponse(BaseModel):
"""Response model for account financial records.
This model represents a financial transaction record in the system,
including bank transaction details, amounts, and related metadata.
Attributes:
iban (str): International Bank Account Number
bank_date (datetime): Date when the transaction occurred at the bank
currency_value (Decimal): Original transaction amount
bank_balance (Decimal): Account balance after the transaction
currency (str): Currency code (e.g., "TRY", "USD")
additional_balance (Decimal): Any additional balance adjustments
channel_branch (str): Bank branch or channel where transaction occurred
process_name (str): Name/type of the transaction
process_type (str): Classification of the transaction
process_comment (str): Additional transaction details or notes
bank_reference_code (str): Bank's reference code for the transaction
add_comment_note (Optional[str]): Additional internal notes
is_receipt_mail_send (Optional[bool]): Whether receipt was emailed
found_from (Optional[str]): Source of the transaction record
similarity (Optional[float]): Matching confidence for duplicate detection
remainder_balance (Optional[Decimal]): Remaining balance if partial
bank_date_y (Optional[int]): Year of bank transaction
bank_date_m (Optional[int]): Month of bank transaction
bank_date_w (Optional[int]): Week of bank transaction
bank_date_d (Optional[int]): Day of bank transaction
approving_accounting_record (Optional[bool]): Accounting approval status
accounting_receipt_date (Optional[datetime]): When receipt was processed
accounting_receipt_number (Optional[int]): Receipt reference number
approved_record (Optional[bool]): Whether record is approved
import_file_name (Optional[str]): Source file if imported
receive_debit_uu_id (Optional[str]): Related debit record ID
budget_type_uu_id (Optional[str]): Associated budget type ID
company_uu_id (Optional[str]): Associated company ID
send_company_uu_id (Optional[str]): Sending company ID
customer_id (Optional[str]): Associated customer ID
customer_uu_id (Optional[str]): Associated customer UUID
send_person_uu_id (Optional[str]): Sending person ID
approving_accounting_person_uu_id (Optional[str]): Approver ID
build_parts_uu_id (Optional[str]): Related building part ID
build_decision_book_uu_id (Optional[str]): Related decision book ID
"""
iban: str
bank_date: datetime
currency_value: Decimal
bank_balance: Decimal
currency: str = "TRY"
additional_balance: Decimal = Decimal("0")
channel_branch: str
process_name: str
process_type: str
process_comment: str
bank_reference_code: str
add_comment_note: Optional[str]
is_receipt_mail_send: Optional[bool] = False
found_from: Optional[str]
similarity: Optional[float]
remainder_balance: Optional[Decimal]
bank_date_y: Optional[int]
bank_date_m: Optional[int]
bank_date_w: Optional[int]
bank_date_d: Optional[int]
approving_accounting_record: Optional[bool]
accounting_receipt_date: Optional[datetime]
accounting_receipt_number: Optional[int]
approved_record: Optional[bool]
import_file_name: Optional[str]
receive_debit_uu_id: Optional[str]
budget_type_uu_id: Optional[str]
company_uu_id: Optional[str]
send_company_uu_id: Optional[str]
customer_id: Optional[str]
customer_uu_id: Optional[str]
send_person_uu_id: Optional[str]
approving_accounting_person_uu_id: Optional[str]
build_parts_uu_id: Optional[str]
build_decision_book_uu_id: Optional[str]
class AccountRecordExchangeResponse(BaseModel):
"""Response model for currency exchange records.
This model represents a currency exchange transaction, tracking
exchange rates and converted amounts for financial records.
Attributes:
account_record_id (int): ID of the related account record
account_record_uu_id (str): UUID of the related account record
exchange_rate (Decimal): Applied exchange rate
exchange_currency (str): Target currency code
exchange_value (Decimal): Converted amount
exchange_date (datetime): When the exchange was calculated
"""
account_record_id: int
account_record_uu_id: str
exchange_rate: Decimal
exchange_currency: str = "TRY"
exchange_value: Decimal
exchange_date: datetime
class AccountRecordsListResponse(BaseModel):
"""Response model for account records list endpoint"""
uu_id: UUID
account_name: str
account_code: str
company_id: int
company_uu_id: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False

View File

@ -0,0 +1,20 @@
from typing import Optional
from pydantic import BaseModel
class ListAddressResponse(BaseModel):
build_number: Optional[str] = None
door_number: Optional[str] = None
floor_number: Optional[str] = None
comment_address: Optional[str] = None
letter_address: Optional[str] = None
short_letter_address: Optional[str] = None
latitude: Optional[float] = None
longitude: Optional[float] = None
street_uu_id: Optional[str] = None
class AddressPostCodeResponse:
street_id: Optional[int] = None
street_uu_id: Optional[str] = None
postcode: Optional[str] = None

View File

@ -0,0 +1,36 @@
from pydantic import BaseModel
from typing import Optional, List, Dict, Any
from datetime import datetime
from uuid import UUID
class AuthenticationLoginResponse(BaseModel):
"""Response model for authentication login endpoint"""
token: str
refresh_token: str
token_type: str
expires_in: int
user_info: Dict[str, Any]
class AuthenticationRefreshResponse(BaseModel):
"""Response model for authentication refresh endpoint"""
token: str
refresh_token: str
token_type: str
expires_in: int
class AuthenticationUserInfoResponse(BaseModel):
"""Response model for authentication user info endpoint"""
user_id: int
username: str
email: str
first_name: str
last_name: str
is_active: bool
created_at: datetime
updated_at: Optional[datetime]

View File

@ -0,0 +1,105 @@
from pydantic import BaseModel
from typing import Optional, TypeVar, Generic, List
from datetime import datetime
from uuid import UUID
T = TypeVar("T")
class BaseResponse(BaseModel):
"""Base response model that all response models inherit from.
This model provides common fields that are present in all database records,
including tracking information (created/updated timestamps), user actions
(created by, updated by, confirmed by), and record status (active, deleted).
Attributes:
uu_id (str): Unique identifier for the record, typically a UUID
created_at (datetime): Timestamp when the record was created
updated_at (Optional[datetime]): Timestamp when the record was last updated
created_by (Optional[str]): Username or identifier of the user who created the record
updated_by (Optional[str]): Username or identifier of the user who last updated the record
confirmed_by (Optional[str]): Username or identifier of the user who confirmed the record
is_confirmed (Optional[bool]): Whether the record has been confirmed/approved
active (Optional[bool]): Whether the record is currently active
deleted (Optional[bool]): Whether the record has been marked as deleted
expiry_starts (Optional[datetime]): When the record becomes valid/active
expiry_ends (Optional[datetime]): When the record expires/becomes inactive
is_notification_send (Optional[bool]): Whether notifications have been sent for this record
is_email_send (Optional[bool]): Whether emails have been sent for this record
"""
uu_id: str
created_at: datetime
updated_at: Optional[datetime]
created_by: Optional[str]
updated_by: Optional[str]
confirmed_by: Optional[str]
is_confirmed: Optional[bool] = None
active: Optional[bool] = True
deleted: Optional[bool] = False
expiry_starts: Optional[datetime]
expiry_ends: Optional[datetime]
is_notification_send: Optional[bool] = False
is_email_send: Optional[bool] = False
class Config:
"""Pydantic configuration for the base response model.
Attributes:
from_attributes (bool): Enables ORM mode for SQLAlchemy integration
"""
from_attributes = True
class CrudCollection(BaseModel, Generic[T]):
"""Base collection model for paginated responses.
This model is used to return collections of items with pagination information.
It is generic over the type of items in the collection, allowing it to be
used with any response model.
Type Parameters:
T: The type of items in the collection
Attributes:
page (int): Current page number, 1-based indexing
size (int): Number of items per page
total (int): Total number of items across all pages
order_field (str): Field used for sorting the collection
order_type (str): Sort direction ('asc' or 'desc')
items (List[T]): List of items in the current page
Example:
```python
class UserResponse(BaseResponse):
name: str
email: str
users = CrudCollection[UserResponse](
page=1,
size=10,
total=100,
order_field="name",
order_type="asc",
items=[...]
)
```
"""
page: int = 1
size: int = 10
total: int = 0
order_field: str = "id"
order_type: str = "asc"
items: List[T] = []
class Config:
"""Pydantic configuration for the collection model.
Attributes:
from_attributes (bool): Enables ORM mode for SQLAlchemy integration
"""
from_attributes = True

View File

@ -0,0 +1,90 @@
from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime
from uuid import UUID
from decimal import Decimal
from .base_responses import BaseResponse, CrudCollection
class DecisionBookBudgetBooksResponse(BaseResponse):
"""Response model for decision book budget books"""
country: str
branch_type: int = 0
company_id: int
company_uu_id: str
branch_id: Optional[int]
branch_uu_id: Optional[str]
build_decision_book_id: int
build_decision_book_uu_id: Optional[str]
class DecisionBookBudgetBooksCollection(
CrudCollection[DecisionBookBudgetBooksResponse]
):
"""Collection of decision book budget books"""
pass
class DecisionBookBudgetCodesResponse(BaseResponse):
"""Response model for decision book budget codes"""
budget_code: str
comment_line: str
budget_type: str
budget_code_seperator: str = "."
system_id: int = 0
locked: bool = False
company_id: Optional[int]
company_uu_id: str
customer_id: Optional[int]
customer_uu_id: str
class DecisionBookBudgetCodesCollection(
CrudCollection[DecisionBookBudgetCodesResponse]
):
"""Collection of decision book budget codes"""
pass
class DecisionBookBudgetMasterResponse(BaseResponse):
"""Response model for decision book budget master"""
budget_type: str
currency: str = "TRY"
total_budget: Decimal
tracking_period_id: Optional[int]
tracking_period_uu_id: Optional[str]
budget_books_id: int
budget_books_uu_id: Optional[str]
department_id: int
department_uu_id: Optional[str]
class DecisionBookBudgetMasterCollection(
CrudCollection[DecisionBookBudgetMasterResponse]
):
"""Collection of decision book budget masters"""
pass
class DecisionBookBudgetsResponse(BaseResponse):
"""Response model for decision book budgets"""
process_date: datetime
budget_codes_id: int
total_budget: Decimal
used_budget: Decimal = Decimal("0")
remaining_budget: Decimal = Decimal("0")
decision_book_budget_master_id: int
decision_book_budget_master_uu_id: Optional[str]
class DecisionBookBudgetsCollection(CrudCollection[DecisionBookBudgetsResponse]):
"""Collection of decision book budgets"""
pass

View File

@ -0,0 +1,309 @@
from typing import Optional, List, Generic
from datetime import datetime
from uuid import UUID
from decimal import Decimal
from api_validations.validations_response.base_responses import (
BaseResponse,
CrudCollection,
)
from api_validations.validations_request import PydanticBaseModel
class ListBuildingResponse(PydanticBaseModel):
gov_address_code: str
build_name: str
build_types_uu_id: Optional[str] = None
build_no: Optional[str] = None
max_floor: Optional[int] = None
underground_floor: Optional[int] = None
address_uu_id: Optional[str] = None
build_date: Optional[str] = None
decision_period_date: Optional[str] = None
tax_no: Optional[str] = None
lift_count: Optional[int] = None
heating_system: Optional[bool] = None
cooling_system: Optional[bool] = None
hot_water_system: Optional[bool] = None
block_service_man_count: Optional[int] = None
security_service_man_count: Optional[int] = None
garage_count: Optional[int] = None
site_uu_id: Optional[str] = None
class BuildAreaListResponse(BaseResponse):
"""Response model for building area list endpoint"""
uu_id: UUID
build_id: int
build_uu_id: str
area_name: str
area_value: float
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class BuildAreaListCollection(CrudCollection[BuildAreaListResponse]):
"""Collection of building area list"""
pass
class BuildSitesListResponse(BaseResponse):
"""Response model for building sites list endpoint"""
uu_id: UUID
address_id: int
site_name: str
site_value: float
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class BuildSitesListCollection(CrudCollection[BuildSitesListResponse]):
"""Collection of building sites list"""
pass
class BuildTypesListResponse(BaseResponse):
"""Response model for building types list endpoint"""
uu_id: UUID
type_name: str
type_value: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class BuildTypesListCollection(CrudCollection[BuildTypesListResponse]):
"""Collection of building types list"""
pass
class BuildTypesResponse(BaseResponse):
"""Response model for building types"""
function_code: str
type_code: str
lang: str = "TR"
class BuildTypesCollection(CrudCollection[BuildTypesResponse]):
"""Collection of building types"""
pass
class Part2EmployeeResponse(BaseResponse):
"""Response model for part to employee mapping"""
build_id: int
part_id: int
employee_id: int
class Part2EmployeeCollection(CrudCollection[Part2EmployeeResponse]):
"""Collection of part to employee mappings"""
pass
class RelationshipEmployee2BuildResponse(BaseResponse):
"""Response model for employee to build relationship"""
company_id: int
employee_id: int
member_id: int
relationship_type: Optional[str] = "Employee"
show_only: bool = False
class RelationshipEmployee2BuildCollection(
CrudCollection[RelationshipEmployee2BuildResponse]
):
"""Collection of employee to build relationships"""
pass
class BuildResponse(BaseResponse):
"""Response model for buildings"""
gov_address_code: str = ""
build_name: str
build_no: str
max_floor: int = 1
underground_floor: int = 0
build_date: datetime
decision_period_date: datetime
tax_no: str = ""
lift_count: int = 0
heating_system: bool = True
cooling_system: bool = False
hot_water_system: bool = False
block_service_man_count: int = 0
security_service_man_count: int = 0
garage_count: int = 0
management_room_id: Optional[int]
site_id: Optional[int]
site_uu_id: Optional[str]
address_id: int
address_uu_id: str
build_types_id: int
build_types_uu_id: Optional[str]
class BuildCollection(CrudCollection[BuildResponse]):
"""Collection of buildings"""
pass
class BuildPartsResponse(BaseResponse):
"""Response model for building parts"""
address_gov_code: str
part_no: int = 0
part_level: int = 0
part_code: str
part_gross_size: int = 0
part_net_size: int = 0
default_accessory: str = "0"
human_livable: bool = True
due_part_key: str
build_id: int
build_uu_id: str
part_direction_id: Optional[int]
part_direction_uu_id: Optional[str]
part_type_id: int
part_type_uu_id: str
class BuildPartsCollection(CrudCollection[BuildPartsResponse]):
"""Collection of building parts"""
pass
class BuildLivingSpaceResponse(BaseResponse):
"""Response model for building living space"""
fix_value: Decimal = Decimal("0")
fix_percent: Decimal = Decimal("0")
agreement_no: str = ""
marketing_process: bool = False
marketing_layer: int = 0
build_parts_id: int
build_parts_uu_id: str
person_id: int
person_uu_id: str
occupant_type: int
occupant_type_uu_id: str
class BuildLivingSpaceCollection(CrudCollection[BuildLivingSpaceResponse]):
"""Collection of building living spaces"""
pass
class BuildManagementResponse(BaseResponse):
"""Response model for building management"""
discounted_percentage: Decimal = Decimal("0.00")
discounted_price: Decimal = Decimal("0.00")
calculated_price: Decimal = Decimal("0.00")
occupant_type: int
occupant_type_uu_id: str
build_id: int
build_uu_id: str
build_parts_id: int
build_parts_uu_id: str
class BuildManagementCollection(CrudCollection[BuildManagementResponse]):
"""Collection of building management records"""
pass
class BuildAreaResponse(BaseResponse):
"""Response model for building area"""
area_name: str = ""
area_code: str = ""
area_type: str = "GREEN"
area_direction: str = "NN"
area_gross_size: Decimal = Decimal("0")
area_net_size: Decimal = Decimal("0")
width: int = 0
size: int = 0
build_id: int
build_uu_id: str
part_type_id: Optional[int]
part_type_uu_id: Optional[str]
class BuildAreaCollection(CrudCollection[BuildAreaResponse]):
"""Collection of building areas"""
pass
class BuildSitesResponse(BaseResponse):
"""Response model for building sites"""
site_name: str
site_no: str
address_id: int
address_uu_id: Optional[str]
class BuildSitesCollection(CrudCollection[BuildSitesResponse]):
"""Collection of building sites"""
pass
class BuildCompaniesProvidingResponse(BaseResponse):
"""Response model for building companies providing services"""
build_id: int
build_uu_id: Optional[str]
company_id: int
company_uu_id: Optional[str]
provide_id: Optional[int]
provide_uu_id: Optional[str]
contract_id: Optional[int]
class BuildCompaniesProvidingCollection(
CrudCollection[BuildCompaniesProvidingResponse]
):
"""Collection of building companies providing services"""
pass
class BuildPersonProvidingResponse(BaseResponse):
"""Response model for building person providing services"""
build_id: int
build_uu_id: Optional[str]
people_id: int
people_uu_id: Optional[str]
provide_id: Optional[int]
provide_uu_id: Optional[str]
contract_id: Optional[int]
class BuildPersonProvidingCollection(CrudCollection[BuildPersonProvidingResponse]):
"""Collection of building person providing services"""
pass

View File

@ -0,0 +1,59 @@
from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime
from uuid import UUID
class CompanyListResponse(BaseModel):
"""Response model for company list endpoint"""
uu_id: UUID
company_name: str
company_code: str
company_email: str
company_phone: str
company_address: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class CompanyDepartmentListResponse(BaseModel):
"""Response model for company department list endpoint"""
uu_id: UUID
department_name: str
department_code: str
company_id: int
company_uu_id: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class CompanyDutyListResponse(BaseModel):
"""Response model for company duty list endpoint"""
uu_id: UUID
duty_name: str
duty_code: str
department_id: int
department_uu_id: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False
class CompanyEmployeeListResponse(BaseModel):
"""Response model for company employee list endpoint"""
uu_id: UUID
employee_id: int
employee_uu_id: str
company_id: int
company_uu_id: str
duty_id: int
duty_uu_id: str
created_at: datetime
updated_at: Optional[datetime]
deleted: bool = False

View File

@ -0,0 +1,204 @@
from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime
from uuid import UUID
from decimal import Decimal
from .base_responses import BaseResponse, CrudCollection
class BuildDecisionBookResponse(BaseResponse):
"""Response model for building decision book"""
decision_book_pdf_path: Optional[str] = ""
resp_company_fix_wage: float = 0
contact_agreement_path: Optional[str] = ""
contact_agreement_date: Optional[datetime]
meeting_date: Optional[str]
decision_type: Optional[str]
class BuildDecisionBookCollection(CrudCollection[BuildDecisionBookResponse]):
"""Collection of building decision books"""
pass
class BuildDecisionBookInvitationsResponse(BaseResponse):
"""Response model for building decision book invitations"""
build_id: int
build_uu_id: Optional[str]
decision_book_id: int
decision_book_uu_id: Optional[str]
invitation_type: str
invitation_attempt: int = 1
living_part_count: int = 1
living_part_percentage: Decimal = Decimal("0.51")
message: Optional[str]
planned_date: datetime
planned_date_expires: datetime
class BuildDecisionBookInvitationsCollection(
CrudCollection[BuildDecisionBookInvitationsResponse]
):
"""Collection of building decision book invitations"""
pass
class BuildDecisionBookPersonResponse(BaseResponse):
"""Response model for building decision book person"""
dues_percent_discount: int = 0
dues_fix_discount: Decimal = Decimal("0")
dues_discount_approval_date: datetime
send_date: datetime
is_attending: bool = False
confirmed_date: Optional[datetime]
token: str = ""
vicarious_person_id: Optional[int]
vicarious_person_uu_id: Optional[str]
invite_id: int
invite_uu_id: str
build_decision_book_id: int
build_decision_book_uu_id: str
build_living_space_id: int
build_living_space_uu_id: Optional[str]
person_id: int
class BuildDecisionBookPersonCollection(
CrudCollection[BuildDecisionBookPersonResponse]
):
"""Collection of building decision book persons"""
pass
class BuildDecisionBookPersonOccupantsResponse(BaseResponse):
"""Response model for building decision book person occupants"""
build_decision_book_person_id: int
build_decision_book_person_uu_id: Optional[str]
invite_id: Optional[int]
invite_uu_id: Optional[str]
occupant_type_id: int
occupant_type_uu_id: Optional[str]
class BuildDecisionBookPersonOccupantsCollection(
CrudCollection[BuildDecisionBookPersonOccupantsResponse]
):
"""Collection of building decision book person occupants"""
pass
class BuildDecisionBookItemsResponse(BaseResponse):
"""Response model for building decision book items"""
item_order: int
item_comment: str
item_objection: Optional[str]
info_is_completed: bool = False
is_payment_created: bool = False
info_type_id: Optional[int]
info_type_uu_id: Optional[str]
build_decision_book_id: int
build_decision_book_uu_id: Optional[str]
item_short_comment: Optional[str]
class BuildDecisionBookItemsCollection(CrudCollection[BuildDecisionBookItemsResponse]):
"""Collection of building decision book items"""
pass
class BuildDecisionBookItemsUnapprovedResponse(BaseResponse):
"""Response model for building decision book items unapproved"""
item_objection: str
item_order: int
decision_book_item_id: int
decision_book_item_uu_id: Optional[str]
person_id: int
person_uu_id: Optional[str]
build_decision_book_item: int
build_decision_book_item_uu_id: Optional[str]
class BuildDecisionBookItemsUnapprovedCollection(
CrudCollection[BuildDecisionBookItemsUnapprovedResponse]
):
"""Collection of building decision book items unapproved"""
pass
class BuildDecisionBookPaymentsResponse(BaseResponse):
"""Response model for building decision book payments"""
payment_plan_time_periods: str
process_date: datetime
payment_amount: Decimal
currency: str = "TRY"
payment_types_id: Optional[int]
payment_types_uu_id: Optional[str]
period_time: str
process_date_y: int
process_date_m: int
build_decision_book_item_id: int
build_decision_book_item_uu_id: str
build_parts_id: int
build_parts_uu_id: str
decision_book_project_id: Optional[int]
decision_book_project_uu_id: Optional[str]
account_records_id: Optional[int]
account_records_uu_id: Optional[str]
class BuildDecisionBookPaymentsCollection(
CrudCollection[BuildDecisionBookPaymentsResponse]
):
"""Collection of building decision book payments"""
pass
class BuildDecisionBookLegalResponse(BaseResponse):
"""Response model for building decision book legal"""
period_start_date: datetime
lawsuits_decision_number: str
lawsuits_decision_date: datetime
period_stop_date: datetime
decision_book_pdf_path: Optional[str] = ""
resp_company_total_wage: Optional[Decimal] = Decimal("0")
contact_agreement_path: Optional[str] = ""
contact_agreement_date: Optional[datetime]
meeting_date: str
lawsuits_type: str = "C"
lawsuits_name: str
lawsuits_note: str
lawyer_cost: Decimal
mediator_lawyer_cost: Decimal
other_cost: Decimal
legal_cost: Decimal
approved_cost: Decimal
total_price: Decimal
build_db_item_id: int
build_db_item_uu_id: Optional[str]
resp_attorney_id: int
resp_attorney_uu_id: Optional[str]
resp_attorney_company_id: int
resp_attorney_company_uu_id: Optional[str]
mediator_lawyer_person_id: int
mediator_lawyer_person_uu_id: Optional[str]
class BuildDecisionBookLegalCollection(CrudCollection[BuildDecisionBookLegalResponse]):
"""Collection of building decision book legal records"""
pass

View File

@ -0,0 +1,160 @@
from typing import Optional
from fastapi import status
from fastapi.responses import JSONResponse
from ApiLayers.LanguageModels.set_defaults.static_validation_retriever import (
StaticValidationRetriever,
)
class BaseEndpointResponse(StaticValidationRetriever):
__abstract__ = True
pass
class EndpointSuccessResponse(BaseEndpointResponse): # 200 OK
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_200_OK,
content=dict(completed=True, **self.response, lang=self.lang, data=data),
)
class EndpointSuccessListResponse(BaseEndpointResponse): # 200 OK
def as_dict(self, data: Optional[dict] = None, pagination: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_200_OK,
content=dict(
completed=True,
**self.response,
lang=self.lang,
pagination=pagination,
data=data,
),
)
class EndpointCreatedResponse(BaseEndpointResponse): # 201 Created
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content=dict(completed=True, **self.response, lang=self.lang, data=data),
)
class EndpointAcceptedResponse(BaseEndpointResponse): # 202 Accepted
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_202_ACCEPTED,
content=dict(completed=True, **self.response, lang=self.lang, data=data),
)
class EndpointNotModifiedResponse(BaseEndpointResponse): # 304 Not Modified
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_304_NOT_MODIFIED,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointBadRequestResponse(BaseEndpointResponse): # 400 Bad Request
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=dict(completed=False, **self.response, lang=self.lang, data=data),
)
class EndpointUnauthorizedResponse(BaseEndpointResponse): # 401 Unauthorized
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointForbiddenResponse(BaseEndpointResponse): # 403 Forbidden
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_403_FORBIDDEN,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointNotFoundResponse(BaseEndpointResponse): # 404 Not Found
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointMethodNotAllowedResponse(BaseEndpointResponse): # 405 Method Not Allowed
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointNotAcceptableResponse(BaseEndpointResponse): # 406 Not Acceptable
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_406_NOT_ACCEPTABLE,
content=dict(completed=False, data=data, **self.response, lang=self.lang),
)
class EndpointConflictResponse(BaseEndpointResponse): # 409 Conflict
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointUnprocessableEntityResponse(
BaseEndpointResponse
): # 422 Unprocessable Entity
def as_dict(self, data: Optional[dict] = None):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=dict(completed=False, **self.response, lang=self.lang, data=data),
)
class EndpointTooManyRequestsResponse(BaseEndpointResponse): # 429 Too Many Requests
def __init__(self, retry_after: int, lang: str, code: str):
super().__init__(lang=lang, code=code)
self.retry_after = retry_after
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
headers={"Retry-After": str(self.retry_after)},
content=dict(completed=False, **self.response, lang=self.lang),
)
class EndpointInternalErrorResponse(BaseEndpointResponse): # 500 Internal Server Error
def as_dict(self):
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content=dict(completed=False, **self.response, lang=self.lang),
)

View File

@ -0,0 +1,52 @@
from typing import Optional
from api_validations.core_validations import BaseModelRegular
from api_validations.validations_request import (
CrudRecordValidation,
CrudRecords,
)
class LivingSpaceListValidation:
tr = {
**CrudRecordValidation.tr,
"fix_value": "Sabit Değer",
"fix_percent": "Sabit Yüzde",
"agreement_no": "Anlaşma No",
"marketing_process": "Pazarlama Süreci",
"marketing_layer": "Pazarlama Katmanı",
"build_parts_id": "Bölüm ID",
"build_parts_uu_id": "Bölüm UUID",
"person_id": "Sorumlu Kişi ID",
"person_uu_id": "Sorumlu Kişi UUID",
"occupant_type": "Kiracı Tipi",
"occupant_type_uu_id": "Kiracı Tipi UUID",
}
en = {
**CrudRecordValidation.en,
"fix_value": "Fixed Value",
"fix_percent": "Fixed Percent",
"agreement_no": "Agreement No",
"marketing_process": "Marketing Process",
"marketing_layer": "Marketing Layer",
"build_parts_id": "Part ID",
"build_parts_uu_id": "Part UUID",
"person_id": "Responsible Person ID",
"person_uu_id": "Responsible Person UUID",
"occupant_type": "Occupant Type",
"occupant_type_uu_id": "Occupant Type UUID",
}
class LivingSpaceListResponse(BaseModelRegular, CrudRecords, LivingSpaceListValidation):
fix_value: Optional[float] = None
fix_percent: Optional[float] = None
agreement_no: Optional[str] = None
marketing_process: Optional[str] = None
marketing_layer: Optional[str] = None
build_parts_id: Optional[int] = None
build_parts_uu_id: Optional[str] = None
person_id: Optional[int] = None
person_uu_id: Optional[str] = None
occupant_type: Optional[str] = None
occupant_type_uu_id: Optional[str] = None

View File

@ -0,0 +1,54 @@
from typing import Optional
from api_validations.core_validations import BaseModelRegular
from api_validations.validations_request import (
CrudRecordValidation,
CrudRecords,
)
class BuildPartsListValidation:
tr = {
**CrudRecordValidation.tr,
"address_gov_code": "Adres Kapı Kodu",
"part_no": "Bölüm No",
"part_level": "Bölüm Seviyesi",
"part_code": "Bölüm Kodu",
"part_gross": "Bölüm Brüt",
"part_net": "Bölüm Net",
"default_accessory": "Varsayılan Aksesuar",
"human_livable": "İnsan Yaşamı",
"due_part_key": "Sabit Ödeme Grubu",
"build_uu_id": "Bina UUID",
"part_direction_uu_id": "Bölüm Yönü UUID",
"part_type_uu_id": "Bölüm Tipi UUID",
}
en = {
**CrudRecordValidation.en,
"address_gov_code": "Address Government Code",
"part_no": "Part Number",
"part_level": "Part Level",
"part_code": "Part Code",
"part_gross": "Part Gross",
"part_net": "Part Net",
"default_accessory": "Default Accessory",
"human_livable": "Human Livable",
"due_part_key": "Constant Payment Group",
"build_uu_id": "Building UUID",
"part_direction_uu_id": "Part Direction UUID",
"part_type_uu_id": "Part Type UUID",
}
class BuildPartsListResponse(BaseModelRegular, CrudRecords, BuildPartsListValidation):
address_gov_code: Optional[str] = None
part_no: Optional[int] = None
part_level: Optional[int] = None
part_code: Optional[str] = None
part_gross: Optional[int] = None
part_net: Optional[int] = None
default_accessory: Optional[str] = None
human_livable: Optional[bool] = None
due_part_key: Optional[str] = None
build_uu_id: Optional[str] = None
part_direction_uu_id: Optional[str] = None
part_type_uu_id: Optional[str] = None

View File

@ -0,0 +1,57 @@
from typing import Optional
from api_validations.core_validations import BaseModelRegular
from api_validations.validations_request import (
CrudRecordValidation,
CrudRecords,
)
class PeopleListValidation:
tr = {
**CrudRecordValidation.tr,
"firstname": "Ad",
"surname": "Soyad",
"middle_name": "Orta İsim",
"sex_code": "Cinsiyet Kodu",
"person_ref": "Kişi Referansı",
"person_tag": "Kişi Etiketi",
"father_name": "Baba Adı",
"mother_name": "Anne Adı",
"country_code": "Ülke Kodu",
"national_identity_id": "Kimlik Numarası",
"birth_place": "Doğum Yeri",
"birth_date": "Doğum Tarihi",
"tax_no": "Vergi Numarası",
}
en = {
**CrudRecordValidation.en,
"firstname": "First Name",
"surname": "Surname",
"middle_name": "Middle Name",
"sex_code": "Sex Code",
"person_ref": "Person Reference",
"person_tag": "Person Tag",
"father_name": "Father's Name",
"mother_name": "Mother's Name",
"country_code": "Country Code",
"national_identity_id": "National Identity ID",
"birth_place": "Birth Place",
"birth_date": "Birth Date",
"tax_no": "Tax Number",
}
class PeopleListResponse(BaseModelRegular, CrudRecords, PeopleListValidation):
firstname: Optional[str] = None
surname: Optional[str] = None
middle_name: Optional[str] = None
sex_code: Optional[str] = None
person_ref: Optional[str] = None
person_tag: Optional[str] = None
father_name: Optional[str] = None
mother_name: Optional[str] = None
country_code: Optional[str] = None
national_identity_id: Optional[str] = None
birth_place: Optional[str] = None
birth_date: Optional[str] = None
tax_no: Optional[str] = None

View File

View File

@ -0,0 +1,58 @@
"""
Base validation models and utilities.
"""
from pydantic import BaseModel, ConfigDict
def rewrite_input_data(data):
"""Remove empty and None values from input data."""
return {
item[0]: item[1]
for item in data.items()
if not item[1] == "" and item[1] is not None
}
class BaseModelRegular(BaseModel):
"""Base model for all validation models with proper schema handling."""
model_config = ConfigDict(
json_schema_extra={"example": {}} # Will be populated by subclasses
)
def __init__(self, **kwargs):
super().__init__(**rewrite_input_data(kwargs))
def excluded_dump(self):
return self.model_dump(exclude_unset=True, exclude_none=True)
def dump(self):
return self.model_dump()
@classmethod
def model_json_schema(cls, *args, **kwargs):
"""Generate JSON schema with proper examples."""
schema = super().model_json_schema(*args, **kwargs)
# Add examples based on field types
if "properties" in schema:
example = {}
for field_name, field_schema in schema["properties"].items():
field_type = field_schema.get("type")
if field_type == "string":
example[field_name] = f"example_{field_name}"
elif field_type == "integer":
example[field_name] = 0
elif field_type == "number":
example[field_name] = 0.0
elif field_type == "boolean":
example[field_name] = False
elif field_type == "array":
example[field_name] = []
elif field_type == "object":
example[field_name] = {}
schema["example"] = example
return schema

View File

@ -0,0 +1,89 @@
import json
from typing import Any, Union, Awaitable
from pydantic import ValidationError
from fastapi import Request, WebSocket, status
from fastapi.responses import Response, JSONResponse
from ApiLayers.LanguageModels.Errors.merge_all_error_languages import (
MergedErrorLanguageModels,
)
from ApiLayers.ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
from ApiLayers.ErrorHandlers.bases import BaseErrorModelClass
def validation_exception_handler(request, exc: ValidationError) -> JSONResponse:
"""
{"message": [{
"type": "missing", "location": ["company_uu_id"], "message": "Field required",
"input": {"invalid_key_input": "e9869a25"}
}], "request": "http://0.0.0.0:41575/authentication/select", "title": "EmployeeSelection"
}
Validation error on pydantic model of each event validation
"""
validation_messages, validation_list = exc.errors() or [], []
for validation in validation_messages:
validation_list.append(
{
"type": dict(validation).get("type"),
"location": dict(validation).get("loc"),
"message": dict(validation).get(
"msg"
), # todo change message with language message
"input": dict(validation).get("input"),
}
)
error_response_dict = dict(
message=validation_list, request=str(request.url.path), title=exc.title
)
return JSONResponse(
content=error_response_dict, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY
)
class HTTPExceptionApiHandler:
def __init__(self, response_model: Any):
self.RESPONSE_MODEL: Any = response_model
@staticmethod
def retrieve_error_status_code(exc: HTTPExceptionApi) -> int:
error_by_codes = BaseErrorModelClass.retrieve_error_by_codes()
grab_status_code = error_by_codes.get(str(exc.error_code).upper(), 500)
return int(grab_status_code)
@staticmethod
def retrieve_error_message(exc: HTTPExceptionApi, error_languages) -> str:
from ApiLayers.ErrorHandlers import DEFAULT_ERROR
return error_languages.get(str(exc.error_code).upper(), DEFAULT_ERROR)
async def handle_exception(
self, request: Union[Request, WebSocket], exc: Exception
) -> Union[Response, Awaitable[None]]:
request_string = (
str(request.url) if isinstance(request, Request) else request.url.path
)
if isinstance(exc, HTTPExceptionApi):
error_languages = MergedErrorLanguageModels.get_language_models(
language=exc.lang
)
status_code = self.retrieve_error_status_code(exc)
error_message = self.retrieve_error_message(exc, error_languages)
return self.RESPONSE_MODEL(
status_code=int(status_code),
content={
"message": error_message,
"lang": exc.lang,
"request": request_string,
"loc": exc.loc,
},
)
return self.RESPONSE_MODEL(
status_code=500,
content={
"message": "Internal Server Error",
"lang": "def",
"request": request_string,
"loc": exc.loc,
},
) # Handle other exceptions with a generic 500 error

View File

@ -0,0 +1,32 @@
from Services.Redis.Actions.actions import RedisActions
from ApiLayers.AllConfigs.Redis.configs import RedisValidationKeys
class HTTPExceptionApi(Exception):
def __init__(self, error_code: str, lang: str, loc: str = "", sys_msg: str = ""):
"""
Initialize the HTTPExceptionApi class.
:param error_code: The error code. To retrieve the error message.
:param lang: The language. Catch error msg from redis.
:param loc: The location. To log where error occurred.
:param sys_msg: The system message. To log the error message.
"""
self.error_code = error_code
self.lang = lang
self.loc = loc
self.sys_msg = sys_msg
def retrieve_error_message_by_code_at_redis(self):
"""
Retrieve the error message from the redis by the error code.
"""
error_redis_key = (
f"{RedisValidationKeys.LANGUAGE_MODELS}:{RedisValidationKeys.ERRORCODES}"
)
error_message = RedisActions.get_json(list_keys=[error_redis_key, self.lang])
if error_message.status:
error_message_dict = error_message.first.as_dict
if error_message_dict.get(self.error_code, None):
return error_message_dict.get(self.error_code)
return f"System Message -> {self.sys_msg}"

View File

@ -0,0 +1,9 @@
from ApiLayers.ErrorHandlers.ErrorHandlers.api_exc_handler import (
HTTPExceptionApiHandler,
)
from ApiLayers.ErrorHandlers.Exceptions.api_exc import HTTPExceptionApi
DEFAULT_ERROR = "UNKNOWN_ERROR"
__all__ = ["HTTPExceptionApiHandler", "HTTPExceptionApi", "DEFAULT_ERROR"]

View File

@ -0,0 +1,13 @@
class BaseError:
NOT_CREATED: int = 405
NOT_DELETED: int = 405
NOT_UPDATED: int = 405
NOT_LISTED: int = 404
NOT_FOUND: int = 404
ALREADY_EXISTS: int = 400
IS_NOT_CONFIRMED: int = 405
NOT_AUTHORIZED: int = 401
NOT_VALID: int = 406
NOT_ACCEPTABLE: int = 406
INVALID_DATA: int = 422
UNKNOWN_ERROR: int = 502

View File

@ -0,0 +1,18 @@
from ApiLayers.ErrorHandlers.base import BaseError
from ApiLayers.ErrorHandlers.statuses import Statuses
class BaseErrorModelClass:
list_of_statuses = [Statuses, BaseError]
@classmethod
def retrieve_error_by_codes(cls):
language_model_status = {}
for list_of_language in cls.list_of_statuses:
clean_dict = {
key: value
for key, value in list_of_language.__dict__.items()
if "__" not in str(key)[0:3]
}
language_model_status.update(clean_dict)
return language_model_status

View File

@ -0,0 +1,58 @@
class Statuses:
HTTP_100_CONTINUE = 100
HTTP_101_SWITCHING_PROTOCOLS = 101
HTTP_102_PROCESSING = 102
HTTP_103_EARLY_HINTS = 103
HTTP_200_OK = 200
HTTP_201_CREATED = 201
HTTP_202_ACCEPTED = 202
HTTP_203_NON_AUTHORITATIVE_INFORMATION = 203
HTTP_204_NO_CONTENT = 204
HTTP_205_RESET_CONTENT = 205
HTTP_206_PARTIAL_CONTENT = 206
HTTP_207_MULTI_STATUS = 207
HTTP_208_ALREADY_REPORTED = 208
HTTP_226_IM_USED = 226
HTTP_300_MULTIPLE_CHOICES = 300
HTTP_301_MOVED_PERMANENTLY = 301
HTTP_302_FOUND = 302
HTTP_303_SEE_OTHER = 303
HTTP_304_NOT_MODIFIED = 304
HTTP_305_USE_PROXY = 305
HTTP_306_RESERVED = 306
HTTP_307_TEMPORARY_REDIRECT = 307
HTTP_308_PERMANENT_REDIRECT = 308
HTTP_400_BAD_REQUEST = 400
HTTP_401_UNAUTHORIZED = 401
HTTP_402_PAYMENT_REQUIRED = 402
HTTP_403_FORBIDDEN = 403
HTTP_404_NOT_FOUND = 404
HTTP_405_METHOD_NOT_ALLOWED = 405
HTTP_406_NOT_ACCEPTABLE = 406
HTTP_407_PROXY_AUTHENTICATION_REQUIRED = 407
HTTP_408_REQUEST_TIMEOUT = 408
HTTP_409_CONFLICT = 409
HTTP_410_GONE = 410
HTTP_411_LENGTH_REQUIRED = 411
HTTP_412_PRECONDITION_FAILED = 412
HTTP_413_REQUEST_ENTITY_TOO_LARGE = 413
HTTP_414_REQUEST_URI_TOO_LONG = 414
HTTP_415_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE = 416
HTTP_417_EXPECTATION_FAILED = 417
HTTP_418_IM_A_TEAPOT = 418
HTTP_421_MISDIRECTED_REQUEST = 421
HTTP_422_UNPROCESSABLE_ENTITY = 422
HTTP_423_LOCKED = 423
HTTP_424_FAILED_DEPENDENCY = 424
HTTP_426_UPGRADE_REQUIRED = 426
HTTP_428_PRECONDITION_REQUIRED = 428
HTTP_429_TOO_MANY_REQUESTS = 429
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = 431
HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = 451
HTTP_500_INTERNAL_SERVER_ERROR = 500
HTTP_502_BAD_GATEWAY = 502
@classmethod
def retrieve_error_by_code(cls, error_code: str):
return getattr(cls, error_code, 502)

View File

@ -0,0 +1,46 @@
CrudCollectionLanguageModel = dict(
tr={
"id": "ID",
"uu_id": "UUID",
"ref_id": "Referans ID",
"created_at": "Oluşturulma Tarihi",
"updated_at": "Güncellenme Tarihi",
"cryp_uu_id": "Şifreli ID",
"created_by": "Oluşturan",
"created_by_id": "Oluşturan ID",
"updated_by": "Güncelleyen",
"updated_by_id": "Güncelleyen ID",
"confirmed_by": "Onaylayan",
"confirmed_by_id": "Onaylayan ID",
"is_confirmed": "Onay Durumu",
"replication_id": "Replikasyon ID",
"deleted": "Silindi",
"active": "Aktif",
"is_notification_send": "Bildirim Gönderildi",
"is_email_send": "E-posta Gönderildi",
"expiry_ends": "Bitiş Tarihi",
"expiry_starts": "Başlangıç Tarihi",
},
en={
"id": "Identity",
"uu_id": "UUID",
"ref_id": "Reference Identity",
"created_at": "Created At",
"updated_at": "Updated At",
"cryp_uu_id": "Encrypted Identity",
"created_by": "Created By",
"created_by_id": "Created By Identity",
"updated_by": "Updated By",
"updated_by_id": "Updated By Identity",
"confirmed_by": "Confirmed By",
"confirmed_by_id": "Confirmed By Identity",
"is_confirmed": "Confirmation Status",
"replication_id": "Replication Identity",
"deleted": "Deleted",
"active": "Active",
"is_notification_send": "Notification Sent",
"is_email_send": "Email Sent",
"expiry_ends": "Expiration End",
"expiry_starts": "Expiration Start",
},
)

View File

@ -0,0 +1,390 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
AccountBooksLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"country": "Ülke",
"branch_type": "Şube Türü",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UU ID",
"branch_id": "Şube ID",
"branch_uu_id": "Şube UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"country": "Country",
"branch_type": "Branch Type",
"company_id": "Company ID",
"company_uu_id": "Company UU ID",
"branch_id": "Branch ID",
"branch_uu_id": "Branch UU ID",
},
)
AccountCodesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"account_code": "Hesap Kodu",
"comment_line": "Yorum Satırı",
"is_receive_or_debit": "Alacak veya Borç",
"product_id": "Ürün ID",
"nvi_id": "Nvi ID",
"status_id": "Durum ID",
"account_code_seperator": "Hesap Kodu Ayırıcı",
"system_id": "Sistem ID",
"locked": "Kilitli",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UU ID",
"customer_id": "Müşteri ID",
"customer_uu_id": "Müşteri UU ID",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"account_code": "Account Code",
"comment_line": "Comment Line",
"is_receive_or_debit": "Is Receive or Debit",
"product_id": "Product ID",
"nvi_id": "Nvi ID",
"status_id": "Status ID",
"account_code_seperator": "Account Code Seperator",
"system_id": "System ID",
"locked": "Locked",
"company_id": "Company ID",
"company_uu_id": "Company UU ID",
"customer_id": "Customer ID",
"customer_uu_id": "Customer UU ID",
"person_id": "Person ID",
"person_uu_id": "Person UU ID",
},
)
AccountCodeParserLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"account_code_1": "Hesap Kodu 1",
"account_code_2": "Hesap Kodu 2",
"account_code_3": "Hesap Kodu 3",
"account_code_4": "Hesap Kodu 4",
"account_code_5": "Hesap Kodu 5",
"account_code_6": "Hesap Kodu 6",
"account_code_id": "Hesap Kodu ID",
"account_code_uu_id": "Hesap Kodu UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"account_code_1": "Account Code 1",
"account_code_2": "Account Code 2",
"account_code_3": "Account Code 3",
"account_code_4": "Account Code 4",
"account_code_5": "Account Code 5",
"account_code_6": "Account Code 6",
"account_code_id": "Account Code ID",
"account_code_uu_id": "Account Code UU ID",
},
)
AccountMasterLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"doc_date": "Belge Tarihi",
"plug_type": "Fiş Türü",
"plug_number": "Fiş Numarası",
"special_code": "Özel Kod",
"authorization_code": "Yetki Kodu",
"doc_code": "Belge Kodu",
"doc_type": "Belge Türü",
"comment_line1": "Yorum Satırı 1",
"comment_line2": "Yorum Satırı 2",
"comment_line3": "Yorum Satırı 3",
"comment_line4": "Yorum Satırı 4",
"comment_line5": "Yorum Satırı 5",
"comment_line6": "Yorum Satırı 6",
"project_code": "Proje Kodu",
"module_no": "Modül No",
"journal_no": "Defter No",
"status_id": "Durum ID",
"canceled": "İptal Edildi",
"print_count": "Yazdırma Sayısı",
"total_active": "Toplam Aktif",
"total_passive": "Toplam Pasif",
"total_active_1": "Toplam Aktif 1",
"total_passive_1": "Toplam Pasif 1",
"total_active_2": "Toplam Aktif 2",
"total_passive_2": "Toplam Pasif 2",
"total_active_3": "Toplam Aktif 3",
"total_passive_3": "Toplam Pasif 3",
"total_active_4": "Toplam Aktif 4",
"total_passive_4": "Toplam Pasif 4",
"cross_ref": "Çapraz Referans",
"data_center_id": "Veri Merkezi ID",
"data_center_rec_num": "Veri Merkezi Kayıt Numarası",
"account_header_id": "Hesap Başlığı ID",
"account_header_uu_id": "Hesap Başlığı UU ID",
"project_item_id": "Proje Öğesi ID",
"project_item_uu_id": "Proje Öğesi UU ID",
"department_id": "Departman ID",
"department_uu_id": "Departman UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"doc_date": "Document Date",
"plug_type": "Plug Type",
"plug_number": "Plug Number",
"special_code": "Special Code",
"authorization_code": "Authorization Code",
"doc_code": "Document Code",
"doc_type": "Document Type",
"comment_line1": "Comment Line 1",
"comment_line2": "Comment Line 2",
"comment_line3": "Comment Line 3",
"comment_line4": "Comment Line 4",
"comment_line5": "Comment Line 5",
"comment_line6": "Comment Line 6",
"project_code": "Project Code",
"module_no": "Module No",
"journal_no": "Journal No",
"status_id": "Status ID",
"canceled": "Canceled",
"print_count": "Print Count",
"total_active": "Total Active",
"total_passive": "Total Passive",
"total_active_1": "Total Active 1",
"total_passive_1": "Total Passive 1",
"total_active_2": "Total Active 2",
"total_passive_2": "Total Passive 2",
"total_active_3": "Total Active 3",
"total_passive_3": "Total Passive 3",
"total_active_4": "Total Active 4",
"total_passive_4": "Total Passive 4",
"cross_ref": "Cross Reference",
"data_center_id": "Data Center ID",
"data_center_rec_num": "Data Center Record Number",
"account_header_id": "Account Header ID",
"account_header_uu_id": "Account Header UU ID",
"project_item_id": "Project Item ID",
"project_item_uu_id": "Project Item UU ID",
"department_id": "Department ID",
"department_uu_id": "Department UU ID",
},
)
AccountDetailLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"doc_date": "Belge Tarihi",
"plug_type": "Fiş Türü",
"plug_number": "Fiş Numarası",
"special_code": "Özel Kod",
"authorization_code": "Yetki Kodu",
"doc_code": "Belge Kodu",
"doc_type": "Belge Türü",
"comment_line1": "Yorum Satırı 1",
"comment_line2": "Yorum Satırı 2",
"comment_line3": "Yorum Satırı 3",
"comment_line4": "Yorum Satırı 4",
"comment_line5": "Yorum Satırı 5",
"comment_line6": "Yorum Satırı 6",
"project_code": "Proje Kodu",
"module_no": "Modül No",
"journal_no": "Defter No",
"status_id": "Durum ID",
"canceled": "İptal Edildi",
"print_count": "Yazdırma Sayısı",
"total_active": "Toplam Aktif",
"total_passive": "Toplam Pasif",
"total_active_1": "Toplam Aktif 1",
"total_passive_1": "Toplam Pasif 1",
"total_active_2": "Toplam Aktif 2",
"total_passive_2": "Toplam Pasif 2",
"total_active_3": "Toplam Aktif 3",
"total_passive_3": "Toplam Pasif 3",
"total_active_4": "Toplam Aktif 4",
"total_passive_4": "Toplam Pasif 4",
"cross_ref": "Çapraz Referans",
"data_center_id": "Veri Merkezi ID",
"data_center_rec_num": "Veri Merkezi Kayıt Numarası",
"account_header_id": "Hesap Başlığı ID",
"account_header_uu_id": "Hesap Başlığı UU ID",
"project_item_id": "Proje Öğesi ID",
"project_item_uu_id": "Proje Öğesi UU ID",
"department_id": "Departman ID",
"department_uu_id": "Departman UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"doc_date": "Document Date",
"plug_type": "Plug Type",
"plug_number": "Plug Number",
"special_code": "Special Code",
"authorization_code": "Authorization Code",
"doc_code": "Document Code",
"doc_type": "Document Type",
"comment_line1": "Comment Line 1",
"comment_line2": "Comment Line 2",
"comment_line3": "Comment Line 3",
"comment_line4": "Comment Line 4",
"comment_line5": "Comment Line 5",
"comment_line6": "Comment Line 6",
"project_code": "Project Code",
"module_no": "Module No",
"journal_no": "Journal No",
"status_id": "Status ID",
"canceled": "Canceled",
"print_count": "Print Count",
"total_active": "Total Active",
"total_passive": "Total Passive",
"total_active_1": "Total Active 1",
"total_passive_1": "Total Passive 1",
"total_active_2": "Total Active 2",
"total_passive_2": "Total Passive 2",
"total_active_3": "Total Active 3",
"total_passive_3": "Total Passive 3",
"total_active_4": "Total Active 4",
"total_passive_4": "Total Passive 4",
"cross_ref": "Cross Reference",
"data_center_id": "Data Center ID",
"data_center_rec_num": "Data Center Record Number",
"account_header_id": "Account Header ID",
"account_header_uu_id": "Account Header UU ID",
"project_item_id": "Project Item ID",
"project_item_uu_id": "Project Item UU ID",
"department_id": "Department ID",
"department_uu_id": "Department UU ID",
},
)
AccountRecordsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"iban": "IBAN",
"bank_date": "Banka Tarihi",
"currency_value": "Döviz Değeri",
"bank_balance": "Banka Bakiyesi",
"currency": "Döviz",
"additional_balance": "Ek Bakiye",
"channel_branch": "Kanal Şubesi",
"process_name": "İşlem Türü Adı",
"process_type": "İşlem Türü",
"process_comment": "İşlem Kayıt Yorumu",
"process_garbage": "İşlem Kayıt Çöpü",
"bank_reference_code": "Banka Referans Kodu",
"add_comment_note": "Yorum Not Ekle",
"is_receipt_mail_send": "Alındı Mail Gönderildi",
"found_from": "Bulunduğu",
"similarity": "Benzerlik",
"remainder_balance": "Kalan Bakiye",
"bank_date_y": "Banka Tarihi Yıl",
"bank_date_m": "Banka Tarihi Ay",
"bank_date_w": "Banka Tarihi Hafta",
"bank_date_d": "Banka Tarihi Gün",
"approving_accounting_record": "Onaylayan Muhasebe Kaydı",
"accounting_receipt_date": "Muhasebe Alındı Tarihi",
"accounting_receipt_number": "Muhasebe Alındı Numarası",
"status_id": "Durum ID",
"approved_record": "Onaylanmış Kayıt",
"import_file_name": "İçe Aktarım Dosya Adı",
"receive_debit": "Alacak Borç",
"receive_debit_uu_id": "Alacak Borç UU ID",
"budget_type": "Bütçe Türü",
"budget_type_uu_id": "Bütçe Türü UU ID",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UU ID",
"send_company_id": "Gönderen Şirket ID",
"send_company_uu_id": "Gönderen Şirket UU ID",
"send_person_id": "Gönderen Kişi ID",
"send_person_uu_id": "Gönderen Kişi UU ID",
"approving_accounting_person": "Onaylayan Muhasebe Kişi",
"approving_accounting_person_uu_id": "Onaylayan Muhasebe Kişi UU ID",
"living_space_id": "Yaşam Alanı ID",
"living_space_uu_id": "Yaşam Alanı UU ID",
"customer_id": "Müşteri ID",
"customer_uu_id": "Müşteri UU ID",
"build_id": "Bina ID",
"build_uu_id": "Bina UU ID",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UU ID",
"build_decision_book_id": "Bina Karar Defteri ID",
"build_decision_book_uu_id": "Bina Karar Defteri UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"iban": "IBAN",
"bank_date": "Bank Date",
"currency_value": "Currency Value",
"bank_balance": "Bank Balance",
"currency": "Currency",
"additional_balance": "Additional Balance",
"channel_branch": "Channel Branch",
"process_name": "Process Type Name",
"process_type": "Process Type",
"process_comment": "Process Record Comment",
"process_garbage": "Process Record Garbage",
"bank_reference_code": "Bank Reference Code",
"add_comment_note": "Add Comment Note",
"is_receipt_mail_send": "Is Receipt Mail Send",
"found_from": "Found From",
"similarity": "Similarity",
"remainder_balance": "Remainder Balance",
"bank_date_y": "Bank Date Year",
"bank_date_m": "Bank Date Month",
"bank_date_w": "Bank Date Week",
"bank_date_d": "Bank Date Day",
"approving_accounting_record": "Approving Accounting Record",
"accounting_receipt_date": "Accounting Receipt Date",
"accounting_receipt_number": "Accounting Receipt Number",
"status_id": "Status ID",
"approved_record": "Approved Record",
"import_file_name": "Import File Name",
"receive_debit": "Receive Debit",
"receive_debit_uu_id": "Receive Debit UU ID",
"budget_type": "Budget Type",
"budget_type_uu_id": "Budget Type UU ID",
"company_id": "Company ID",
"company_uu_id": "Company UU ID",
"send_company_id": "Send Company ID",
"send_company_uu_id": "Send Company UU ID",
"send_person_id": "Send Person ID",
"send_person_uu_id": "Send Person UU ID",
"approving_accounting_person": "Approving Accounting Person",
"approving_accounting_person_uu_id": "Approving Accounting Person UU ID",
"living_space_id": "Living Space ID",
"living_space_uu_id": "Living Space UU ID",
"customer_id": "Customer ID",
"customer_uu_id": "Customer UU ID",
"build_id": "Build ID",
"build_uu_id": "Build UU ID",
"build_parts_id": "Build Parts ID",
"build_parts_uu_id": "Build Parts UU ID",
"build_decision_book_id": "Build Decision Book ID",
"build_decision_book_uu_id": "Build Decision Book UU ID",
},
)
AccountRecordExchangesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"are_currency": "Para Birimi",
"are_exchange_rate": "Döviz Kuru",
"usd_exchange_rate_value": "USD Döviz Kuru Değeri",
"eur_exchange_rate_value": "EUR Döviz Kuru Değeri",
"gbp_exchange_rate_value": "GBP Döviz Kuru Değeri",
"cny_exchange_rate_value": "CNY Döviz Kuru Değeri",
"account_records_id": "Hesap Kayıt ID",
"account_records_uu_id": "Hesap Kayıt UU ID",
},
en={
**CrudCollectionLanguageModel["en"],
"are_currency": "Currency",
"are_exchange_rate": "Exchange Rate",
"usd_exchange_rate_value": "USD Exchange Rate Value",
"eur_exchange_rate_value": "EUR Exchange Rate Value",
"gbp_exchange_rate_value": "GBP Exchange Rate Value",
"cny_exchange_rate_value": "CNY Exchange Rate Value",
"account_records_id": "Account Record ID",
"account_records_uu_id": "Account Record UU ID",
},
)

View File

@ -0,0 +1,54 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
BuildIbansLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"iban": "IBAN Numarası",
"start_date": "Banka İşlem Başlangıç Tarihi",
"stop_date": "Banka İşlem Bitiş Tarihi",
"bank_code": "Banka Kodu",
"xcomment": "Yorum",
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"iban": "IBAN Number",
"start_date": "Bank Transaction Start Date",
"stop_date": "Bank Transaction End Date",
"bank_code": "Bank Code",
"xcomment": "Comment",
"build_id": "Build ID",
"build_uu_id": "Build UUID",
},
)
BuildIbanDescriptionLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"iban": "IBAN Numarası",
"group_id": "Grup ID",
"search_word": "Arama Kelimesi",
"customer_id": "Müşteri ID",
"customer_uu_id": "Müşteri UUID",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"iban": "IBAN Number",
"group_id": "Group ID",
"search_word": "Search Word",
"customer_id": "Customer ID",
"customer_uu_id": "Customer UUID",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
"build_parts_id": "Build Parts ID",
"build_parts_uu_id": "Build Parts UUID",
},
)

View File

@ -0,0 +1,103 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
DecisionBookBudgetBooksLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"country": "Ülke",
"branch_type": "Şube Tipi",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
"branch_id": "Şube ID",
"branch_uu_id": "Şube UUID",
"build_decision_book_id": "Karar Defteri ID",
"build_decision_book_uu_id": "Karar Defteri UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"country": "Country",
"branch_type": "Branch Type",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
"branch_id": "Branch ID",
"branch_uu_id": "Branch UUID",
"build_decision_book_id": "Build Decision Book ID",
"build_decision_book_uu_id": "Build Decision Book UUID",
},
)
DecisionBookBudgetCodesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"budget_code": "Bütçe Kodu",
"comment_line": "Yorum Satırı",
"build_decision_book_id": "Karar Defteri ID",
"build_decision_book_uu_id": "Karar Defteri UUID",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UUID",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"budget_code": "Budget Code",
"comment_line": "Comment Line",
"build_decision_book_id": "Build Decision Book ID",
"build_decision_book_uu_id": "Build Decision Book UUID",
"build_parts_id": "Build Parts ID",
"build_parts_uu_id": "Build Parts UUID",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
},
)
DecisionBookBudgetMasterLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"budget_type": "Bütçe Tipi",
"currency": "Para Birimi",
"total_budget": "Toplam Bütçe",
"tracking_period_id": "Takip Dönemi ID",
"tracking_period_uu_id": "Takip Dönemi UUID",
"budget_books_id": "Bütçe Kitapları ID",
"budget_books_uu_id": "Bütçe Kitapları UUID",
"department_id": "Departman ID",
"department_uu_id": "Departman UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"budget_type": "Budget Type",
"currency": "Currency",
"total_budget": "Total Budget",
"tracking_period_id": "Tracking Period ID",
"tracking_period_uu_id": "Tracking Period UUID",
"budget_books_id": "Budget Books ID",
"budget_books_uu_id": "Budget Books UUID",
"department_id": "Department ID",
"department_uu_id": "Department UUID",
},
)
DecisionBookBudgetsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"process_date": "İşlem Tarihi",
"budget_codes_id": "Bütçe Kodları ID",
"total_budget": "Toplam Bütçe",
"used_budget": "Kullanılan Bütçe",
"remaining_budget": "Kalan Bütçe",
"decision_book_budget_master_id": "Karar Defteri Bütçesi ID",
"decision_book_budget_master_uu_id": "Karar Defteri Bütçesi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"process_date": "Process Date",
"budget_codes_id": "Budget Codes ID",
"total_budget": "Total Budget",
"used_budget": "Used Budget",
"remaining_budget": "Remaining Budget",
"decision_book_budget_master_id": "Decision Book Budget Master ID",
"decision_book_budget_master_uu_id": "Decision Book Budget Master UUID",
},
)

View File

@ -0,0 +1,303 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
BuildTypesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"function_code": "Fonksiyon Kodu",
"type_code": "Yapı Tipi Kodu",
"lang": "Dil",
"type_name": "Tip Adı",
},
en={
**CrudCollectionLanguageModel["en"],
"function_code": "Function Code",
"type_code": "Type Code",
"lang": "Language",
"type_name": "Type Name",
},
)
Part2EmployeeLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_id": "Bina ID",
"part_id": "Bina Parça ID",
"employee_id": "Çalışan ID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_id": "Build ID",
"part_id": "Build Part ID",
"employee_id": "Employee ID",
},
)
RelationshipEmployee2BuildLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"company_id": "Şirket ID",
"employee_id": "Çalışan ID",
"member_id": "Üye ID",
"relationship_type": "İlişki Tipi",
"show_only": "Sadece Göster",
},
en={
**CrudCollectionLanguageModel["en"],
"company_id": "Company ID",
"employee_id": "Employee ID",
"member_id": "Member ID",
"relationship_type": "Relationship Type",
"show_only": "Show Only",
},
)
BuildLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"gov_address_code": "Adres Kodu",
"build_name": "Bina Adı",
"build_no": "Bina No",
"max_floor": "Max Kat",
"underground_floor": "Zemin Kat",
"build_date": "Bina Tarihi",
"decision_period_date": "Karar Dönemi Tarihi",
"tax_no": "Vergi No",
"lift_count": "Asansör Sayısı",
"heating_system": "Isıtma Sistemi",
"cooling_system": "Soğutma Sistemi",
"hot_water_system": "Sıcak Su Sistemi",
"block_service_man_count": "Blok Hizmet Görevlisi Sayısı",
"security_service_man_count": "Güvenlik Görevlisi Sayısı",
"garage_count": "Garaj Sayısı",
"management_room_id": "Yönetim Odası ID",
"site_id": "Site ID",
"site_uu_id": "Site UUID",
"address_id": "Adres ID",
"address_uu_id": "Adres UUID",
"build_types_id": "Bina Tipi ID",
"build_types_uu_id": "Bina Tipi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"gov_address_code": "Address Code",
"build_name": "Building Name",
"build_no": "Building Number",
"max_floor": "Max Floor",
"underground_floor": "Underground Floor",
"build_date": "Building Date",
"decision_period_date": "Decision Period Date",
"tax_no": "Tax No",
"lift_count": "Lift Count",
"heating_system": "Heating System",
"cooling_system": "Cooling System",
"hot_water_system": "Hot Water System",
"block_service_man_count": "Block Service Man Count",
"security_service_man_count": "Security Service Man Count",
"garage_count": "Garage Count",
"management_room_id": "Management Room ID",
"site_id": "Site ID",
"site_uu_id": "Site UUID",
"address_id": "Address ID",
"address_uu_id": "Address UUID",
"build_types_id": "Build Types ID",
"build_types_uu_id": "Build Types UUID",
},
)
BuildPartsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"address_gov_code": "Adres Kodu",
"part_no": "Bina Parça No",
"part_level": "Bina Parça Katı",
"part_code": "Bina Parça Kodu",
"part_gross_size": "Bina Parça Brüt Alanı",
"part_net_size": "Bina Parça Net Alanı",
"default_accessory": "Varsayılan Aksesuar",
"human_livable": "İnsan Yaşam Alanı",
"due_part_key": "Ödeme Grubu",
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"part_direction_id": "Bina Parça Yönü ID",
"part_direction_uu_id": "Bina Parça Yönü UUID",
"part_type_id": "Bina Parça Tipi ID",
"part_type_uu_id": "Bina Parça Tipi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"address_gov_code": "Address Code",
"part_no": "Part Number",
"part_level": "Part Level",
"part_code": "Part Code",
"part_gross_size": "Part Gross Size",
"part_net_size": "Part Net Size",
"default_accessory": "Default Accessory",
"human_livable": "Human Livable",
"due_part_key": "Due Part Key",
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"part_direction_id": "Part Direction ID",
"part_direction_uu_id": "Part Direction UUID",
"part_type_id": "Part Type ID",
"part_type_uu_id": "Part Type UUID",
},
)
BuildLivingSpaceLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"fix_value": "Düz Değer",
"fix_percent": "Düz Yüzde",
"agreement_no": "Anlaşma No",
"marketing_process": "Pazarlama İşlemi",
"marketing_layer": "Pazarlama Katmanı",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UUID",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UUID",
"occupant_type": "Sakin Tipi",
"occupant_type_uu_id": "Sakin Tipi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"fix_value": "Fixed Value",
"fix_percent": "Fixed Percent",
"agreement_no": "Agreement No",
"marketing_process": "Marketing Process",
"marketing_layer": "Marketing Layer",
"build_parts_id": "Build Part ID",
"build_parts_uu_id": "Build Part UUID",
"person_id": "Person ID",
"person_uu_id": "Person UUID",
"occupant_type": "Occupant Type",
"occupant_type_uu_id": "Occupant Type UUID",
},
)
BuildManagementLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"discounted_percentage": "İndirim Yüzdesi",
"discounted_price": "İndirimli Fiyat",
"calculated_price": "Hesaplanan Fiyat",
"occupant_type": "Sakin Tipi",
"occupant_type_uu_id": "Sakin Tipi UUID",
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"discounted_percentage": "Discounted Percentage",
"discounted_price": "Discounted Price",
"calculated_price": "Calculated Price",
"occupant_type": "Occupant Type",
"occupant_type_uu_id": "Occupant Type UUID",
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"build_parts_id": "Build Part ID",
"build_parts_uu_id": "Build Part UUID",
},
)
BuildAreaLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"area_name": "Alan Adı",
"area_code": "Alan Kodu",
"area_type": "Alan Tipi",
"area_direction": "Alan Yönü",
"area_gross_size": "Alan Brüt Alanı",
"area_net_size": "Alan Net Alanı",
"width": "En",
"size": "Boyut",
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"part_type_id": "Bina Parça Tipi ID",
"part_type_uu_id": "Bina Parça Tipi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"area_name": "Area Name",
"area_code": "Area Code",
"area_type": "Area Type",
"area_direction": "Area Direction",
"area_gross_size": "Area Gross Size",
"area_net_size": "Area Net Size",
"width": "Width",
"size": "Size",
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"part_type_id": "Part Type ID",
"part_type_uu_id": "Part Type UUID",
},
)
BuildSitesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"site_name": "Site Adı",
"site_no": "Site No",
"address_id": "Adres ID",
"address_uu_id": "Adres UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"site_name": "Site Name",
"site_no": "Site No",
"address_id": "Address ID",
"address_uu_id": "Address UUID",
},
)
BuildCompaniesProvidingLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
"provide_id": "Sağlayıcı ID",
"provide_uu_id": "Sağlayıcı UUID",
"contract_id": "Sözleşme ID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
"provide_id": "Provide ID",
"provide_uu_id": "Provide UUID",
"contract_id": "Contract ID",
},
)
BuildPersonProvidingLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"people_id": "Kişi ID",
"people_uu_id": "Kişi UUID",
"provide_id": "Sağlayıcı ID",
"provide_uu_id": "Sağlayıcı UUID",
"contract_id": "Sözleşme ID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"people_id": "People ID",
"people_uu_id": "People UUID",
"provide_id": "Provide ID",
"provide_uu_id": "Provide UUID",
"contract_id": "Contract ID",
},
)

View File

@ -0,0 +1,400 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
BuildDecisionBookLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"decision_book_pdf_path": "Karar Defteri PDF Yolu",
"resp_company_fix_wage": "Firma Sabit Ücreti",
"is_out_sourced": "Dış Kaynak Kullanımı",
"meeting_date": "Toplantı Tarihi",
"decision_type": "Karar Türü",
"meeting_is_completed": "Toplantı Tamamlandı",
"meeting_completed_date": "Toplantı Tamamlanma Tarihi",
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"resp_company_id": "Sorumlu Firma ID",
"resp_company_uu_id": "Sorumlu Firma UUID",
"contact_id": "İletişim ID",
"contact_uu_id": "İletişim UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"decision_book_pdf_path": "Decision Book PDF Path",
"resp_company_fix_wage": "Resp Company Fix Wage",
"is_out_sourced": "Is Out Sourced",
"meeting_date": "Meeting Date",
"decision_type": "Decision Type",
"meeting_is_completed": "Meeting Is Completed",
"meeting_completed_date": "Meeting Completed Date",
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"resp_company_id": "Resp Company ID",
"resp_company_uu_id": "Resp Company UUID",
"contact_id": "Contact ID",
"contact_uu_id": "Contact UUID",
},
)
BuildDecisionBookInvitationsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_id": "Bina ID",
"build_uu_id": "Bina UUID",
"decision_book_id": "Karar Defteri ID",
"decision_book_uu_id": "Karar Defteri UUID",
"invitation_type": "Davet Türü",
"invitation_attempt": "Davet Denemesi",
"living_part_count": "Yaşam Bölüm Sayısı",
"living_part_percentage": "Yaşam Bölüm Yüzdesi",
"message": "Davet Mesajı",
"planned_date": "Planlanan Tarih",
"planned_date_expires": "Planlanan Tarih Bitiş",
},
en={
**CrudCollectionLanguageModel["en"],
"build_id": "Build ID",
"build_uu_id": "Build UUID",
"decision_book_id": "Decision Book ID",
"decision_book_uu_id": "Decision Book UUID",
"invitation_type": "Invitation Type",
"invitation_attempt": "Invitation Attempt",
"living_part_count": "Living Part Count",
"living_part_percentage": "Living Part Percentage",
"message": "Message",
"planned_date": "Planned Date",
"planned_date_expires": "Planned Date Expires",
},
)
BuildDecisionBookPersonLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"dues_percent_discount": "Aidat İndirim Oranı",
"dues_fix_discount": "Aidat Sabit İndirim",
"dues_discount_approval_date": "İndirim Onay Tarihi",
"send_date": "Gönderme Tarihi",
"is_attending": "Katılıyor",
"confirmed_date": "Onay Tarihi",
"token": "Token",
"vicarious_person_id": "Vekil Kişi ID",
"vicarious_person_uu_id": "Vekil Kişi UUID",
"invite_id": "Davet ID",
"invite_uu_id": "Davet UUID",
"build_decision_book_id": "Karar Defteri ID",
"build_decision_book_uu_id": "Karar Defteri UUID",
"build_living_space_id": "Yaşam Alanı ID",
"build_living_space_uu_id": "Yaşam Alanı UUID",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"dues_percent_discount": "Dues Percent Discount",
"dues_fix_discount": "Dues Fix Discount",
"dues_discount_approval_date": "Dues Discount Approval Date",
"send_date": "Send Date",
"is_attending": "Is Attending",
"confirmed_date": "Confirmed Date",
"token": "Token",
"vicarious_person_id": "Vicarious Person ID",
"vicarious_person_uu_id": "Vicarious Person UUID",
"invite_id": "Invite ID",
"invite_uu_id": "Invite UUID",
"build_decision_book_id": "Decision Book ID",
"build_decision_book_uu_id": "Decision Book UUID",
"build_living_space_id": "Living Space ID",
"build_living_space_uu_id": "Living Space UUID",
"person_id": "Person ID",
"person_uu_id": "Person UUID",
},
)
BuildDecisionBookPersonOccupantsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_decision_book_person_id": "Karar Defteri Kişi ID",
"build_decision_book_person_uu_id": "Karar Defter Kişi UUID",
"invite_id": "Davet ID",
"invite_uu_id": "Davet UUID",
"occupant_type_id": "Kişi Tür ID",
"occupant_type_uu_id": "Kişi Tür UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_decision_book_person_id": "Build Decision Book Person ID",
"build_decision_book_person_uu_id": "Build Decision Book Person UUID",
"invite_id": "Invite ID",
"invite_uu_id": "Invite UUID",
"occupant_type_id": "Occupant Type ID",
"occupant_type_uu_id": "Occupant Type UUID",
},
)
BuildDecisionBookItemsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"item_order": "Madde Sırası",
"item_comment": "Madde Yorumu",
"item_objection": "Madde İtirazı",
"info_is_completed": "Bilgi Tamamlandı",
"is_payment_created": "Ödeme Yapıldı",
"info_type_id": "Bilgi Türü ID",
"info_type_uu_id": "Bilgi Türü UUID",
"build_decision_book_id": "Karar Defteri ID",
"build_decision_book_uu_id": "Karar Defteri UUID",
"item_short_comment": "Kısa Yorum",
},
en={
**CrudCollectionLanguageModel["en"],
"item_order": "Item Order",
"item_comment": "Item Comment",
"item_objection": "Item Objection",
"info_is_completed": "Info Is Completed",
"is_payment_created": "Is Payment Created",
"info_type_id": "Info Type ID",
"info_type_uu_id": "Info Type UUID",
"build_decision_book_id": "Build Decision Book ID",
"build_decision_book_uu_id": "Build Decision Book UUID",
"item_short_comment": "Item Short Comment",
},
)
BuildDecisionBookItemsUnapprovedLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"item_objection": "Madde İtirazı",
"item_order": "Madde Sırası",
"decision_book_item_id": "Karar Defteri Madde ID",
"decision_book_item_uu_id": "Karar Defteri Madde UUID",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UUID",
"build_decision_book_item": "Karar Defteri Madde ID",
"build_decision_book_item_uu_id": "Karar Defteri Madde UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"item_objection": "Item Objection",
"item_order": "Item Order",
"decision_book_item_id": "Decision Book Item ID",
"decision_book_item_uu_id": "Decision Book Item UUID",
"person_id": "Person ID",
"person_uu_id": "Person UUID",
"build_decision_book_item": "Build Decision Book Item ID",
"build_decision_book_item_uu_id": "Build Decision Book Item UUID",
},
)
BuildDecisionBookPaymentsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"payment_plan_time_periods": "Ödeme Planı Zaman Periyodu",
"process_date": "Ödeme Tarihi",
"payment_amount": "Ödeme Miktarı",
"currency": "Para Birimi",
"payment_types_id": "Ödeme Türü ID",
"payment_types_uu_id": "Ödeme Türü UUID",
"period_time": "Dönem Zamanı",
"process_date_y": "Tarih Yılı",
"process_date_m": "Tarih Ayı",
"build_decision_book_item_id": "Karar Defteri Madde ID",
"build_decision_book_item_uu_id": "Karar Defteri Madde UUID",
"build_parts_id": "Bina Parça ID",
"build_parts_uu_id": "Bina Parça UUID",
"decision_book_project_id": "Karar Defteri Proje ID",
"decision_book_project_uu_id": "Karar Defteri Proje UUID",
"account_records_id": "Hesap Kayıtları ID",
"account_records_uu_id": "Hesap Kayıtları UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"payment_plan_time_periods": "Payment Plan Time Periods",
"process_date": "Process Date",
"payment_amount": "Payment Amount",
"currency": "Currency",
"payment_types_id": "Payment Types ID",
"payment_types_uu_id": "Payment Types UUID",
"period_time": "Period Time",
"process_date_y": "Process Date Year",
"process_date_m": "Process Date Month",
"build_decision_book_item_id": "Build Decision Book Item ID",
"build_decision_book_item_uu_id": "Build Decision Book Item UUID",
"build_parts_id": "Build Parts ID",
"build_parts_uu_id": "Build Parts UUID",
"decision_book_project_id": "Decision Book Project ID",
"decision_book_project_uu_id": "Decision Book Project UUID",
"account_records_id": "Account Records ID",
"account_records_uu_id": "Account Records UUID",
},
)
BuildDecisionBookLegalLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"period_start_date": "Dönem Başlangıç Tarihi",
"lawsuits_decision_number": "Dava Karar Numarası",
"lawsuits_decision_date": "Dava Karar Tarihi",
"period_stop_date": "Dönem Bitiş Tarihi",
"decision_book_pdf_path": "Karar Defteri PDF Yolu",
"resp_company_total_wage": "Firma Toplam Ücreti",
"contact_agreement_path": "İletişim Anlaşma Yolu",
"contact_agreement_date": "İletişim Anlaşma Tarihi",
"meeting_date": "Toplantı Tarihi",
"lawsuits_type": "Dava Türü",
"lawsuits_name": "Dava Adı",
"lawsuits_note": "Dava Notu",
"lawyer_cost": "Avukat Ücreti",
"mediator_lawyer_cost": "Arabulucu Avukat Ücreti",
"other_cost": "Diğer Ücret",
"legal_cost": "Yasal Ücret",
"approved_cost": "Onaylanan Ücret",
"total_price": "Toplam Ücret",
"build_db_item_id": "Karar Defteri Madde ID",
"build_db_item_uu_id": "Karar Defteri Madde UUID",
"resp_attorney_id": "Sorumlu Avukat ID",
"resp_attorney_uu_id": "Sorumlu Avukat UUID",
"resp_attorney_company_id": "Sorumlu Avukat Firma ID",
"resp_attorney_company_uu_id": "Sorumlu Avukat Firma UUID",
"mediator_lawyer_person_id": "Arabulucu Avukat Kişi ID",
"mediator_lawyer_person_uu_id": "Arabulucu Avukat Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"period_start_date": "Period Start Date",
"lawsuits_decision_number": "Lawsuits Decision Number",
"lawsuits_decision_date": "Lawsuits Decision Date",
"period_stop_date": "Period Stop Date",
"decision_book_pdf_path": "Decision Book PDF Path",
"resp_company_total_wage": "Resp Company Total Wage",
"contact_agreement_path": "Contact Agreement Path",
"contact_agreement_date": "Contact Agreement Date",
"meeting_date": "Meeting Date",
"lawsuits_type": "Lawsuits Type",
"lawsuits_name": "Lawsuits Name",
"lawsuits_note": "Lawsuits Note",
"lawyer_cost": "Lawyer Cost",
"mediator_lawyer_cost": "Mediator Lawyer Cost",
"other_cost": "Other Cost",
"legal_cost": "Legal Cost",
"approved_cost": "Approved Cost",
"total_price": "Total Price",
"build_db_item_id": "Build Decision Book Item ID",
"build_db_item_uu_id": "Build Decision Book Item UUID",
"resp_attorney_id": "Resp Attorney ID",
"resp_attorney_uu_id": "Resp Attorney UUID",
"resp_attorney_company_id": "Resp Attorney Company ID",
"resp_attorney_company_uu_id": "Resp Attorney Company UUID",
"mediator_lawyer_person_id": "Mediator Lawyer Person ID",
"mediator_lawyer_person_uu_id": "Mediator Lawyer Person UUID",
},
)
BuildDecisionBookProjectsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"project_no": "Proje No",
"project_name": "Proje Adı",
"project_start_date": "Proje Başlangıç Tarihi",
"project_stop_date": "Proje Bitiş Tarihi",
"project_type": "Proje Türü",
"project_note": "Proje Notu",
"decision_book_pdf_path": "Karar Defteri PDF Yolu",
"is_completed": "Proje Tamamlandı",
"status_code": "Durum Kodu",
"resp_company_fix_wage": "Firma Sabit Ücreti",
"is_out_sourced": "Dış Kaynak Kullanımı",
"meeting_date": "Toplantı Tarihi",
"currency": "Para Birimi",
"bid_price": "Teklif Fiyatı",
"approved_price": "Onaylanan Fiyat",
"final_price": "Son Fiyat",
"contact_id": "İletişim ID",
"contact_uu_id": "İletişim UUID",
"build_decision_book_id": "Karar Defteri ID",
"build_decision_book_uu_id": "Karar Defteri UUID",
"build_decision_book_item_id": "Karar Defteri Madde ID",
"build_decision_book_item_uu_id": "Karar Defteri Madde UUID",
"project_response_living_space_id": "Proje Yanıt Yaşam Alanı ID",
"project_response_living_space_uu_id": "Proje Yanıt Yaşam Alanı UUID",
"resp_company_id": "Sorumlu Firma ID",
"resp_company_uu_id": "Sorumlu Firma UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"project_no": "Project No",
"project_name": "Project Name",
"project_start_date": "Project Start Date",
"project_stop_date": "Project Stop Date",
"project_type": "Project Type",
"project_note": "Project Note",
"decision_book_pdf_path": "Decision Book PDF Path",
"is_completed": "Is Completed",
"status_code": "Status Code",
"resp_company_fix_wage": "Resp Company Fix Wage",
"is_out_sourced": "Is Out Sourced",
"meeting_date": "Meeting Date",
"currency": "Currency",
"bid_price": "Bid Price",
"approved_price": "Approved Price",
"final_price": "Final Price",
"contact_id": "Contact ID",
"contact_uu_id": "Contact UUID",
"build_decision_book_id": "Build Decision Book ID",
"build_decision_book_uu_id": "Build Decision Book UUID",
"build_decision_book_item_id": "Build Decision Book Item ID",
"build_decision_book_item_uu_id": "Build Decision Book Item UUID",
"project_response_living_space_id": "Project Response Living Space ID",
"project_response_living_space_uu_id": "Project Response Living Space UUID",
"resp_company_id": "Resp Company ID",
"resp_company_uu_id": "Resp Company UUID",
},
)
BuildDecisionBookProjectPersonLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"dues_percent_discount": "Aidat İndirim Oranı",
"job_fix_wage": "İş Sabit Ücreti",
"bid_price": "Teklif Fiyatı",
"decision_price": "Karar Fiyatı",
"build_decision_book_project_id": "Karar Defteri Proje ID",
"build_decision_book_project_uu_id": "Karar Defteri Proje UUID",
"living_space_id": "Yaşam Alanı ID",
"living_space_uu_id": "Yaşam Alanı UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"dues_percent_discount": "Dues Percent Discount",
"job_fix_wage": "Job Fix Wage",
"bid_price": "Bid Price",
"decision_price": "Decision Price",
"build_decision_book_project_id": "Build Decision Book Project ID",
"build_decision_book_project_uu_id": "Build Decision Book Project UUID",
"living_space_id": "Living Space ID",
"living_space_uu_id": "Living Space UUID",
},
)
BuildDecisionBookProjectItemsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"item_header": "Madde Başlığı",
"item_comment": "Madde Yorumu",
"attachment_pdf_path": "Ek PDF Yolu",
"item_estimated_cost": "Tahmini Maliyet",
"item_short_comment": "Kısa Yorum",
"build_decision_book_project_id": "Karar Defteri Proje ID",
"build_decision_book_project_uu_id": "Karar Defteri Proje UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"item_header": "Item Header",
"item_comment": "Item Comment",
"attachment_pdf_path": "Attachment PDF Path",
"item_estimated_cost": "Estimated Cost",
"item_short_comment": "Item Short Comment",
"build_decision_book_project_id": "Build Decision Book Project ID",
"build_decision_book_project_uu_id": "Build Decision Book Project UUID",
},
)

View File

@ -0,0 +1,67 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
RelationshipDutyCompanyLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"owner_id": "Sahip ID",
"duties_id": "Görev ID",
"member_id": "Üye ID",
"parent_id": "Üst ID",
"relationship_type": "İlişki Tipi",
"child_count": "Çocuk Sayısı",
"show_only": "Sadece Göster",
},
en={
**CrudCollectionLanguageModel["en"],
"owner_id": "Owner ID",
"duties_id": "Duties ID",
"member_id": "Member ID",
"parent_id": "Parent ID",
"relationship_type": "Relationship Type",
"child_count": "Child Count",
"show_only": "Show Only",
},
)
CompaniesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"formal_name": "Resmi Ad",
"company_type": "Şirket Tipi",
"commercial_type": "Ticari Tip",
"tax_no": "Vergi No",
"public_name": "Kamu Adı",
"company_tag": "Şirket Etiketi",
"default_lang_type": "Varsayılan Dil Tipi",
"default_money_type": "Varsayılan Para Tipi",
"is_commercial": "Ticari",
"is_blacklist": "Kara Liste",
"parent_id": "Üst ID",
"workplace_no": "İşyeri No",
"official_address_id": "Resmi Adres ID",
"official_address_uu_id": "Resmi Adres UUID",
"top_responsible_company_id": "Üst Sorumlu Şirket ID",
"top_responsible_company_uu_id": "Üst Sorumlu Şirket UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"formal_name": "Formal Name",
"company_type": "Company Type",
"commercial_type": "Commercial Type",
"tax_no": "Tax No",
"public_name": "Public Name",
"company_tag": "Company Tag",
"default_lang_type": "Default Language Type",
"default_money_type": "Default Money Type",
"is_commercial": "Commercial",
"is_blacklist": "Blacklist",
"parent_id": "Parent ID",
"workplace_no": "Workplace No",
"official_address_id": "Official Address ID",
"official_address_uu_id": "Official Address UUID",
"top_responsible_company_id": "Top Responsible Company ID",
"top_responsible_company_uu_id": "Top Responsible Company UUID",
},
)

View File

@ -0,0 +1,64 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
DepartmentsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"parent_department_id": "Üst Departman ID",
"department_code": "Departman Kodu",
"department_name": "Departman Adı",
"department_description": "Departman Açıklaması",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"parent_department_id": "Parent Department ID",
"department_code": "Department Code",
"department_name": "Department Name",
"department_description": "Department Description",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
},
)
DutiesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"users_default_duty": "Kullanıcılar için Varsayılan Görev",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
"duties_id": "Görev ID",
"duties_uu_id": "Görev UUID",
"department_id": "Departman ID",
"department_uu_id": "Departman UUID",
"management_duty": "Yönetim Görevi",
},
en={
**CrudCollectionLanguageModel["en"],
"users_default_duty": "Default Duty for Users",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
"duties_id": "Duty ID",
"duties_uu_id": "Duty UUID",
"department_id": "Department ID",
"department_uu_id": "Department UUID",
"management_duty": "Management Duty",
},
)
DutyLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"duty_name": "Görev Adı",
"duty_code": "Görev Kodu",
"duty_description": "Görev Açıklaması",
},
en={
**CrudCollectionLanguageModel["en"],
"duty_name": "Duty Name",
"duty_code": "Duty Code",
"duty_description": "Duty Description",
},
)

View File

@ -0,0 +1,73 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
StaffLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"staff_description": "Personel Açıklaması",
"staff_name": "Personel Adı",
"staff_code": "Personel Kodu",
"duties_id": "Görev ID",
"duties_uu_id": "Görev UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"staff_description": "Staff Description",
"staff_name": "Staff Name",
"staff_code": "Staff Code",
"duties_id": "Duty ID",
"duties_uu_id": "Duty UUID",
},
)
EmployeesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"staff_id": "Personel ID",
"staff_uu_id": "Personel UUID",
"people_id": "Kişi ID",
"people_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"staff_id": "Staff ID",
"staff_uu_id": "Staff UUID",
"people_id": "People ID",
"people_uu_id": "People UUID",
},
)
EmployeeHistoryLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"staff_id": "Personel ID",
"staff_uu_id": "Personel UUID",
"people_id": "Kişi ID",
"people_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"staff_id": "Staff ID",
"staff_uu_id": "Staff UUID",
"people_id": "People ID",
"people_uu_id": "People UUID",
},
)
EmployeesSalariesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"gross_salary": "Brüt Maaş",
"net_salary": "Net Maaş",
"people_id": "Kişi ID",
"people_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"gross_salary": "Gross Salary",
"net_salary": "Net Salary",
"people_id": "People ID",
"people_uu_id": "People UUID",
},
)

View File

@ -0,0 +1,187 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
EventsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"event_type": "Etkinlik Türü",
"function_code": "Fonksiyon Kodu",
"function_class": "Fonksiyon Sınıfı",
"description": "ıklama",
"property_description": "Özellik Açıklaması",
"marketing_layer": "Pazarlama Katmanı",
"cost": "Maliyet",
"unit_price": "Birim Fiyat",
"endpoint_id": "Endpoint ID",
"endpoint_uu_id": "Endpoint UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"event_type": "Event Type",
"function_code": "Function Code",
"function_class": "Function Class",
"description": "Description",
"property_description": "Property Description",
"marketing_layer": "Marketing Layer",
"cost": "Cost",
"unit_price": "Unit Price",
"endpoint_id": "Endpoint ID",
"endpoint_uu_id": "Endpoint UUID",
},
)
ModulesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"module_name": "Modül Adı",
"module_description": "Modül Açıklaması",
"module_code": "Modül Kodu",
"module_layer": "Modül Katmanı",
"is_default_module": "Varsayılan Modül",
},
en={
**CrudCollectionLanguageModel["en"],
"module_name": "Module Name",
"module_description": "Module Description",
"module_code": "Module Code",
"module_layer": "Module Layer",
"is_default_module": "Default Module",
},
)
ServicesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"module_id": "Modül ID",
"module_uu_id": "Modül UUID",
"service_name": "Servis Adı",
"service_description": "Servis Açıklaması",
"service_code": "Servis Kodu",
"related_responsibility": "İlgili Sorumluluk",
},
en={
**CrudCollectionLanguageModel["en"],
"module_id": "Module ID",
"module_uu_id": "Module UUID",
"service_name": "Service Name",
"service_description": "Service Description",
"service_code": "Service Code",
"related_responsibility": "Related Responsibility",
},
)
Service2EventsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"service_id": "Servis ID",
"service_uu_id": "Servis UUID",
"event_id": "Etkinlik ID",
"event_uu_id": "Etkinlik UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"service_id": "Service ID",
"service_uu_id": "Service UUID",
"event_id": "Event ID",
"event_uu_id": "Event UUID",
},
)
Event2OccupantExtraLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_living_space_id": "Bina Yaşam Alanı ID",
"build_living_space_uu_id": "Bina Yaşam Alanı UUID",
"event_id": "Etkinlik ID",
"event_uu_id": "Etkinlik UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_living_space_id": "Build Living Space ID",
"build_living_space_uu_id": "Build Living Space UUID",
"event_id": "Event ID",
"event_uu_id": "Event UUID",
},
)
Event2EmployeeExtraLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"employee_id": "Çalışan ID",
"employee_uu_id": "Çalışan UUID",
"event_id": "Etkinlik ID",
"event_uu_id": "Etkinlik UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"employee_id": "Employee ID",
"employee_uu_id": "Employee UUID",
"event_id": "Event ID",
"event_uu_id": "Event UUID",
},
)
Event2EmployeeLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"employee_id": "Çalışan ID",
"employee_uu_id": "Çalışan UUID",
"event_service_id": "Etkinlik Servis ID",
"event_service_uu_id": "Etkinlik Servis UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"employee_id": "Employee ID",
"employee_uu_id": "Employee UUID",
"event_service_id": "Event Service ID",
"event_service_uu_id": "Event Service UUID",
},
)
Event2OccupantLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_living_space_id": "Bina Yaşam Alanı ID",
"build_living_space_uu_id": "Bina Yaşam Alanı UUID",
"event_service_id": "Etkinlik Servis ID",
"event_service_uu_id": "Etkinlik Servis UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_living_space_id": "Build Living Space ID",
"build_living_space_uu_id": "Build Living Space UUID",
"event_service_id": "Event Service ID",
"event_service_uu_id": "Event Service UUID",
},
)
ModulePriceLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"campaign_code": "Kampanya Kodu",
"module_id": "Modül ID",
"module_uu_id": "Modül UUID",
"service_id": "Servis ID",
"service_uu_id": "Servis UUID",
"event_id": "Etkinlik ID",
"event_uu_id": "Etkinlik UUID",
"is_counted_percentage": "İndirim Oranı",
"discounted_price": "İndirimli Fiyat",
"calculated_price": "Hesaplanan Fiyat",
},
en={
**CrudCollectionLanguageModel["en"],
"campaign_code": "Campaign Code",
"module_id": "Module ID",
"module_uu_id": "Module UUID",
"service_id": "Service ID",
"service_uu_id": "Service UUID",
"event_id": "Event ID",
"event_uu_id": "Event UUID",
"is_counted_percentage": "Discount Rate",
"discounted_price": "Discounted Price",
"calculated_price": "Calculated Price",
},
)

View File

@ -0,0 +1,426 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
UsersTokensLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"user_id": "Kullanıcı ID",
"token_type": "Token Türü",
"token": "Token",
"domain": "Domain",
"expires_at": "Bitiş Tarihi",
},
en={
**CrudCollectionLanguageModel["en"],
"user_id": "User ID",
"token_type": "Token Type",
"token": "Token",
"domain": "Domain",
"expires_at": "Expires At",
},
)
UsersLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"user_tag": "Kullanıcı Etiketi",
"email": "E-posta",
"phone_number": "Telefon Numarası",
"via": "Via",
"avatar": "Avatar",
"hash_password": "Şifre",
"password_token": "Şifre Token",
"remember_me": "Beni Hatırla",
"password_expires_day": "Şifre Son Kullanma Günü",
"password_expiry_begins": "Şifre Son Kullanma Başlangıç",
"related_company": "İlgili Şirket",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"user_tag": "User Tag",
"email": "Email",
"phone_number": "Phone Number",
"via": "Via",
"avatar": "Avatar",
"hash_password": "Password",
"password_token": "Password Token",
"remember_me": "Remember Me",
"password_expires_day": "Password Expires Day",
"password_expiry_begins": "Password Expiry Begins",
"related_company": "Related Company",
"person_id": "Person ID",
"person_uu_id": "Person UUID",
},
)
RelationshipDutyPeopleLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"company_id": "Şirket ID",
"duties_id": "Görev ID",
"member_id": "Üye ID",
"relationship_type": "İlişki Türü",
"show_only": "Sadece Göster",
},
en={
**CrudCollectionLanguageModel["en"],
"company_id": "Company ID",
"duties_id": "Duty ID",
"member_id": "Member ID",
"relationship_type": "Relationship Type",
"show_only": "Show Only",
},
)
PeopleLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"firstname": "Ad",
"surname": "Soyad",
"middle_name": "Orta Ad",
"sex_code": "Cinsiyet Kodu",
"person_ref": "Kişi Referansı",
"person_tag": "Kişi Etiketi",
"father_name": "Baba Adı",
"mother_name": "Anne Adı",
"country_code": "Ülke Kodu",
"national_identity_id": "Kimlik Numarası",
"birth_place": "Doğum Yeri",
"birth_date": "Doğum Tarihi",
"tax_no": "Vergi Numarası",
},
en={
**CrudCollectionLanguageModel["en"],
"firstname": "First Name",
"surname": "Last Name",
"middle_name": "Middle Name",
"sex_code": "Gender",
"person_ref": "Person Reference",
"person_tag": "Person Tag",
"father_name": "Father Name",
"mother_name": "Mother Name",
"country_code": "Country Code",
"national_identity_id": "National Identity ID",
"birth_place": "Birth Place",
"birth_date": "Birth Date",
"tax_no": "Tax No",
},
)
RelationshipEmployee2PostCodeLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"company_id": "Şirket ID",
"employee_id": "Çalışan ID",
"member_id": "Üye ID",
"relationship_type": "İlişki Türü",
"show_only": "Sadece Göster",
},
en={
**CrudCollectionLanguageModel["en"],
"company_id": "Company ID",
"employee_id": "Employee ID",
"member_id": "Member ID",
"relationship_type": "Relationship Type",
"show_only": "Show Only",
},
)
AddressPostcodeLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"street_id": "Sokak ID",
"street_uu_id": "Sokak UUID",
"postcode": "Posta Kodu",
},
en={
**CrudCollectionLanguageModel["en"],
"street_id": "Street ID",
"street_uu_id": "Street UUID",
"postcode": "Postcode",
},
)
AddressesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"build_number": "Bina Numarası",
"door_number": "Kapı Numarası",
"floor_number": "Kat Numarası",
"comment_address": "Adres",
"letter_address": "Adres",
"short_letter_address": "Adres",
"latitude": "Enlem",
"longitude": "Boylam",
"street_id": "Sokak ID",
"street_uu_id": "Sokak UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"build_number": "Build Number",
"door_number": "Door Number",
"floor_number": "Floor Number",
"comment_address": "Address",
"letter_address": "Address",
"short_letter_address": "Address",
"latitude": "Latitude",
"longitude": "Longitude",
"street_id": "Street ID",
"street_uu_id": "Street UUID",
},
)
AddressGeographicLocationsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"geo_table": "Tablo Adı",
"geo_id": "ID",
"geo_name": "Ad",
"geo_latitude": "Enlem",
"geo_longitude": "Boylam",
"geo_altitude": "Yükseklik",
"geo_description": "ıklama",
"geo_area_size": "Alan",
"geo_population": "Nüfus",
},
en={
**CrudCollectionLanguageModel["en"],
"geo_table": "Table Name",
"geo_id": "ID",
"geo_name": "Name",
"geo_latitude": "Latitude",
"geo_longitude": "Longitude",
"geo_altitude": "Altitude",
"geo_description": "Description",
"geo_area_size": "Area",
"geo_population": "Population",
},
)
AddressCountryLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"country_code": "Ülke Kodu",
"country_name": "Ülke Adı",
"money_code": "Para Kodu",
"language": "Dil Kodu",
"address_geographic_id": "Adres Coğrafi ID",
},
en={
**CrudCollectionLanguageModel["en"],
"country_code": "Country Code",
"country_name": "Country Name",
"money_code": "Money Code",
"language": "Language Code",
"address_geographic_id": "Address Geographic ID",
},
)
AddressStateLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"state_code": "Eyalet Kodu",
"state_name": "Eyalet Adı",
"licence_plate": "Plaka Kodu",
"phone_code": "Telefon Kodu",
"gov_code": "Hükümet Kodu",
"address_geographic_id": "Adres Coğrafi ID",
"country_id": "Ülke ID",
"country_uu_id": "Ülke UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"state_code": "State Code",
"state_name": "State Name",
"licence_plate": "Licence Plate",
"phone_code": "Phone Code",
"gov_code": "Government Code",
"address_geographic_id": "Address Geographic ID",
"country_id": "Country ID",
"country_uu_id": "Country UUID",
},
)
AddressCityLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"city_code": "Şehir Kodu",
"city_name": "Şehir Adı",
"licence_plate": "Plaka Kodu",
"phone_code": "Telefon Kodu",
"gov_code": "Hükümet Kodu",
"address_geographic_id": "Adres Coğrafi ID",
"state_id": "Eyalet ID",
"state_uu_id": "Eyalet UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"city_code": "City Code",
"city_name": "City Name",
"licence_plate": "Licence Plate",
"phone_code": "Phone Code",
"gov_code": "Government Code",
"address_geographic_id": "Address Geographic ID",
"state_id": "State ID",
"state_uu_id": "State UUID",
},
)
AddressDistrictLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"district_code": "İlçe Kodu",
"district_name": "İlçe Adı",
"phone_code": "Telefon Kodu",
"gov_code": "Hükümet Kodu",
"address_geographic_id": "Adres Coğrafi ID",
"city_id": "Şehir ID",
"city_uu_id": "Şehir UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"district_code": "District Code",
"district_name": "District Name",
"phone_code": "Phone Code",
"gov_code": "Government Code",
"address_geographic_id": "Address Geographic ID",
"city_id": "City ID",
"city_uu_id": "City UUID",
},
)
AddressLocalityLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"locality_code": "Mahalle Kodu",
"locality_name": "Mahalle Adı",
"type_code": "Tip Kodu",
"type_description": "Tip Açıklaması",
"gov_code": "Hükümet Kodu",
"address_show": "Adres Göster",
"address_geographic_id": "Adres Coğrafi ID",
"district_id": "İlçe ID",
"district_uu_id": "İlçe UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"locality_code": "Locality Code",
"locality_name": "Locality Name",
"type_code": "Type Code",
"type_description": "Type Description",
"gov_code": "Government Code",
"address_show": "Address Show",
"address_geographic_id": "Address Geographic ID",
"district_id": "District ID",
"district_uu_id": "District UUID",
},
)
AddressNeighborhoodLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"neighborhood_code": "Mahalle Kodu",
"neighborhood_name": "Mahalle Adı",
"type_code": "Tip Kodu",
"type_description": "Tip Açıklaması",
"gov_code": "Hükümet Kodu",
"address_show": "Adres Göster",
"address_geographic_id": "Adres Coğrafi ID",
"district_id": "İlçe ID",
"district_uu_id": "İlçe UUID",
"locality_id": "Mahalle ID",
"locality_uu_id": "Mahalle UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"neighborhood_code": "Neighborhood Code",
"neighborhood_name": "Neighborhood Name",
"type_code": "Type Code",
"type_description": "Type Description",
"gov_code": "Government Code",
"address_show": "Address Show",
"address_geographic_id": "Address Geographic ID",
"district_id": "District ID",
"district_uu_id": "District UUID",
"locality_id": "Locality ID",
"locality_uu_id": "Locality UUID",
},
)
AddressStreetLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"street_code": "Sokak Kodu",
"street_name": "Sokak Adı",
"type_code": "Tip Kodu",
"type_description": "Tip Açıklaması",
"gov_code": "Hükümet Kodu",
"address_geographic_id": "Adres Coğrafi ID",
"neighborhood_id": "Mahalle ID",
"neighborhood_uu_id": "Mahalle UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"street_code": "Street Code",
"street_name": "Street Name",
"type_code": "Type Code",
"type_description": "Type Description",
"gov_code": "Government Code",
"address_geographic_id": "Address Geographic ID",
"neighborhood_id": "Neighborhood ID",
"neighborhood_uu_id": "Neighborhood UUID",
},
)
OccupantTypesLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"occupant_type": "Kişi Türü",
"occupant_description": "Kişi Açıklaması",
"occupant_code": "Kişi Kodu",
"occupant_category": "Kişi Kategori",
"occupant_category_type": "Kişi Kategori Türü",
"occupant_is_unique": "Kişi Benzersiz",
},
en={
**CrudCollectionLanguageModel["en"],
"occupant_type": "Occupant Type",
"occupant_description": "Occupant Description",
"occupant_code": "Occupant Code",
"occupant_category": "Occupant Category",
"occupant_category_type": "Occupant Category Type",
"occupant_is_unique": "Occupant Unique",
},
)
ContractsLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"contract_type": "Sözleşme Türü",
"contract_title": "Sözleşme Başlığı",
"contract_details": "Sözleşme Detayları",
"contract_terms": "Sözleşme Şartları",
"contract_code": "Sözleşme Kodu",
"contract_date": "Sözleşme Tarihi",
"company_id": "Şirket ID",
"company_uu_id": "Şirket UUID",
"person_id": "Kişi ID",
"person_uu_id": "Kişi UUID",
},
en={
**CrudCollectionLanguageModel["en"],
"contract_type": "Contract Type",
"contract_title": "Contract Title",
"contract_details": "Contract Details",
"contract_terms": "Contract Terms",
"contract_code": "Contract Code",
"contract_date": "Contract Date",
"company_id": "Company ID",
"company_uu_id": "Company UUID",
"person_id": "Person ID",
"person_uu_id": "Person UUID",
},
)

View File

@ -0,0 +1,22 @@
from ApiLayers.LanguageModels.Database.Mixins.crud_mixin import (
CrudCollectionLanguageModel,
)
EndpointRestrictionLanguageModel = dict(
tr={
**CrudCollectionLanguageModel["tr"],
"endpoint_function": "API Fonksiyonu",
"endpoint_name": "API Adı",
"endpoint_method": "API Metodu",
"endpoint_desc": "API Açıklaması",
"endpoint_code": "API Kodu",
},
en={
**CrudCollectionLanguageModel["en"],
"endpoint_function": "API Function",
"endpoint_name": "API Name",
"endpoint_method": "API Method",
"endpoint_desc": "API Description",
"endpoint_code": "API Code",
},
)

View File

@ -0,0 +1,4 @@
from .defualt_error import default_errors
all_errors_list = [default_errors]

View File

@ -0,0 +1,35 @@
class BaseErrorLanguageModelTurkish:
NOT_CREATED: str = "Kayıt oluşturulamadı."
NOT_DELETED: str = "Kayıt silinemedi."
NOT_UPDATED: str = "Kayıt güncellenemedi."
NOT_LISTED: str = "Kayıt listelenemedi."
NOT_FOUND: str = "Kayıt bulunamadı."
ALREADY_EXISTS: str = "Kayıt zaten mevcut."
IS_NOT_CONFIRMED: str = "Kayıt onaylanmadı."
NOT_AUTHORIZED: str = "Yetkisiz kullanıcı."
NOT_VALID: str = "Gecersiz veri."
NOT_ACCEPTABLE: str = "Gecersiz veri."
INVALID_DATA: str = "Gecersiz veri."
UNKNOWN_ERROR: str = "Bilinmeyen bir hata oluştu."
class BaseErrorLanguageModelEnglish:
NOT_CREATED: str = "Not Created."
NOT_DELETED: str = "Not Deleted."
NOT_UPDATED: str = "Not Updated."
NOT_LISTED: str = "Not Listed."
NOT_FOUND: str = "Not Found."
ALREADY_EXISTS: str = "Already Exists."
IS_NOT_CONFIRMED: str = "Not Confirmed."
NOT_AUTHORIZED: str = "Not Authorized."
NOT_VALID: str = "Not Valid."
NOT_ACCEPTABLE: str = "Not Acceptable."
INVALID_DATA: str = "Invalid Data."
UNKNOWN_ERROR: str = "Unknown Error occured."
class BaseErrorLanguageModels:
tr: BaseErrorLanguageModelTurkish = BaseErrorLanguageModelTurkish
en: BaseErrorLanguageModelEnglish = BaseErrorLanguageModelEnglish

View File

@ -0,0 +1,98 @@
default_errors = {
"NOT_CREATED": {
"tr": {
"message": "Kayıt oluşturulamadı. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record could not be created. Please try again.",
},
},
"NOT_DELETED": {
"tr": {
"message": "Kayıt silinemedi. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record could not be deleted. Please try again.",
},
},
"NOT_UPDATED": {
"tr": {
"message": "Kayıt güncellenemedi. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record could not be updated. Please try again.",
},
},
"NOT_LISTED": {
"tr": {
"message": "Kayıt listelenemedi. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record could not be listed. Please try again.",
},
},
"NOT_FOUND": {
"tr": {
"message": "Kayıt bulunamadı. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record could not be found. Please try again.",
},
},
"ALREADY_EXISTS": {
"tr": {
"message": "Kayıt zaten mevcut. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record already exists. Please try again.",
},
},
"IS_NOT_CONFIRMED": {
"tr": {
"message": "Kayıt onaylanmadı. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Record is not confirmed. Please try again.",
},
},
"NOT_AUTHORIZED": {
"tr": {
"message": "Yetkisiz kullanıcı. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Unauthorized user. Please try again.",
},
},
"NOT_VALID": {
"tr": {
"message": "Geçersiz veri. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Invalid data. Please try again.",
},
},
"NOT_ACCEPTABLE": {
"tr": {
"message": "Geçersiz veri. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Invalid data. Please try again.",
},
},
"INVALID_DATA": {
"tr": {
"message": "Geçersiz veri. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "Invalid data. Please try again.",
},
},
"UNKNOWN_ERROR": {
"tr": {
"message": "Bilinmeyen bir hata oluştu. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "An unknown error occured. Please try again.",
},
},
}

View File

@ -0,0 +1,18 @@
from ApiLayers.LanguageModels.Errors.base_languages import BaseErrorLanguageModels
class MergedErrorLanguageModels:
list_of_languages = [BaseErrorLanguageModels]
@classmethod
def get_language_models(cls, language: str):
language_model_keys = {}
for list_of_language in cls.list_of_languages:
language_model_class = getattr(list_of_language, language, None)
clean_dict = {
key: value
for key, value in language_model_class.__dict__.items()
if "__" not in str(key)[0:3]
}
language_model_keys.update(clean_dict)
return language_model_keys

View File

@ -0,0 +1,29 @@
from typing import Dict
LoginRequestLanguageModel: Dict[str, Dict[str, str]] = {
"tr": {
"domain": "Domain",
"access_key": "Erişim Anahtarı",
"password": "Parola",
"remember_me": "Beni Hatırla",
},
"en": {
"domain": "Domain",
"access_key": "Access Key",
"password": "Password",
"remember_me": "Remember Me",
},
}
SelectRequestLanguageModel: Dict[str, Dict[str, str]] = {
"tr": {
"company_uu_id": "Şirket UU ID",
"build_living_space_uu_id": "Bina Konut UU ID",
},
"en": {
"company_uu_id": "Company UU ID",
"build_living_space_uu_id": "Build Living Space UU ID",
},
}

View File

@ -0,0 +1,9 @@
from .Auth.login import (
LoginRequestLanguageModel,
SelectRequestLanguageModel,
)
__all__ = [
"LoginRequestLanguageModel",
"SelectRequestLanguageModel",
]

View File

@ -0,0 +1,26 @@
accountResponses = {
"ACCOUNTS_LIST": {
"tr": {
"message": "Hesap Bilgileri gönderilen sorgu ve filtreleme seçeneklerine göre başarılı bir şekilde listelendi.",
},
"en": {
"message": "Account Information listed successfully regarding to the sent query and filtering options.",
},
},
"ACCOUNT_CREATED": {
"tr": {
"message": "Hesap bilgileri başarılı bir şekilde eklendi.",
},
"en": {
"message": "Account information added successfully.",
},
},
"ACCOUNT_UPDATED": {
"tr": {
"message": "Hesap bilgileri başarılı bir şekilde güncellendi.",
},
"en": {
"message": "Account information updated successfully.",
},
},
}

View File

@ -0,0 +1,5 @@
from .authentication.auth import authResponses
from .accounts.accounts import accountResponses
all_response_list = [authResponses, accountResponses]

View File

@ -0,0 +1,98 @@
authResponses = {
"LOGIN_SELECT": {
"tr": {
"message": "Şirket/Görev başarılı bir şekilde seçildi.",
},
"en": {
"message": "Company/Duty selected successfully.",
},
},
"LOGIN_SUCCESS": {
"tr": {
"message": "Giriş başırı ile tamamlandı. Devam etmek için bir şirket/görev seçiniz.",
},
"en": {
"message": "Login successful. Please select an company/duty to continue.",
},
},
"TOKEN_VALID": {
"tr": {
"message": "Header'da belirtilen token geçerli.",
},
"en": {
"message": "The token specified in the header is valid.",
},
},
"USER_INFO_REFRESHED": {
"tr": {
"message": "Token aracılığıyla kullanıcı bilgileri başarılı bir şekilde güncellendi.",
},
"en": {
"message": "User information updated successfully via token.",
},
},
"CREATED_PASSWORD": {
"tr": {
"message": "Şifre başarılı bir şekilde oluşturuldu.",
},
"en": {
"message": "Password created successfully.",
},
},
"PASSWORD_CHANGED": {
"tr": {
"message": "Şifre başarılı bir şekilde değiştirildi.",
},
"en": {
"message": "Password changed successfully.",
},
},
"LOGOUT_USER": {
"tr": {
"message": "Kullanıcı başarılı bir şekilde çıkış yaptı.",
},
"en": {
"message": "User successfully logged out.",
},
},
"DISCONNECTED_USER": {
"tr": {
"message": "Kullanıcı tüm cihazlardan başarılı bir şekilde çıkış yaptı.",
},
"en": {
"message": "User successfully logged out of all devices.",
},
},
"USER_NOT_FOUND": {
"tr": {
"message": "Kullanıcı bulunamadı. Lütfen tekrar deneyiniz.",
},
"en": {
"message": "User not found. Please try again.",
},
},
"FORGOT_PASSWORD": {
"tr": {
"message": "Şifre sıfırlama talebi başarılı bir şekilde oluşturuldu.",
},
"en": {
"message": "Password reset request created successfully.",
},
},
"USER_AVATAR": {
"tr": {
"message": "Kullanıcı avatarı data blogunda belirtildiği şekildedir.",
},
"en": {
"message": "User avatar is as specified in the data block.",
},
},
"TOKEN_REFRESH": {
"tr": {
"message": "Token başarılı bir şekilde yenilendi.",
},
"en": {
"message": "Token successfully refreshed.",
},
},
}

View File

@ -0,0 +1,227 @@
from Events.Engine import MethodToEvent
from Events.Engine.abstract_class import PageInfo
# from .account_records import (
# AccountRecordsUpdateEventMethods,
# AccountRecordsCreateEventMethods,
# AccountRecordsListEventMethods,
# )
cluster_name = "AccountCluster"
prefix = "/accounts"
class AccountRecordsUpdateEventMethods(MethodToEvent):
pass
class AccountRecordsCreateEventMethods(MethodToEvent):
pass
class AccountRecordsListEventMethods(MethodToEvent):
pass
class LanguageModels:
SITE_URL: str
COMPONENT: str = "Table"
PREFIX_URL: str = ""
PAGE_INFO: dict
def as_dict(self):
return {
"SITE_URL": self.SITE_URL,
"COMPONENT": self.COMPONENT,
"PREFIX_URL": self.PREFIX_URL,
"PAGE_INFO": self.PAGE_INFO,
}
account_language_update_models = LanguageModels()
account_language_update_models.COMPONENT = "Link"
account_language_update_models.SITE_URL = f"/update?site={cluster_name}"
account_language_update_models.PREFIX_URL = (
f"{prefix}{AccountRecordsUpdateEventMethods.URL}"
)
account_language_update_models.PAGE_INFO = {
"en": {
"page": "Update Account Records",
},
"tr": {
"page": "Hesap Kayıdı Güncelle",
},
}
account_language_model_as_dict = account_language_update_models.as_dict()
account_language_created_models = LanguageModels()
account_language_created_models.COMPONENT = "Link"
account_language_created_models.SITE_URL = f"/create?site={cluster_name}"
account_language_created_models.PREFIX_URL = (
f"{prefix}{AccountRecordsCreateEventMethods.URL}"
)
account_language_created_models.PAGE_INFO = {
"en": {
"page": "Create Account Records",
},
"tr": {"page": "Hesap Kayıdı Oluştur"},
}
account_language_created_models_as_dict = account_language_created_models.as_dict()
account_language_list_models = LanguageModels()
account_language_list_models.COMPONENT = "Table"
account_language_list_models.SITE_URL = f"/list?site={cluster_name}"
account_language_list_models.PREFIX_URL = (
f"{prefix}{AccountRecordsListEventMethods.URL}"
)
account_language_list_models.PAGE_INFO = {
"en": {
"page": "List Account Records",
},
"tr": {
"page": "Hesap Kayıtlarını Listele",
},
}
account_language_list_models_as_dict = account_language_list_models.as_dict()
account_language_create_models = LanguageModels()
account_language_create_models.COMPONENT = "Form"
account_language_create_models.SITE_URL = f"/create?site={cluster_name}"
account_language_create_models.PREFIX_URL = (
f"{prefix}{AccountRecordsListEventMethods.URL}"
)
account_language_create_models.PAGE_INFO = {
"en": {"page": "List Account Records", "button:": "Create"},
"tr": {"page": "Hesap Kayıtlarını Listele", "button:": "Oluştur"},
}
account_language_create_models_as_dict = account_language_create_models.as_dict()
account_language_update_form_models = LanguageModels()
account_language_update_form_models.COMPONENT = "Form"
account_language_update_form_models.SITE_URL = f"/update?site={cluster_name}"
account_language_update_form_models.PREFIX_URL = (
f"{prefix}{AccountRecordsUpdateEventMethods.URL}"
)
account_language_update_form_models.PAGE_INFO = {
"en": {"page": "Update Account Records", "button:": "Update"},
"tr": {"page": "Hesap Kayıdı Güncelle", "button:": "Güncelle"},
}
account_language_update_form_models_as_dict = (
account_language_update_form_models.as_dict()
)
create_key = f"{prefix}{AccountRecordsCreateEventMethods.URL}"
update_key = f"{prefix}{AccountRecordsUpdateEventMethods.URL}"
list_key = f"{prefix}{AccountRecordsListEventMethods.URL}"
dashboard_page_info = PageInfo(
name=f"{cluster_name}",
url=f"/dashboard?site={cluster_name}",
icon="Building",
instructions={
str(list_key): {
"headers": {
"store": True,
"url": "/validations/header",
"data": {"event_code": f"{prefix}/list", "asked_field": "headers"},
},
"data": {
"store": True,
"url": f"{prefix}/list",
"data": dict(page=1, limit=1),
},
},
},
page_info={
"page": {
"en": "Account Records for reaching user all types account information",
"tr": "Kullanıcı tüm hesap bilgilerine ulaşmak için Hesap Kayıtları",
},
},
endpoints={
str(update_key): AccountRecordsUpdateEventMethods.retrieve_all_event_keys(),
str(create_key): AccountRecordsCreateEventMethods.retrieve_all_event_keys(),
str(list_key): AccountRecordsListEventMethods.retrieve_all_event_keys(),
},
language_models={
account_language_update_models.PREFIX_URL: account_language_model_as_dict,
account_language_created_models.PREFIX_URL: account_language_created_models_as_dict,
account_language_list_models.PREFIX_URL: account_language_list_models_as_dict,
},
)
create_page_info = PageInfo(
name=f"{cluster_name}",
url=f"/create?site={cluster_name}",
icon="Building",
instructions={
str(create_key): {
"validation": {
"store": True,
"url": "/validations/validation",
"data": {"event_code": f"{prefix}/create", "asked_field": "validation"},
},
"headers": {
"store": True,
"url": "/validations/header",
"data": {"event_code": f"{prefix}/create", "asked_field": "headers"},
},
},
},
page_info={
"page": {
"en": "Account Records creating for user all types account information",
"tr": "Kullanıcı tüm hesap bilgilerine ulaşmak için Hesap Kayıtları oluştur",
},
},
endpoints={
str(create_key): AccountRecordsCreateEventMethods.retrieve_all_event_keys(),
},
language_models={
account_language_create_models.PREFIX_URL: account_language_create_models_as_dict,
},
)
update_page_info = PageInfo(
name=f"{cluster_name}",
url=f"/update?site={cluster_name}",
icon="Building",
instructions={
str(update_key): {
"validation": {
"store": True,
"url": "/validations/validation",
"data": {"event_code": f"{prefix}/update", "asked_field": "validation"},
},
"headers": {
"store": True,
"url": "/validations/header",
"data": {"event_code": f"{prefix}/update", "asked_field": "headers"},
},
},
},
page_info={
"page": {
"en": "Account Records updating for user all types account information",
"tr": "Kullanıcı tüm hesap bilgilerine ulaşmak için Hesap Kayıtları güncelle",
},
},
endpoints={
str(update_key): AccountRecordsUpdateEventMethods.retrieve_all_event_keys(),
},
language_models={
account_language_update_form_models.PREFIX_URL: account_language_update_form_models_as_dict,
},
)
account_page_info = {
f"/dashboard?site={cluster_name}": dashboard_page_info,
f"/create?site={cluster_name}": create_page_info,
f"/update?site={cluster_name}": update_page_info,
}

View File

View File

@ -0,0 +1,10 @@
responses = {
"LOGIN_SELECT": {
"tr": {
"": "",
},
"en": {
"": "",
},
},
}

View File

@ -0,0 +1,177 @@
from ApiLayers.AllConfigs.Redis.configs import (
RedisValidationKeysAction,
RedisValidationKeys,
)
from ApiLayers.AllConfigs.main import LanguageConfig
from Events.Engine.set_defaults.category_cluster_models import CategoryClusterController
from Services.Redis.Actions.actions import RedisActions
class SetDefaultLanguageModelsRedis:
std_out: str = ""
def __init__(
self,
set_response_languages_list: list[dict],
set_errors_languages_list: list[dict],
):
self.responses_list: list[dict] = set_response_languages_list
self.errors_list: list[dict] = set_errors_languages_list
def __str__(self):
return f"\nPrepareLanguageModels:\n\n{self.std_out}"
def set_all(self):
# RedisActions.delete(list_keys=["*"])
RedisActions.delete(list_keys=[f"{RedisValidationKeys.LANGUAGE_MODELS}:*"])
for response in self.responses_list:
for lang in list(LanguageConfig.SUPPORTED_LANGUAGES):
for code, dict_to_set in response.items():
# [SAVE]REDIS => LANGUAGE_MODELS:STATIC:RESPONSES:{ResponseCode}:tr = {...}
set_key = (
f"{RedisValidationKeysAction.static_response_key}:{code}:{lang}"
)
RedisActions.set_json(list_keys=[set_key], value=dict_to_set[lang])
self.std_out += f"Language Response Models are set to Redis\n"
for response in self.errors_list:
for lang in list(LanguageConfig.SUPPORTED_LANGUAGES):
for code, dict_to_set in response.items():
# [SAVE]REDIS => LANGUAGE_MODELS:STATIC:ERRORCODES:{ErrorCode}:en = {...}
set_key = f"{RedisValidationKeysAction.static_error_code_key}:{code}:{lang}"
RedisActions.set_json(list_keys=[set_key], value=dict_to_set[lang])
self.std_out += f"Language Error Models are set to Redis\n"
class SetClusterLanguageModelsRedis:
std_out: str = ""
events_lm_dict: dict[str, dict[str, dict]] = {}
events_rq_dict: dict[str, dict[str, dict]] = {}
events_rs_dict: dict[str, dict[str, dict]] = {}
def __init__(self, cluster_controller_group: CategoryClusterController):
self.cluster_controller_group = cluster_controller_group
def __str__(self):
return f"\nPrepareLanguageModels:\n\n{self.std_out}"
@staticmethod
def merge_language_dicts(list_of_lang_models: list[dict]):
"""
Merges the language models of the events to a single dictionary.
"""
merged_lang_models: dict[str, dict] = {}
for lang_model in list_of_lang_models:
for lang in list(LanguageConfig.SUPPORTED_LANGUAGES):
if not lang_model.get(lang, None):
raise ValueError(
f"Language model for {lang} not found in {lang_model}"
)
if lang not in merged_lang_models:
merged_lang_models[lang] = lang_model[lang]
else:
merged_lang_models[lang].update(lang_model[lang])
return merged_lang_models
def set_models_from_cluster(self):
"""
iterate(ClusterToMethod) to set all models by pairing function codes
"""
for cluster_control in self.cluster_controller_group.imports:
self.std_out += f"Setting models from cluster : {cluster_control.name}\n"
for endpoint in cluster_control.category_cluster.ENDPOINTS.values():
for key_event, event in endpoint.EVENTS.items():
merged_language_dict = self.merge_language_dicts(
event.LANGUAGE_MODELS
)
request_validation = getattr(
event.REQUEST_VALIDATOR, "model_fields", None
)
response_validation = getattr(
event.RESPONSE_VALIDATOR, "model_fields", None
)
objects_missing = bool(request_validation) and bool(
merged_language_dict
)
if not objects_missing:
continue
if merged_language_dict:
self.events_lm_dict[key_event] = merged_language_dict
if request_validation:
self.events_rq_dict[key_event] = request_validation
if response_validation:
self.events_rs_dict[key_event] = response_validation
self.std_out += f"Request/Response/Language validation model is set {key_event}\n"
def set_all(self):
"""
Set all language models from cluster list by pairing event code and models
"""
self.set_models_from_cluster()
if self.events_lm_dict and self.events_rq_dict:
"""
[SAVE]REDIS => LANGUAGE_MODELS:DYNAMIC:HEADERS:REQUEST:{FunctionCode}:tr = {...}
Get Request BaseModel pydantic model_fields of each event and set headers which are included in model_fields
"""
for lang in list(
LanguageConfig.SUPPORTED_LANGUAGES
): # Iterate(languages ["tr", "en"])
for key_field in self.events_rq_dict.keys(): # Iterate(function_code)
request_model = self.events_rq_dict[key_field]
if not request_model:
self.std_out += (
f"Request validation model not found for {key_field}\n"
)
continue
if (
key_field not in self.events_rq_dict
or key_field not in self.events_lm_dict
):
self.std_out += (
f"Request language model are missing {key_field}\n"
)
continue
value_to_set = {}
set_key = f"{RedisValidationKeysAction.dynamic_header_request_key}:{key_field}:{lang}"
for key in request_model.keys():
value_to_set[key] = self.events_lm_dict[key_field][lang][key]
RedisActions.set_json(list_keys=[set_key], value=value_to_set)
self.std_out += f"Language Request Headers are set to Redis\n"
if self.events_lm_dict and self.events_rs_dict:
"""
[SAVE]REDIS => LANGUAGE_MODELS:DYNAMIC:HEADERS:RESPONSE:{FunctionCode}:en = {...}
Get Response BaseModel pydantic model_fields of each event and set headers which are included in model_fields
"""
for lang in list(
LanguageConfig.SUPPORTED_LANGUAGES
): # Iterate(languages ["tr", "en"])
for key_field in self.events_rs_dict.keys(): # Iterate(function_code)
response_model = self.events_rs_dict[key_field]
if not response_model:
self.std_out += (
f"Response validation model not found for {key_field}\n"
)
continue
if (
key_field not in self.events_rs_dict
or key_field not in self.events_lm_dict
):
self.std_out += (
f"Response language model are missing {key_field}\n"
)
continue
value_to_set = {}
set_key = f"{RedisValidationKeysAction.dynamic_header_response_key}:{key_field}:{lang}"
for key in response_model.keys():
value_to_set[key] = self.events_lm_dict[key_field][lang][key]
RedisActions.set_json(list_keys=[set_key], value=value_to_set)
self.std_out += f"Language Response Headers are set to Redis\n"

View File

@ -0,0 +1,26 @@
from typing import Optional
from Services.Redis import RedisActions
from ApiLayers.AllConfigs.Redis.configs import RedisValidationKeysAction
class StaticValidationRetriever:
lang: str = "tr"
code: str = ""
def __init__(self, lang: str, code: str):
self.lang = lang
self.code = code
@property
def response(self) -> Optional[dict]:
language_model = RedisActions.get_json(
list_keys=[
RedisValidationKeysAction.static_response_key,
self.code,
self.lang,
]
)
if language_model.status:
return language_model.first
return {"message": f"{self.code} -> Language model not found"}

View File

@ -0,0 +1,14 @@
from .token_event_middleware import TokenEventMiddleware
from .auth_middleware import (
LoggerTimingMiddleware,
RequestTimingMiddleware,
MiddlewareModule,
)
__all__ = [
"TokenEventMiddleware",
"RequestTimingMiddleware",
"MiddlewareModule",
"LoggerTimingMiddleware",
]

View File

@ -0,0 +1,175 @@
"""
Authentication and Authorization middleware for FastAPI applications.
This module provides authentication decorator for protecting endpoints
and a middleware for request timing measurements.
"""
import inspect
from time import perf_counter
from typing import Callable
from functools import wraps
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from ApiLayers.ApiLibrary.common.line_number import get_line_number_for_error
from ApiLayers.ApiValidations.Custom.wrapper_contexts import AuthContext
from ApiLayers.ErrorHandlers.ErrorHandlers.api_exc_handler import HTTPExceptionApi
from ApiLayers.AllConfigs.Token.config import Auth
from ApiLayers.ApiServices.Token.token_handler import TokenService
class MiddlewareModule:
"""
Middleware module for handling authentication and request timing.
"""
@staticmethod
def get_user_from_request(request: Request) -> dict:
"""
Get authenticated token context from request.
Args:
request: FastAPI request object
Returns:
AuthContext: Context containing the authenticated token data
Raises:
HTTPExceptionApi: If token is missing, invalid, or user not found
"""
# Get token and validate - will raise HTTPExceptionApi if invalid
redis_token = TokenService.get_access_token_from_request(request=request)
# Get token context - will validate token and raise appropriate errors
token_context = TokenService.get_object_via_access_key(access_token=redis_token)
if not token_context:
raise HTTPExceptionApi(
error_code="USER_NOT_FOUND",
lang="tr",
loc=get_line_number_for_error(),
sys_msg="TokenService: Token Context couldnt retrieved from redis",
)
return token_context
@classmethod
def auth_required(cls, func: Callable) -> Callable:
"""
Decorator for protecting FastAPI endpoints with authentication.
Usage:
@router.get("/protected")
@MiddlewareModule.auth_required
async def protected_endpoint(request: Request):
auth = protected_endpoint.auth # Access auth context
if auth.is_employee:
# Handle employee logic
employee_id = auth.token_context.employee_id
else:
# Handle occupant logic
occupant_id = auth.token_context.occupant_id
return {"user_id": auth.user_id}
Args:
func: The FastAPI route handler function to protect
Returns:
Callable: Wrapped function that checks authentication before execution
Raises:
HTTPExceptionApi: If authentication fails
"""
@wraps(func)
async def wrapper(request: Request, *args, **kwargs):
# Get and validate token context from request
endpoint_url = str(request.url.path)
token_context = cls.get_user_from_request(request=request)
auth_context = AuthContext(
auth=token_context, url=endpoint_url, request=request
)
# Set auth context on the wrapper function itself
setattr(func, "auth_context", auth_context)
setattr(wrapper, "auth_context", auth_context)
# Call the original endpoint function
if inspect.iscoroutinefunction(func):
result = await func(request, *args, **kwargs)
else:
result = func(request, *args, **kwargs)
# Set auth context on the wrapper function itself
setattr(func, "auth_context", auth_context)
setattr(wrapper, "auth_context", auth_context)
return result
return wrapper
class RequestTimingMiddleware(BaseHTTPMiddleware):
"""
Middleware for measuring and logging request timing.
Only handles timing, no authentication.
"""
async def dispatch(self, request: Request, call_next: Callable) -> Response:
"""
Process each request through the middleware.
Args:
request: FastAPI request object
call_next: Next middleware in the chain
Returns:
Response: Processed response with timing headers
"""
start_time = perf_counter()
# Process the request
response = await call_next(request)
# Add timing information to response headers
end_time = perf_counter()
elapsed = (end_time - start_time) * 1000 # Convert to milliseconds
response.headers.update(
{
"request-start": f"{start_time:.6f}",
"request-end": f"{end_time:.6f}",
"request-duration": f"{elapsed:.2f}ms",
}
)
return response
class LoggerTimingMiddleware(BaseHTTPMiddleware):
"""
Middleware for measuring and logging request timing.
Only handles timing, no authentication.
"""
async def dispatch(self, request: Request, call_next: Callable) -> Response:
# Log the request
import arrow
headers = dict(request.headers)
response = await call_next(request)
# Log the response
print(
"Loggers :",
{
"url": request.url,
"method": request.method,
"access_token": headers.get(Auth.ACCESS_TOKEN_TAG, ""),
"referer": headers.get("referer", ""),
"origin": headers.get("origin", ""),
"user-agent": headers.get("user-agent", ""),
"datetime": arrow.now().format("YYYY-MM-DD HH:mm:ss ZZ"),
"status_code": response.status_code,
},
)
return response

Some files were not shown because too many files have changed in this diff Show More